text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import React from 'react'; import ReactDOM from 'react-dom'; import * as d3 from 'd3'; import {kde, probabilitiesOfSuperiority, summaryStatistics, regression, RegressionResults, Summary} from './lib/statistics'; import {LocationsWithTileID} from './lib/locations_with_tile_id'; import type {ScaleBand, ScaleLinear} from 'd3'; const versionColor = d3.scaleOrdinal(['#1b9e77', '#7570b3', '#d95f02']); const formatSample = d3.format('.3r'); function identity(x) { return x; } function translateX(x) { return `translate(${x + 0.5},0)`; } function translateY(y) { return `translate(0,${y + 0.5})`; } function number(scale) { return function(d) { return +scale(d); }; } function center(scale) { let offset = Math.max(0, scale.bandwidth() - 1) / 2; // Adjust for 0.5px offset. if (scale.round()) offset = Math.round(offset); return function(d) { return +scale(d) + offset; }; } type AxisProps = { scale: ScaleBand<string> | ScaleLinear<number, number>; orientation: string; ticks?: number | (number | string)[]; tickValues?: number[]; tickFormat?: (n: number | { valueOf(): number; }) => string; tickSize?: number; tickSizeInner?: number; tickSizeOuter?: number; tickPadding?: number; transform?: string; } class Axis extends React.Component<AxisProps, {}> { render() { const scale = this.props.scale; const orient = this.props.orientation || 'left'; const tickArguments = this.props.ticks ? [].concat(this.props.ticks) : []; const tickValues = this.props.tickValues || null; const tickFormat = this.props.tickFormat || null; const tickSizeInner = this.props.tickSize || this.props.tickSizeInner || 6; const tickSizeOuter = this.props.tickSize || this.props.tickSizeOuter || 6; const tickPadding = this.props.tickPadding || 3; const k = orient === 'top' || orient === 'left' ? -1 : 1; const x = orient === 'left' || orient === 'right' ? 'x' : 'y'; const transform = orient === 'top' || orient === 'bottom' ? translateX : translateY; const values = tickValues == null ? ((scale as ScaleLinear<number, number>).ticks ? (scale as ScaleLinear<number, number>).ticks(...tickArguments) : scale.domain()) : tickValues; const format = tickFormat == null ? ((scale as ScaleLinear<number, number>).tickFormat ? (scale as ScaleLinear<number, number>).tickFormat(...tickArguments) : identity) : tickFormat; const spacing = Math.max(tickSizeInner, 0) + tickPadding; const range = scale.range(); const range0 = +range[0] + 0.5; const range1 = +range[range.length - 1] + 0.5; const position = ((scale as ScaleBand<string>).bandwidth ? center : number)(scale.copy()); return ( <g fill='none' fontSize={10} fontFamily='sans-serif' textAnchor={orient === 'right' ? 'start' : orient === 'left' ? 'end' : 'middle'} transform={this.props.transform}> <path className='domain' stroke='#000' d={orient === 'left' || orient === 'right' ? `M${k * tickSizeOuter},${range0}H0.5V${range1}H${k * tickSizeOuter}` : `M${range0},${k * tickSizeOuter}V0.5H${range1}V${k * tickSizeOuter}`} /> {values.map((d, i) => <g key={i} className='tick' transform={transform(position(d))}> <line stroke='#000' {...{[`${x}2`]: k * tickSizeInner}}/> <text fill='#000' dy={orient === 'top' ? '0em' : orient === 'bottom' ? '0.71em' : '0.32em'} {...{[x]: k * spacing}}>{format(d)}</text> </g> )} {this.props.children} </g> ); } } type Version = { name: string; status: string; samples: number[]; density: [number, number][]; summary: Summary; regression: RegressionResults; error: Error; } type StatisticsPlotProps = { versions: Version[]; } type StatisticsPlotState = { width: number; } class StatisticsPlot extends React.Component<StatisticsPlotProps, StatisticsPlotState> { constructor(props) { super(props); this.state = {width: 100}; } render() { const margin = {top: 0, right: 20, bottom: 20, left: 0}; const width = this.state.width - margin.left - margin.right; const height = 400 - margin.top - margin.bottom; const kdeWidth = 100; const summaries = this.props.versions .filter(v => v.status === 'ended') .map(v => v.summary); const t = d3.scaleLinear() .domain([ d3.min(summaries.map(s => s.min)), d3.max(summaries.map(s => Math.min(s.max, s.q2 + 3 * s.iqr))) ]) .range([height, 0]) .clamp(true) .nice(); const b = d3.scaleBand() .domain(this.props.versions.map(v => v.name)) .range([kdeWidth + 20, width]) .paddingOuter(0.15) .paddingInner(0.3); const versions = this.props.versions.map(v => ({ name: v.name, samples: v.samples, summary: v.summary, density: kde(v.samples, v.summary, t.ticks(50)) })); const p = d3.scaleLinear() .domain([0, d3.max(versions.map(v => d3.max(v.density, d => d[1])))]) .range([0, kdeWidth]); const line = d3.line() .curve(d3.curveBasis) .y(d => t(d[0])) .x(d => p(d[1])); return ( <svg width="100%" height={height + margin.top + margin.bottom} style={{overflow: 'visible'}} // Old API that is not advised anymore ref={(ref) => { (this as any).ref = ref; }}> <defs> <g id="up-arrow"> <path transform="translate(-6, -2)" style={{stroke: 'inherit', fill: 'inherit'}} d="M2,10 L6,2 L10,10"></path> </g> </defs> <g transform={`translate(${margin.left},${margin.top})`}> <Axis orientation="bottom" scale={p} ticks={[2, '%']} transform={`translate(0,${height})`}> </Axis> <Axis orientation="left" scale={t} tickFormat={formatSample}> <text fill='#000' textAnchor="end" y={6} transform="rotate(-90)" dy=".71em">Time (ms)</text> </Axis> {versions.map((v, i) => { if (v.samples.length === 0) return null; const bandwidth = b.bandwidth(); const color = versionColor(v.name); const scale = d3.scaleLinear() .domain([0, v.samples.length]) .range([0, bandwidth]); const { mean, trimmedMean, q1, q2, q3, min, max, argmin, argmax } = v.summary; const tMax = t.domain()[1]; return <g key={i}> <path fill="none" stroke={color} strokeWidth={2} strokeOpacity={0.7} d={line(v.density)} /> <g transform={`translate(${b(v.name)},0)`}> {v.samples.map((d, i) => <circle key={i} fill={color} cx={scale(i)} cy={t(d)} r={i === argmin || i === argmax ? 2 : 1} style={{ fillOpacity: d < tMax ? 1 : 0 }} /> )} {v.samples.filter(d => d >= tMax) .map((d, i) => <use key={i} href="#up-arrow" x={scale(i)} y={t(d)} style={{ stroke:color, strokeWidth: i === argmin || i === argmax ? 2 : 1, fill: 'rgba(200, 0, 0, 0.5)' }} /> ) } <line // quartiles x1={bandwidth / 2} x2={bandwidth / 2} y1={t(q1)} y2={t(q3)} stroke={color} strokeWidth={bandwidth} strokeOpacity={0.5} /> <line // median x1={bandwidth / 2} x2={bandwidth / 2} y1={t(q2) - 0.5} y2={t(q2) + 0.5} stroke={color} strokeWidth={bandwidth} strokeOpacity={1} /> <use href="#up-arrow" // mean style={{stroke: color, fill: color, fillOpacity: 0.4}} transform={mean >= tMax ? 'translate(-10, 0)' : `translate(-5, ${t(mean)}) rotate(90)`} x={0} y={0} /> <use href="#up-arrow" // trimmed mean style={{stroke: color, fill: color}} transform={`translate(-5, ${t(trimmedMean)}) rotate(90)`} x={0} y={0} /> {[mean, trimmedMean].map((d, i) => <text // left key={i} dx={-16} dy='.3em' x={0} y={t(d)} textAnchor='end' fontSize={10} fontFamily='sans-serif'>{formatSample(d)}</text> )} {[[argmin, min], [argmax, max]].map((d, i) => <text // extent key={i} dx={0} dy={i === 0 ? '1.3em' : '-0.7em'} x={scale(d[0])} y={t(d[1])} textAnchor='middle' fontSize={10} fontFamily='sans-serif'>{formatSample(d[1])}</text> )} {[q1, q2, q3].map((d, i) => <text // right key={i} dx={6} dy='.3em' x={bandwidth} y={t(d)} textAnchor='start' fontSize={10} fontFamily='sans-serif'>{formatSample(d)}</text> )} </g> </g>; })} </g> </svg> ); } componentDidMount() { // Old API that is not advised anymore this.setState({width: (this as any).ref.clientWidth}); } } type RegressionPlotProps = { versions: Version[]; } type RegressionPlotState = { width: number; } class RegressionPlot extends React.Component<RegressionPlotProps, RegressionPlotState> { constructor(props) { super(props); this.state = {width: 100}; } render() { const margin = {top: 10, right: 20, bottom: 30, left: 0}; const width = this.state.width - margin.left - margin.right; const height = 200 - margin.top - margin.bottom; const versions = this.props.versions.filter(version => version.regression); const x = d3.scaleLinear() .domain([0, d3.max(versions.map(version => d3.max(version.regression.data, d => d[0])))]) .range([0, width]) .nice(); const y = d3.scaleLinear() .domain([0, d3.max(versions.map(version => d3.max(version.regression.data, d => d[1])))]) .range([height, 0]) .nice(); const line = d3.line() .x(d => x(d[0])) .y(d => y(d[1])); return ( <svg width="100%" height={height + margin.top + margin.bottom} style={{overflow: 'visible'}} // Old API that is not advised anymore ref={(ref) => { (this as any).ref = ref; }}> <g transform={`translate(${margin.left},${margin.top})`}> <Axis orientation="bottom" scale={x} transform={`translate(0,${height})`}> <text fill='#000' textAnchor="end" y={-6} x={width}>Iterations</text> </Axis> <Axis orientation="left" scale={y} ticks={4} tickFormat={formatSample}> <text fill='#000' textAnchor="end" y={6} transform="rotate(-90)" dy=".71em">Time (ms)</text> </Axis> {versions.map((v, i) => <g key={i} fill={versionColor(v.name)} fillOpacity="0.7"> {v.regression.data.map(([a, b], i) => <circle key={i} r="2" cx={x(a)} cy={y(b)}/> )} <path stroke={versionColor(v.name)} strokeWidth={1} strokeOpacity={0.5} d={line(v.regression.data.map(d => [ d[0], d[0] * v.regression.slope + v.regression.intercept ]))} /> </g> )} </g> </svg> ); } componentDidMount() { // Old API that is not advised anymore this.setState({width: (this as any).ref.clientWidth}); } } type BenchmarkStatisticProps = { status: string; error: Error; statistic: (version: Version) => any; version: Version; } class BenchmarkStatistic extends React.Component<BenchmarkStatisticProps, {}> { render() { switch (this.props.status) { case 'waiting': return <p className="quiet"></p>; case 'running': return <p>Running...</p>; case 'error': case 'errored': return <p>{this.props.error.message}</p>; default: return this.props.statistic(this.props.version); } } } type BenchmarkRowProps = { name: string; location: LocationsWithTileID; versions: Version[]; } class BenchmarkRow extends React.Component<BenchmarkRowProps, {}> { render() { const endedCount = this.props.versions.filter(version => version.status === 'ended').length; let main; let current; if (/main/.test(this.props.versions[0].name)) { [main, current] = this.props.versions; } else { [current, main] = this.props.versions; } let change; let pInferiority; if (endedCount === 2) { const delta = current.summary.trimmedMean - main.summary.trimmedMean; // Use "Cohen's d" (modified to used the trimmed mean/sd) to decide // how much to emphasize difference between means // https://en.wikipedia.org/wiki/Effect_size#Cohen.27s_d const pooledDeviation = Math.sqrt( ( (main.samples.length - 1) * Math.pow(main.summary.windsorizedDeviation, 2) + (current.samples.length - 1) * Math.pow(current.summary.windsorizedDeviation, 2) ) / (main.samples.length + current.samples.length - 2) ); const d = delta / pooledDeviation; const {superior, inferior} = probabilitiesOfSuperiority(main.samples, current.samples); change = <span className={d < 0.2 ? 'quiet' : d < 1.5 ? '' : 'strong'}>( {delta > 0 ? '+' : ''}{formatSample(delta)} ms / {d.toFixed(1)} std devs )</span>; const comparison = inferior > superior ? 'SLOWER' : 'faster'; const probability = Math.max(inferior, superior); pInferiority = <p className={`center ${probability > 0.90 ? 'strong' : 'quiet'}`}> {(probability * 100).toFixed(0)}% chance that a random <svg width={8} height={8}><circle fill={versionColor(current.name)} cx={4} cy={4} r={4} /></svg> sample is {comparison} than a random <svg width={8} height={8}><circle fill={versionColor(main.name)} cx={4} cy={4} r={4} /></svg> sample. </p>; } return ( <div className="col12 clearfix space-bottom"> <table className="fixed space-bottom"> <tbody> <tr><th><h2 className="col4"><a href={`#${this.props.name}`} onClick={this.reload}>{this.props.name}</a></h2></th> {this.props.versions.map(version => <th style={{color: versionColor(version.name)}} key={version.name}>{version.name}</th>)}</tr> {this.props.location && <tr> <th><p style={{color: '#1287A8'}}>{this.props.location.description}</p></th> <th><p style={{color: '#1287A8'}}>Zoom Level: {this.props.location.zoom}</p></th> <th><p style={{color: '#1287A8'}}>Lat: {this.props.location.center[1]} Lng: {this.props.location.center[0]}</p></th> </tr>} {this.renderStatistic('(20% trimmed) Mean', (version) => <p> {formatSample(version.summary.trimmedMean)} ms {current && version.name === current.name && change} </p>)} {this.renderStatistic('(Windsorized) Deviation', (version) => <p>{formatSample(version.summary.windsorizedDeviation)} ms</p>)} {this.renderStatistic('R² Slope / Correlation', (version) => <p>{formatSample(version.regression.slope)} ms / {version.regression.correlation.toFixed(3)} { version.regression.correlation < 0.9 ? '\u2620\uFE0F' : version.regression.correlation < 0.99 ? '\u26A0\uFE0F' : ''}</p>)} {this.renderStatistic('Minimum', (version) => <p>{formatSample(version.summary.min)} ms</p>)} {pInferiority && <tr><td colSpan={3}>{pInferiority}</td></tr>} </tbody> </table> {endedCount > 0 && <StatisticsPlot versions={this.props.versions}/>} {endedCount > 0 && <RegressionPlot versions={this.props.versions}/>} </div> ); } renderStatistic(title: string, statistic: (version: Version) => any) { return ( <tr> <th>{title}</th> {this.props.versions.map(version => <td key={version.name}><BenchmarkStatistic statistic={statistic} status={version.status} error={version.error} version={version}/></td> )} </tr> ); } reload() { location.reload(); } } type BenchmarksTableProps = { finished: boolean; benchmarks: BenchmarkRowProps[]; } class BenchmarksTable extends React.Component<BenchmarksTableProps, {}> { render() { return ( <div style={{width: 960, margin: '2em auto'}}> <h1 className="space-bottom1">MapLibre GL JS Benchmarks – { this.props.finished ? <span>Finished</span> : <span>Running</span>}</h1> {this.props.benchmarks.map((benchmark, i) => { return <BenchmarkRow key={`${benchmark.name}-${i}`} {...benchmark}/>; })} </div> ); } } function updateUI(benchmarks, finished?) { finished = !!finished; ReactDOM.render( <BenchmarksTable benchmarks={benchmarks} finished={finished}/>, document.getElementById('benchmarks') ); } export function run(benchmarks) { const filter = window.location.hash.substr(1); if (filter) benchmarks = benchmarks.filter(({name}) => name === filter); for (const benchmark of benchmarks) { for (const version of benchmark.versions) { version.status = 'waiting'; version.logs = []; version.samples = []; version.summary = {}; } } updateUI(benchmarks); let promise = Promise.resolve(); benchmarks.forEach(bench => { bench.versions.forEach(version => { promise = promise.then(() => { version.status = 'running'; updateUI(benchmarks); return version.bench.run() .then(measurements => { // scale measurements down by iteration count, so that // they represent (average) time for a single iteration const samples = measurements.map(({time, iterations}) => time / iterations); version.status = 'ended'; version.samples = samples; version.summary = summaryStatistics(samples); version.regression = regression(measurements); updateUI(benchmarks); }) .catch(error => { version.status = 'errored'; version.error = error; updateUI(benchmarks); }); }); }); }); promise = promise.then(() => { updateUI(benchmarks, true); }); }
the_stack
import { Cents, Degrees, Frequency, Seconds, Time } from "../../core/type/Units"; import { optionsFromArguments } from "../../core/util/Defaults"; import { readOnly } from "../../core/util/Interface"; import { isNumber, isString } from "../../core/util/TypeCheck"; import { Signal } from "../../signal/Signal"; import { Source } from "../Source"; import { AMOscillator } from "./AMOscillator"; import { FatOscillator } from "./FatOscillator"; import { FMOscillator } from "./FMOscillator"; import { Oscillator } from "./Oscillator"; import { generateWaveform, OmniOscillatorOptions, OmniOscillatorType, ToneOscillatorInterface, ToneOscillatorType } from "./OscillatorInterface"; import { PulseOscillator } from "./PulseOscillator"; import { PWMOscillator } from "./PWMOscillator"; export { OmniOscillatorOptions } from "./OscillatorInterface"; /** * All of the oscillator types that OmniOscillator can take on */ type AnyOscillator = Oscillator | PWMOscillator | PulseOscillator | FatOscillator | AMOscillator | FMOscillator; /** * All of the Oscillator constructor types mapped to their name. */ interface OmniOscillatorSource { "fm": FMOscillator; "am": AMOscillator; "pwm": PWMOscillator; "pulse": PulseOscillator; "oscillator": Oscillator; "fat": FatOscillator; } /** * The available oscillator types. */ export type OmniOscSourceType = keyof OmniOscillatorSource; // Conditional Types type IsAmOrFmOscillator<Osc, Ret> = Osc extends AMOscillator ? Ret : Osc extends FMOscillator ? Ret : undefined; type IsFatOscillator<Osc, Ret> = Osc extends FatOscillator ? Ret : undefined; type IsPWMOscillator<Osc, Ret> = Osc extends PWMOscillator ? Ret : undefined; type IsPulseOscillator<Osc, Ret> = Osc extends PulseOscillator ? Ret : undefined; type IsFMOscillator<Osc, Ret> = Osc extends FMOscillator ? Ret : undefined; type AnyOscillatorConstructor = new (...args: any[]) => AnyOscillator; const OmniOscillatorSourceMap: { [key in OmniOscSourceType]: AnyOscillatorConstructor } = { am: AMOscillator, fat: FatOscillator, fm: FMOscillator, oscillator: Oscillator, pulse: PulseOscillator, pwm: PWMOscillator, }; /** * OmniOscillator aggregates all of the oscillator types into one. * @example * return Tone.Offline(() => { * const omniOsc = new Tone.OmniOscillator("C#4", "pwm").toDestination().start(); * }, 0.1, 1); * @category Source */ export class OmniOscillator<OscType extends AnyOscillator> extends Source<OmniOscillatorOptions> implements Omit<ToneOscillatorInterface, "type"> { readonly name: string = "OmniOscillator"; readonly frequency: Signal<"frequency">; readonly detune: Signal<"cents">; /** * The oscillator that can switch types */ private _oscillator!: AnyOscillator; /** * the type of the oscillator source */ private _sourceType!: OmniOscSourceType; /** * @param frequency The initial frequency of the oscillator. * @param type The type of the oscillator. */ constructor(frequency?: Frequency, type?: OmniOscillatorType); constructor(options?: Partial<OmniOscillatorOptions>); constructor() { super(optionsFromArguments(OmniOscillator.getDefaults(), arguments, ["frequency", "type"])); const options = optionsFromArguments(OmniOscillator.getDefaults(), arguments, ["frequency", "type"]); this.frequency = new Signal({ context: this.context, units: "frequency", value: options.frequency, }); this.detune = new Signal({ context: this.context, units: "cents", value: options.detune, }); readOnly(this, ["frequency", "detune"]); // set the options this.set(options); } static getDefaults(): OmniOscillatorOptions { return Object.assign( Oscillator.getDefaults(), FMOscillator.getDefaults(), AMOscillator.getDefaults(), FatOscillator.getDefaults(), PulseOscillator.getDefaults(), PWMOscillator.getDefaults(), ); } /** * start the oscillator */ protected _start(time: Time): void { this._oscillator.start(time); } /** * start the oscillator */ protected _stop(time: Time): void { this._oscillator.stop(time); } protected _restart(time: Seconds): this { this._oscillator.restart(time); return this; } /** * The type of the oscillator. Can be any of the basic types: sine, square, triangle, sawtooth. Or * prefix the basic types with "fm", "am", or "fat" to use the FMOscillator, AMOscillator or FatOscillator * types. The oscillator could also be set to "pwm" or "pulse". All of the parameters of the * oscillator's class are accessible when the oscillator is set to that type, but throws an error * when it's not. * @example * const omniOsc = new Tone.OmniOscillator().toDestination().start(); * omniOsc.type = "pwm"; * // modulationFrequency is parameter which is available * // only when the type is "pwm". * omniOsc.modulationFrequency.value = 0.5; */ get type(): OmniOscillatorType { let prefix = ""; if (["am", "fm", "fat"].some(p => this._sourceType === p)) { prefix = this._sourceType; } return prefix + this._oscillator.type as OmniOscillatorType; } set type(type) { if (type.substr(0, 2) === "fm") { this._createNewOscillator("fm"); this._oscillator = this._oscillator as FMOscillator; this._oscillator.type = type.substr(2) as ToneOscillatorType; } else if (type.substr(0, 2) === "am") { this._createNewOscillator("am"); this._oscillator = this._oscillator as AMOscillator; this._oscillator.type = type.substr(2) as ToneOscillatorType; } else if (type.substr(0, 3) === "fat") { this._createNewOscillator("fat"); this._oscillator = this._oscillator as FatOscillator; this._oscillator.type = type.substr(3) as ToneOscillatorType; } else if (type === "pwm") { this._createNewOscillator("pwm"); this._oscillator = this._oscillator as PWMOscillator; } else if (type === "pulse") { this._createNewOscillator("pulse"); } else { this._createNewOscillator("oscillator"); this._oscillator = this._oscillator as Oscillator; this._oscillator.type = (type as ToneOscillatorType); } } /** * The value is an empty array when the type is not "custom". * This is not available on "pwm" and "pulse" oscillator types. * See [[Oscillator.partials]] */ get partials(): number[] { return this._oscillator.partials; } set partials(partials) { if (!this._getOscType(this._oscillator, "pulse") && !this._getOscType(this._oscillator, "pwm")) { this._oscillator.partials = partials; } } get partialCount(): number { return this._oscillator.partialCount; } set partialCount(partialCount) { if (!this._getOscType(this._oscillator, "pulse") && !this._getOscType(this._oscillator, "pwm")) { this._oscillator.partialCount = partialCount; } } set(props: Partial<OmniOscillatorOptions>): this { // make sure the type is set first if (Reflect.has(props, "type") && props.type) { this.type = props.type; } // then set the rest super.set(props); return this; } /** * connect the oscillator to the frequency and detune signals */ private _createNewOscillator(oscType: OmniOscSourceType): void { if (oscType !== this._sourceType) { this._sourceType = oscType; const OscConstructor = OmniOscillatorSourceMap[oscType]; // short delay to avoid clicks on the change const now = this.now(); if (this._oscillator) { const oldOsc = this._oscillator; oldOsc.stop(now); // dispose the old one this.context.setTimeout(() => oldOsc.dispose(), this.blockTime); } this._oscillator = new OscConstructor({ context: this.context, }); this.frequency.connect(this._oscillator.frequency); this.detune.connect(this._oscillator.detune); this._oscillator.connect(this.output); this._oscillator.onstop = () => this.onstop(this); if (this.state === "started") { this._oscillator.start(now); } } } get phase(): Degrees { return this._oscillator.phase; } set phase(phase) { this._oscillator.phase = phase; } /** * The source type of the oscillator. * @example * const omniOsc = new Tone.OmniOscillator(440, "fmsquare"); * console.log(omniOsc.sourceType); // 'fm' */ get sourceType(): OmniOscSourceType { return this._sourceType; } set sourceType(sType) { // the basetype defaults to sine let baseType = "sine"; if (this._oscillator.type !== "pwm" && this._oscillator.type !== "pulse") { baseType = this._oscillator.type; } // set the type if (sType === "fm") { this.type = "fm" + baseType as OmniOscillatorType; } else if (sType === "am") { this.type = "am" + baseType as OmniOscillatorType; } else if (sType === "fat") { this.type = "fat" + baseType as OmniOscillatorType; } else if (sType === "oscillator") { this.type = baseType as OmniOscillatorType; } else if (sType === "pulse") { this.type = "pulse"; } else if (sType === "pwm") { this.type = "pwm"; } } private _getOscType<SourceType extends OmniOscSourceType>( osc: AnyOscillator, sourceType: SourceType, ): osc is OmniOscillatorSource[SourceType] { return osc instanceof OmniOscillatorSourceMap[sourceType]; } /** * The base type of the oscillator. See [[Oscillator.baseType]] * @example * const omniOsc = new Tone.OmniOscillator(440, "fmsquare4"); * console.log(omniOsc.sourceType, omniOsc.baseType, omniOsc.partialCount); */ get baseType(): OscillatorType | "pwm" | "pulse" { return this._oscillator.baseType; } set baseType(baseType) { if (!this._getOscType(this._oscillator, "pulse") && !this._getOscType(this._oscillator, "pwm") && baseType !== "pulse" && baseType !== "pwm") { this._oscillator.baseType = baseType; } } /** * The width of the oscillator when sourceType === "pulse". * See [[PWMOscillator.width]] */ get width(): IsPulseOscillator<OscType, Signal<"audioRange">> { if (this._getOscType(this._oscillator, "pulse")) { return this._oscillator.width as IsPulseOscillator<OscType, Signal<"audioRange">>; } else { return undefined as IsPulseOscillator<OscType, Signal<"audioRange">>; } } /** * The number of detuned oscillators when sourceType === "fat". * See [[FatOscillator.count]] */ get count(): IsFatOscillator<OscType, number> { if (this._getOscType(this._oscillator, "fat")) { return this._oscillator.count as IsFatOscillator<OscType, number>; } else { return undefined as IsFatOscillator<OscType, number>; } } set count(count) { if (this._getOscType(this._oscillator, "fat") && isNumber(count)) { this._oscillator.count = count; } } /** * The detune spread between the oscillators when sourceType === "fat". * See [[FatOscillator.count]] */ get spread(): IsFatOscillator<OscType, Cents> { if (this._getOscType(this._oscillator, "fat")) { return this._oscillator.spread as IsFatOscillator<OscType, Cents>; } else { return undefined as IsFatOscillator<OscType, Cents>; } } set spread(spread) { if (this._getOscType(this._oscillator, "fat") && isNumber(spread)) { this._oscillator.spread = spread; } } /** * The type of the modulator oscillator. Only if the oscillator is set to "am" or "fm" types. * See [[AMOscillator]] or [[FMOscillator]] */ get modulationType(): IsAmOrFmOscillator<OscType, ToneOscillatorType> { if (this._getOscType(this._oscillator, "fm") || this._getOscType(this._oscillator, "am")) { return this._oscillator.modulationType as IsAmOrFmOscillator<OscType, ToneOscillatorType>; } else { return undefined as IsAmOrFmOscillator<OscType, ToneOscillatorType>; } } set modulationType(mType) { if ((this._getOscType(this._oscillator, "fm") || this._getOscType(this._oscillator, "am")) && isString(mType)) { this._oscillator.modulationType = mType; } } /** * The modulation index when the sourceType === "fm" * See [[FMOscillator]]. */ get modulationIndex(): IsFMOscillator<OscType, Signal<"positive">> { if (this._getOscType(this._oscillator, "fm")) { return this._oscillator.modulationIndex as IsFMOscillator<OscType, Signal<"positive">>; } else { return undefined as IsFMOscillator<OscType, Signal<"positive">>; } } /** * Harmonicity is the frequency ratio between the carrier and the modulator oscillators. * See [[AMOscillator]] or [[FMOscillator]] */ get harmonicity(): IsAmOrFmOscillator<OscType, Signal<"positive">> { if (this._getOscType(this._oscillator, "fm") || this._getOscType(this._oscillator, "am")) { return this._oscillator.harmonicity as IsAmOrFmOscillator<OscType, Signal<"positive">>; } else { return undefined as IsAmOrFmOscillator<OscType, Signal<"positive">>; } } /** * The modulationFrequency Signal of the oscillator when sourceType === "pwm" * see [[PWMOscillator]] * @min 0.1 * @max 5 */ get modulationFrequency(): IsPWMOscillator<OscType, Signal<"frequency">> { if (this._getOscType(this._oscillator, "pwm")) { return this._oscillator.modulationFrequency as IsPWMOscillator<OscType, Signal<"frequency">>; } else { return undefined as IsPWMOscillator<OscType, Signal<"frequency">>; } } async asArray(length = 1024): Promise<Float32Array> { return generateWaveform(this, length); } dispose(): this { super.dispose(); this.detune.dispose(); this.frequency.dispose(); this._oscillator.dispose(); return this; } }
the_stack
import * as fs from 'fs'; import { inspect, promisify } from 'util'; import { Suite } from '../Suite'; import { AbstractRunnable, RunnableReloadResult } from '../AbstractRunnable'; import { GoogleTestTest } from './GoogleTestTest'; import { Parser } from 'xml2js'; import { RunnableProperties } from '../RunnableProperties'; import { SharedVariables } from '../SharedVariables'; import { RunningRunnable, ProcessResult } from '../RunningRunnable'; import { AbstractTest, AbstractTestEvent } from '../AbstractTest'; import { CancellationFlag, Version } from '../Util'; import { TestGrouping } from '../TestGroupingInterface'; import { RootSuite } from '../RootSuite'; export class GoogleTestRunnable extends AbstractRunnable { public constructor( shared: SharedVariables, rootSuite: RootSuite, execInfo: RunnableProperties, private readonly _argumentPrefix: string, version: Promise<Version | undefined>, ) { super(shared, rootSuite, execInfo, 'GoogleTest', version); } private getTestGrouping(): TestGrouping { if (this.properties.testGrouping) { return this.properties.testGrouping; } else { const grouping = { groupByExecutable: this._getGroupByExecutable() }; grouping.groupByExecutable.groupByTags = { tags: [], tagFormat: '${tag}' }; return grouping; } } private async _reloadFromXml(xmlStr: string, cancellationFlag: CancellationFlag): Promise<RunnableReloadResult> { const testGrouping = this.getTestGrouping(); interface XmlObject { [prop: string]: any; //eslint-disable-line } let xml: XmlObject = {}; new Parser({ explicitArray: true }).parseString(xmlStr, (err: Error, result: Record<string, unknown>) => { if (err) { throw err; } else { xml = result; } }); const reloadResult = new RunnableReloadResult(); for (let i = 0; i < xml.testsuites.testsuite.length; ++i) { const suiteName = xml.testsuites.testsuite[i].$.name; for (let j = 0; j < xml.testsuites.testsuite[i].testcase.length; j++) { if (cancellationFlag.isCancellationRequested) return reloadResult; const testCase = xml.testsuites.testsuite[i].testcase[j]; const testName = testCase.$.name.startsWith('DISABLED_') ? testCase.$.name.substr(9) : testCase.$.name; const testNameAsId = suiteName + '.' + testCase.$.name; const typeParam: string | undefined = testCase.$.type_param; const valueParam: string | undefined = testCase.$.value_param; const file = testCase.$.file ? await this._resolveSourceFilePath(testCase.$.file) : undefined; const line = testCase.$.line ? testCase.$.line - 1 : undefined; reloadResult.add( ...(await this._createSubtreeAndAddTest( testGrouping, testNameAsId, testName, file, [suiteName], (parent: Suite) => new GoogleTestTest(this._shared, this, parent, testNameAsId, testName, typeParam, valueParam, file, line), (old: AbstractTest) => (old as GoogleTestTest).update(typeParam, valueParam, file, line), )), ); } } return reloadResult; } private async _reloadFromString( stdOutStr: string, cancellationFlag: CancellationFlag, ): Promise<RunnableReloadResult> { const testGrouping = this.getTestGrouping(); const lines = stdOutStr.split(/\r?\n/); const testGroupRe = /^([A-z][\/A-z0-9_\-]*)\.(?:\s+(#\s+TypeParam(?:\(\))?\s+=\s*(.+)))?$/; const testRe = /^\s+([A-z0-9][\/A-z0-9_\-]*)(?:\s+(#\s+GetParam(?:\(\))?\s+=\s*(.+)))?$/; let lineCount = lines.length; while (lineCount > 0 && lines[lineCount - 1].match(testRe) === null) lineCount--; let lineNum = 0; // gtest_main.cc while (lineCount > lineNum && lines[lineNum].match(testGroupRe) === null) lineNum++; if (lineCount - lineNum === 0) throw Error('Wrong test list.'); let testGroupMatch = lineCount > lineNum ? lines[lineNum].match(testGroupRe) : null; const reloadResult = new RunnableReloadResult(); while (testGroupMatch) { lineNum++; const testGroupName = testGroupMatch[1]; const suiteName = testGroupMatch[1]; const typeParam: string | undefined = testGroupMatch[3]; let testMatch = lineCount > lineNum ? lines[lineNum].match(testRe) : null; while (testMatch) { if (cancellationFlag.isCancellationRequested) return reloadResult; lineNum++; const testName = testMatch[1].startsWith('DISABLED_') ? testMatch[1].substr(9) : testMatch[1]; const valueParam: string | undefined = testMatch[3]; const testNameAsId = testGroupName + '.' + testMatch[1]; reloadResult.add( ...(await this._createSubtreeAndAddTest( testGrouping, testNameAsId, testName, undefined, [suiteName], (parent: Suite) => new GoogleTestTest( this._shared, this, parent, testNameAsId, testName, typeParam, valueParam, undefined, undefined, ), (old: AbstractTest) => (old as GoogleTestTest).update(typeParam, valueParam, undefined, undefined), )), ); testMatch = lineCount > lineNum ? lines[lineNum].match(testRe) : null; } testGroupMatch = lineCount > lineNum ? lines[lineNum].match(testGroupRe) : null; } return reloadResult; } protected async _reloadChildren(cancellationFlag: CancellationFlag): Promise<RunnableReloadResult> { const cacheFile = this.properties.path + '.TestMate.testListCache.xml'; if (this._shared.enabledTestListCaching) { try { const cacheStat = await promisify(fs.stat)(cacheFile); const execStat = await promisify(fs.stat)(this.properties.path); if (cacheStat.size > 0 && cacheStat.mtime > execStat.mtime) { this._shared.log.info('loading from cache: ', cacheFile); const xmlStr = await promisify(fs.readFile)(cacheFile, 'utf8'); return await this._reloadFromXml(xmlStr, cancellationFlag); } } catch (e) { this._shared.log.info('coudnt use cache', e); } } const args = this.properties.prependTestListingArgs.concat([ `--${this._argumentPrefix}list_tests`, `--${this._argumentPrefix}output=xml:${cacheFile}`, ]); this._shared.log.info('discovering tests', this.properties.path, args, this.properties.options.cwd); const googleTestListOutput = await this.properties.spawner.spawnAsync( this.properties.path, args, this.properties.options, 30000, ); if (googleTestListOutput.stderr && !this.properties.ignoreTestEnumerationStdErr) { this._shared.log.warn('reloadChildren -> googleTestListOutput.stderr: ', googleTestListOutput); return await this._createAndAddUnexpectedStdError(googleTestListOutput.stdout, googleTestListOutput.stderr); } else { const hasXmlFile = await promisify(fs.exists)(cacheFile); if (hasXmlFile) { const xmlStr = await promisify(fs.readFile)(cacheFile, 'utf8'); const result = await this._reloadFromXml(xmlStr, cancellationFlag); if (!this._shared.enabledTestListCaching) { fs.unlink(cacheFile, (err: Error | null) => { err && this._shared.log.warn("Couldn't remove: ", cacheFile, err); }); } return result; } else { this._shared.log.info( "Couldn't parse output file. Possibly it is an older version of Google Test framework. It is trying to parse the output", ); try { return await this._reloadFromString(googleTestListOutput.stdout, cancellationFlag); } catch (e) { this._shared.log.info('GoogleTest._reloadFromStdOut error', e, googleTestListOutput); throw e; } } } } private _getRunParamsCommon(childrenToRun: readonly Readonly<AbstractTest>[]): string[] { const execParams: string[] = []; const testNames = childrenToRun.map(c => c.testNameAsId); execParams.push(`--${this._argumentPrefix}filter=` + testNames.join(':')); execParams.push(`--${this._argumentPrefix}also_run_disabled_tests`); if (this._shared.rngSeed !== null) { execParams.push(`--${this._argumentPrefix}shuffle`); execParams.push( `--${this._argumentPrefix}random_seed=` + (this._shared.rngSeed === 'time' ? '0' : this._shared.rngSeed.toString()), ); } if (this._shared.googleTestGMockVerbose !== 'default') { execParams.push('--gmock_verbose=' + this._shared.googleTestGMockVerbose); } return execParams; } protected _getRunParamsInner(childrenToRun: readonly Readonly<AbstractTest>[]): string[] { return [`--${this._argumentPrefix}color=no`, ...this._getRunParamsCommon(childrenToRun)]; } protected _getDebugParamsInner(childrenToRun: readonly Readonly<AbstractTest>[], breakOnFailure: boolean): string[] { const colouring = this.properties.enableDebugColouring ? 'yes' : 'no'; const debugParams = [`--${this._argumentPrefix}color=${colouring}`, ...this._getRunParamsCommon(childrenToRun)]; if (breakOnFailure) debugParams.push(`--${this._argumentPrefix}break_on_failure`); return debugParams; } protected _handleProcess(testRunId: string, runInfo: RunningRunnable): Promise<void> { const data = new (class { public stdoutAndErrBuffer = ''; // no reason to separate public currentTestCaseNameFull: string | undefined = undefined; public currentChild: AbstractTest | undefined = undefined; public route: Suite[] = []; public unprocessedTestCases: string[] = []; public processedTestCases: AbstractTest[] = []; })(); const testBeginRe = /^\[ RUN \] ((.+)\.(.+))$/m; const rngSeed: number | undefined = typeof this._shared.rngSeed === 'number' ? this._shared.rngSeed : undefined; return new Promise<ProcessResult>(resolve => { const chunks: string[] = []; const processChunk = (chunk: string): void => { chunks.push(chunk); data.stdoutAndErrBuffer = data.stdoutAndErrBuffer + chunk; let invariant = 99999; do { if (runInfo.cancellationToken.isCancellationRequested) return; if (data.currentTestCaseNameFull === undefined) { const m = data.stdoutAndErrBuffer.match(testBeginRe); if (m == null) return; data.currentTestCaseNameFull = m[1]; const test = this._findTest(v => v.testNameAsId == data.currentTestCaseNameFull); if (test) { const route = [...test.route()]; this.sendMinimalEventsIfNeeded(testRunId, data.route, route); data.route = route; data.currentChild = test; this._shared.log.info('Test', data.currentChild.testNameAsId, 'has started.'); this._shared.sendTestRunEvent(data.currentChild.getStartEvent(testRunId)); } else { this._shared.log.info('TestCase not found in children', data.currentTestCaseNameFull); } data.stdoutAndErrBuffer = data.stdoutAndErrBuffer.substr(m.index!); } else { const testEndRe = new RegExp( '(?!\\[ RUN \\])\\[..........\\] ' + data.currentTestCaseNameFull.replace('.', '\\.') + '.*$', 'm', ); const m = data.stdoutAndErrBuffer.match(testEndRe); if (m == null) return; const testCase = data.stdoutAndErrBuffer.substring(0, m.index! + m[0].length); if (data.currentChild !== undefined) { this._shared.log.info('Test ', data.currentChild.testNameAsId, 'has finished.'); try { const ev = data.currentChild.parseAndProcessTestCase( testRunId, testCase, rngSeed, runInfo.timeout, undefined, ); this._shared.sendTestRunEvent(ev); data.processedTestCases.push(data.currentChild); } catch (e) { this._shared.log.error('parsing and processing test', e, data); data.currentChild.lastRunEvent = { testRunId, type: 'test', test: data.currentChild.id, state: 'errored', message: [ '😱 Unexpected error under parsing output !! Error: ' + inspect(e), 'Consider opening an issue: https://github.com/matepek/vscode-catch2-test-adapter/issues/new/choose', `Please attach the output of: "${runInfo.process.spawnfile} ${runInfo.process.spawnargs}"`, '=== Output ===', testCase, '==============', '⬇ stdoutAndErrBuffer:', data.stdoutAndErrBuffer, '⬆ stdoutAndErrBuffer', '⬇ std::cout:', runInfo.process.stdout, '⬆ std::cout', '⬇ std::cerr:', runInfo.process.stderr, '⬆ std::cerr', ].join('\n'), }; this._shared.sendTestRunEvent(data.currentChild.lastRunEvent); } } else { this._shared.log.info('Test case found without TestInfo: ', this, '; ' + testCase); data.unprocessedTestCases.push(testCase); } data.currentTestCaseNameFull = undefined; data.currentChild = undefined; // do not clear data.route data.stdoutAndErrBuffer = data.stdoutAndErrBuffer.substr(m.index! + m[0].length); } } while (data.stdoutAndErrBuffer.length > 0 && --invariant > 0); if (invariant == 0) { this._shared.log.error('invariant==0', this, runInfo, data, chunks); resolve(ProcessResult.error('Possible infinite loop of this extension')); runInfo.killProcess(); } }; runInfo.process.stdout.on('data', (chunk: Uint8Array) => processChunk(chunk.toLocaleString())); runInfo.process.stderr.on('data', (chunk: Uint8Array) => processChunk(chunk.toLocaleString())); runInfo.process.once('close', (code: number | null, signal: string | null) => { if (runInfo.cancellationToken.isCancellationRequested) { resolve(ProcessResult.ok()); } else { if (code !== null && code !== undefined) resolve(ProcessResult.createFromErrorCode(code)); else if (signal !== null && signal !== undefined) resolve(ProcessResult.createFromSignal(signal)); else resolve(ProcessResult.error('unknown sfngvdlfkxdvgn')); } }); }) .catch((reason: Error) => { // eslint-disable-next-line if ((reason as any).code === undefined) this._shared.log.exceptionS(reason); return new ProcessResult(reason); }) .then((result: ProcessResult) => { result.error && this._shared.log.info(result.error.toString(), result, runInfo, this, data); if (data.currentTestCaseNameFull !== undefined) { if (data.currentChild !== undefined) { this._shared.log.info('data.currentChild !== undefined: ', data); let ev: AbstractTestEvent; if (runInfo.cancellationToken.isCancellationRequested) { ev = data.currentChild.getCancelledEvent(testRunId, data.stdoutAndErrBuffer); } else if (runInfo.timeout !== null) { ev = data.currentChild.getTimeoutEvent(testRunId, runInfo.timeout); } else { ev = data.currentChild.getFailedEventBase(testRunId); ev.message = '😱 Unexpected error !!'; if (result.error) { ev.state = 'errored'; ev.message += '\n' + result.error.message; } ev.message += data.stdoutAndErrBuffer ? `\n\n>>>${data.stdoutAndErrBuffer}<<<` : ''; } data.currentChild.lastRunEvent = ev; this._shared.sendTestRunEvent(ev); } else { this._shared.log.warn('data.inTestCase: ', data); } } this.sendMinimalEventsIfNeeded(testRunId, data.route, []); data.route = []; const isTestRemoved = runInfo.timeout === null && !runInfo.cancellationToken.isCancellationRequested && result.error === undefined && data.processedTestCases.length < runInfo.childrenToRun.length; if (data.unprocessedTestCases.length > 0 || isTestRemoved) { this.reloadTests(this._shared.taskPool, runInfo.cancellationToken).then( () => { // we have test results for the newly detected tests // after reload we can set the results const events: AbstractTestEvent[] = []; for (let i = 0; i < data.unprocessedTestCases.length; i++) { const testCase = data.unprocessedTestCases[i]; const m = testCase.match(testBeginRe); if (m == null) break; const testNameAsId = m[1]; const currentChild = this._findTest(v => v.compare(testNameAsId)); if (currentChild === undefined) break; try { const ev = currentChild.parseAndProcessTestCase( testRunId, testCase, rngSeed, runInfo.timeout, undefined, ); events.push(ev); } catch (e) { this._shared.log.error('parsing and processing test', e, testCase); } } events.length && this._shared.sendTestEvents(events); }, (reason: Error) => { // Suite possibly deleted: It is a dead suite. this._shared.log.error('reloading-error: ', reason); }, ); } }); } }
the_stack
import { KeyboardAccessoryView, useComponentSize, } from '@flyerhq/react-native-keyboard-accessory-view' import { oneOf } from '@flyerhq/react-native-link-preview' import dayjs from 'dayjs' import calendar from 'dayjs/plugin/calendar' import * as React from 'react' import { FlatList, FlatListProps, GestureResponderHandlers, InteractionManager, LayoutAnimation, StatusBar, StatusBarProps, Text, View, } from 'react-native' import { useSafeAreaInsets } from 'react-native-safe-area-context' import { usePrevious } from '../../hooks' import { l10n } from '../../l10n' import { defaultTheme } from '../../theme' import { MessageType, Theme, User } from '../../types' import { calculateChatMessages, initLocale, L10nContext, ThemeContext, unwrap, UserContext, } from '../../utils' import { CircularActivityIndicator } from '../CircularActivityIndicator' import { Input, InputAdditionalProps, InputTopLevelProps } from '../Input' import { Message, MessageTopLevelProps } from '../Message' import ImageView from './ImageView' import styles from './styles' // Untestable /* istanbul ignore next */ const animate = () => { LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut) } // eslint-disable-next-line jest/require-hook dayjs.extend(calendar) export type ChatTopLevelProps = InputTopLevelProps & MessageTopLevelProps export interface ChatProps extends ChatTopLevelProps { /** Allows you to replace the default Input widget e.g. if you want to create a channel view. */ customBottomComponent?: () => React.ReactNode /** If {@link ChatProps.dateFormat} and/or {@link ChatProps.timeFormat} is not enough to * customize date headers in your case, use this to return an arbitrary * string based on a `dateTime` of a particular message. Can be helpful to * return "Today" if `dateTime` is today. IMPORTANT: this will replace * all default date headers, so you must handle all cases yourself, like * for example today, yesterday and before. Or you can just return the same * date header for any message. */ customDateHeaderText?: (dateTime: number) => string /** Allows you to customize the date format. IMPORTANT: only for the date, * do not return time here. @see {@link ChatProps.timeFormat} to customize the time format. * @see {@link ChatProps.customDateHeaderText} for more customization. */ dateFormat?: string /** Disable automatic image preview on tap. */ disableImageGallery?: boolean /** Allows you to change what the user sees when there are no messages. * `emptyChatPlaceholder` and `emptyChatPlaceholderTextStyle` are ignored * in this case. */ emptyState?: () => React.ReactNode /** Use this to enable `LayoutAnimation`. Experimental on Android (same as React Native). */ enableAnimation?: boolean flatListProps?: Partial<FlatListProps<MessageType.DerivedAny[]>> inputProps?: InputAdditionalProps /** Used for pagination (infinite scroll) together with {@link ChatProps.onEndReached}. * When true, indicates that there are no more pages to load and * pagination will not be triggered. */ isLastPage?: boolean /** Override the default localized copy. */ l10nOverride?: Partial<Record<keyof typeof l10n[keyof typeof l10n], string>> locale?: keyof typeof l10n messages: MessageType.Any[] /** Used for pagination (infinite scroll). Called when user scrolls * to the very end of the list (minus `onEndReachedThreshold`). * See {@link ChatProps.flatListProps} to set it up. */ onEndReached?: () => Promise<void> /** Show user names for received messages. Useful for a group chat. Will be * shown only on text messages. */ showUserNames?: boolean /** Chat theme. Implement {@link Theme} to create your own theme or use * existing one, like the {@link defaultTheme}. */ theme?: Theme /** * Allows you to customize the time format. IMPORTANT: only for the time, * do not return date here. @see {@link ChatProps.dateFormat} to customize the date format. * @see {@link ChatProps.customDateHeaderText} for more customization. */ timeFormat?: string user: User } /** Entry component, represents the complete chat */ export const Chat = ({ customBottomComponent, customDateHeaderText, dateFormat, disableImageGallery, emptyState, enableAnimation, flatListProps, inputProps, isAttachmentUploading, isLastPage, l10nOverride, locale = 'en', messages, onAttachmentPress, onEndReached, onMessageLongPress, onMessagePress, onPreviewDataFetched, onSendPress, renderBubble, renderCustomMessage, renderFileMessage, renderImageMessage, renderTextMessage, sendButtonVisibilityMode = 'editing', showUserAvatars = false, showUserNames = false, textInputProps, theme = defaultTheme, timeFormat, usePreviewData = true, user, }: ChatProps) => { const { container, emptyComponentContainer, emptyComponentTitle, flatList, flatListContentContainer, footer, footerLoadingPage, header, keyboardAccessoryView, } = styles({ theme }) const { onLayout, size } = useComponentSize() const animationRef = React.useRef(false) const list = React.useRef<FlatList<MessageType.DerivedAny>>(null) const insets = useSafeAreaInsets() const [isImageViewVisible, setIsImageViewVisible] = React.useState(false) const [isNextPageLoading, setNextPageLoading] = React.useState(false) const [imageViewIndex, setImageViewIndex] = React.useState(0) const [stackEntry, setStackEntry] = React.useState<StatusBarProps>({}) const l10nValue = React.useMemo( () => ({ ...l10n[locale], ...unwrap(l10nOverride) }), [l10nOverride, locale] ) const { chatMessages, gallery } = calculateChatMessages(messages, user, { customDateHeaderText, dateFormat, showUserNames, timeFormat, }) const previousChatMessages = usePrevious(chatMessages) React.useEffect(() => { if ( chatMessages[0]?.type !== 'dateHeader' && chatMessages[0]?.id !== previousChatMessages?.[0]?.id && chatMessages[0]?.author?.id === user.id ) { list.current?.scrollToOffset({ animated: true, offset: 0, }) } // eslint-disable-next-line react-hooks/exhaustive-deps }, [chatMessages]) React.useEffect(() => { initLocale(locale) }, [locale]) // Untestable /* istanbul ignore next */ if (animationRef.current && enableAnimation) { InteractionManager.runAfterInteractions(animate) } React.useEffect(() => { // Untestable /* istanbul ignore next */ if (animationRef.current && enableAnimation) { InteractionManager.runAfterInteractions(animate) } else { animationRef.current = true } }, [enableAnimation, messages]) const handleEndReached = React.useCallback( // Ignoring because `scroll` event for some reason doesn't trigger even basic // `onEndReached`, impossible to test. // TODO: Verify again later /* istanbul ignore next */ async ({ distanceFromEnd }: { distanceFromEnd: number }) => { if ( !onEndReached || isLastPage || distanceFromEnd <= 0 || messages.length === 0 || isNextPageLoading ) { return } setNextPageLoading(true) await onEndReached?.() setNextPageLoading(false) }, [isLastPage, isNextPageLoading, messages.length, onEndReached] ) const handleImagePress = React.useCallback( (message: MessageType.Image) => { setImageViewIndex( gallery.findIndex( (image) => image.id === message.id && image.uri === message.uri ) ) setIsImageViewVisible(true) setStackEntry( StatusBar.pushStackEntry({ barStyle: 'light-content', animated: true, }) ) }, [gallery] ) const handleMessagePress = React.useCallback( (message: MessageType.Any) => { if (message.type === 'image' && !disableImageGallery) { handleImagePress(message) } onMessagePress?.(message) }, [disableImageGallery, handleImagePress, onMessagePress] ) // TODO: Tapping on a close button results in the next warning: // `An update to ImageViewing inside a test was not wrapped in act(...).` /* istanbul ignore next */ const handleRequestClose = () => { setIsImageViewVisible(false) StatusBar.popStackEntry(stackEntry) } const keyExtractor = React.useCallback( ({ id }: MessageType.DerivedAny) => id, [] ) const renderItem = React.useCallback( ({ item: message }: { item: MessageType.DerivedAny; index: number }) => { const messageWidth = showUserAvatars && message.type !== 'dateHeader' && message.author.id !== user.id ? Math.floor(Math.min(size.width * 0.72, 440)) : Math.floor(Math.min(size.width * 0.77, 440)) const roundBorder = message.type !== 'dateHeader' && message.nextMessageInGroup const showAvatar = message.type !== 'dateHeader' && !message.nextMessageInGroup const showName = message.type !== 'dateHeader' && message.showName const showStatus = message.type !== 'dateHeader' && message.showStatus return ( <Message {...{ enableAnimation, message, messageWidth, onMessageLongPress, onMessagePress: handleMessagePress, onPreviewDataFetched, renderBubble, renderCustomMessage, renderFileMessage, renderImageMessage, renderTextMessage, roundBorder, showAvatar, showName, showStatus, showUserAvatars, usePreviewData, }} /> ) }, [ enableAnimation, handleMessagePress, onMessageLongPress, onPreviewDataFetched, renderBubble, renderCustomMessage, renderFileMessage, renderImageMessage, renderTextMessage, showUserAvatars, size.width, usePreviewData, user.id, ] ) const renderListEmptyComponent = React.useCallback( () => ( <View style={emptyComponentContainer}> {oneOf( emptyState, <Text style={emptyComponentTitle}> {l10nValue.emptyChatPlaceholder} </Text> )()} </View> ), [emptyComponentContainer, emptyComponentTitle, emptyState, l10nValue] ) const renderListFooterComponent = React.useCallback( () => // Impossible to test, see `handleEndReached` function /* istanbul ignore next */ isNextPageLoading ? ( <View style={footerLoadingPage}> <CircularActivityIndicator color={theme.colors.primary} size={16} /> </View> ) : ( <View style={footer} /> ), [footer, footerLoadingPage, isNextPageLoading, theme.colors.primary] ) const renderScrollable = React.useCallback( (panHandlers: GestureResponderHandlers) => ( <FlatList automaticallyAdjustContentInsets={false} contentContainerStyle={[ flatListContentContainer, // eslint-disable-next-line react-native/no-inline-styles { justifyContent: chatMessages.length !== 0 ? undefined : 'center', paddingTop: insets.bottom, }, ]} initialNumToRender={10} ListEmptyComponent={renderListEmptyComponent} ListFooterComponent={renderListFooterComponent} ListHeaderComponent={<View />} ListHeaderComponentStyle={header} maxToRenderPerBatch={6} onEndReachedThreshold={0.75} style={flatList} showsVerticalScrollIndicator={false} {...unwrap(flatListProps)} data={chatMessages} inverted keyboardDismissMode='interactive' keyExtractor={keyExtractor} onEndReached={handleEndReached} ref={list} renderItem={renderItem} {...panHandlers} /> ), [ chatMessages, flatList, flatListContentContainer, flatListProps, handleEndReached, header, insets.bottom, keyExtractor, renderItem, renderListEmptyComponent, renderListFooterComponent, ] ) return ( <UserContext.Provider value={user}> <ThemeContext.Provider value={theme}> <L10nContext.Provider value={l10nValue}> <View style={container} onLayout={onLayout}> {customBottomComponent ? ( <> <>{renderScrollable({})}</> <>{customBottomComponent()}</> </> ) : ( <KeyboardAccessoryView {...{ renderScrollable, style: keyboardAccessoryView, }} > <Input {...{ ...unwrap(inputProps), isAttachmentUploading, onAttachmentPress, onSendPress, renderScrollable, sendButtonVisibilityMode, textInputProps, }} /> </KeyboardAccessoryView> )} <ImageView imageIndex={imageViewIndex} images={gallery} onRequestClose={handleRequestClose} visible={isImageViewVisible} /> </View> </L10nContext.Provider> </ThemeContext.Provider> </UserContext.Provider> ) }
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * Gateway * __NOTE__: An instance of this class is automatically created for an * instance of the ServerManagement. */ export interface Gateway { /** * Creates or updates a ManagementService gateway. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {string} [options.location] Location of the resource. * * @param {object} [options.tags] Resource tags. * * @param {string} [options.upgradeMode] The upgradeMode property gives the * flexibility to gateway to auto upgrade itself. If properties value not * specified, then we assume upgradeMode = Automatic. Possible values include: * 'Manual', 'Automatic' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GatewayResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(resourceGroupName: string, gatewayName: string, options?: { location? : string, tags? : any, upgradeMode? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GatewayResource>>; /** * Creates or updates a ManagementService gateway. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {string} [options.location] Location of the resource. * * @param {object} [options.tags] Resource tags. * * @param {string} [options.upgradeMode] The upgradeMode property gives the * flexibility to gateway to auto upgrade itself. If properties value not * specified, then we assume upgradeMode = Automatic. Possible values include: * 'Manual', 'Automatic' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GatewayResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GatewayResource} [result] - The deserialized result object if an error did not occur. * See {@link GatewayResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ create(resourceGroupName: string, gatewayName: string, options?: { location? : string, tags? : any, upgradeMode? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.GatewayResource>; create(resourceGroupName: string, gatewayName: string, callback: ServiceCallback<models.GatewayResource>): void; create(resourceGroupName: string, gatewayName: string, options: { location? : string, tags? : any, upgradeMode? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GatewayResource>): void; /** * Updates a gateway belonging to a resource group. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {string} [options.location] Location of the resource. * * @param {object} [options.tags] Resource tags. * * @param {string} [options.upgradeMode] The upgradeMode property gives the * flexibility to gateway to auto upgrade itself. If properties value not * specified, then we assume upgradeMode = Automatic. Possible values include: * 'Manual', 'Automatic' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GatewayResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(resourceGroupName: string, gatewayName: string, options?: { location? : string, tags? : any, upgradeMode? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GatewayResource>>; /** * Updates a gateway belonging to a resource group. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {string} [options.location] Location of the resource. * * @param {object} [options.tags] Resource tags. * * @param {string} [options.upgradeMode] The upgradeMode property gives the * flexibility to gateway to auto upgrade itself. If properties value not * specified, then we assume upgradeMode = Automatic. Possible values include: * 'Manual', 'Automatic' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GatewayResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GatewayResource} [result] - The deserialized result object if an error did not occur. * See {@link GatewayResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName: string, gatewayName: string, options?: { location? : string, tags? : any, upgradeMode? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.GatewayResource>; update(resourceGroupName: string, gatewayName: string, callback: ServiceCallback<models.GatewayResource>): void; update(resourceGroupName: string, gatewayName: string, options: { location? : string, tags? : any, upgradeMode? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GatewayResource>): void; /** * Deletes a gateway from a resource group. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, gatewayName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes a gateway from a resource group. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, gatewayName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, gatewayName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, gatewayName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Gets a gateway. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum) * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Gets subscription credentials which * uniquely identify Microsoft Azure subscription. The subscription ID forms * part of the URI for every service call. Possible values include: 'status', * 'download' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GatewayResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, gatewayName: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GatewayResource>>; /** * Gets a gateway. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum) * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Gets subscription credentials which * uniquely identify Microsoft Azure subscription. The subscription ID forms * part of the URI for every service call. Possible values include: 'status', * 'download' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GatewayResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GatewayResource} [result] - The deserialized result object if an error did not occur. * See {@link GatewayResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, gatewayName: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.GatewayResource>; get(resourceGroupName: string, gatewayName: string, callback: ServiceCallback<models.GatewayResource>): void; get(resourceGroupName: string, gatewayName: string, options: { expand? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GatewayResource>): void; /** * Returns gateways in a subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GatewayResources>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GatewayResources>>; /** * Returns gateways in a subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GatewayResources} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GatewayResources} [result] - The deserialized result object if an error did not occur. * See {@link GatewayResources} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.GatewayResources>; list(callback: ServiceCallback<models.GatewayResources>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GatewayResources>): void; /** * Returns gateways in a resource group. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GatewayResources>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GatewayResources>>; /** * Returns gateways in a resource group. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GatewayResources} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GatewayResources} [result] - The deserialized result object if an error did not occur. * See {@link GatewayResources} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.GatewayResources>; listForResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.GatewayResources>): void; listForResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GatewayResources>): void; /** * Upgrades a gateway. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ upgradeWithHttpOperationResponse(resourceGroupName: string, gatewayName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Upgrades a gateway. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ upgrade(resourceGroupName: string, gatewayName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; upgrade(resourceGroupName: string, gatewayName: string, callback: ServiceCallback<void>): void; upgrade(resourceGroupName: string, gatewayName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Regenerate a gateway's profile * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ regenerateProfileWithHttpOperationResponse(resourceGroupName: string, gatewayName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Regenerate a gateway's profile * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ regenerateProfile(resourceGroupName: string, gatewayName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; regenerateProfile(resourceGroupName: string, gatewayName: string, callback: ServiceCallback<void>): void; regenerateProfile(resourceGroupName: string, gatewayName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Gets a gateway profile. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GatewayProfile>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getProfileWithHttpOperationResponse(resourceGroupName: string, gatewayName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GatewayProfile>>; /** * Gets a gateway profile. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GatewayProfile} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GatewayProfile} [result] - The deserialized result object if an error did not occur. * See {@link GatewayProfile} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getProfile(resourceGroupName: string, gatewayName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.GatewayProfile>; getProfile(resourceGroupName: string, gatewayName: string, callback: ServiceCallback<models.GatewayProfile>): void; getProfile(resourceGroupName: string, gatewayName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GatewayProfile>): void; /** * Creates or updates a ManagementService gateway. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {string} [options.location] Location of the resource. * * @param {object} [options.tags] Resource tags. * * @param {string} [options.upgradeMode] The upgradeMode property gives the * flexibility to gateway to auto upgrade itself. If properties value not * specified, then we assume upgradeMode = Automatic. Possible values include: * 'Manual', 'Automatic' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GatewayResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateWithHttpOperationResponse(resourceGroupName: string, gatewayName: string, options?: { location? : string, tags? : any, upgradeMode? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GatewayResource>>; /** * Creates or updates a ManagementService gateway. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {string} [options.location] Location of the resource. * * @param {object} [options.tags] Resource tags. * * @param {string} [options.upgradeMode] The upgradeMode property gives the * flexibility to gateway to auto upgrade itself. If properties value not * specified, then we assume upgradeMode = Automatic. Possible values include: * 'Manual', 'Automatic' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GatewayResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GatewayResource} [result] - The deserialized result object if an error did not occur. * See {@link GatewayResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCreate(resourceGroupName: string, gatewayName: string, options?: { location? : string, tags? : any, upgradeMode? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.GatewayResource>; beginCreate(resourceGroupName: string, gatewayName: string, callback: ServiceCallback<models.GatewayResource>): void; beginCreate(resourceGroupName: string, gatewayName: string, options: { location? : string, tags? : any, upgradeMode? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GatewayResource>): void; /** * Updates a gateway belonging to a resource group. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {string} [options.location] Location of the resource. * * @param {object} [options.tags] Resource tags. * * @param {string} [options.upgradeMode] The upgradeMode property gives the * flexibility to gateway to auto upgrade itself. If properties value not * specified, then we assume upgradeMode = Automatic. Possible values include: * 'Manual', 'Automatic' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GatewayResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginUpdateWithHttpOperationResponse(resourceGroupName: string, gatewayName: string, options?: { location? : string, tags? : any, upgradeMode? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GatewayResource>>; /** * Updates a gateway belonging to a resource group. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {string} [options.location] Location of the resource. * * @param {object} [options.tags] Resource tags. * * @param {string} [options.upgradeMode] The upgradeMode property gives the * flexibility to gateway to auto upgrade itself. If properties value not * specified, then we assume upgradeMode = Automatic. Possible values include: * 'Manual', 'Automatic' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GatewayResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GatewayResource} [result] - The deserialized result object if an error did not occur. * See {@link GatewayResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginUpdate(resourceGroupName: string, gatewayName: string, options?: { location? : string, tags? : any, upgradeMode? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.GatewayResource>; beginUpdate(resourceGroupName: string, gatewayName: string, callback: ServiceCallback<models.GatewayResource>): void; beginUpdate(resourceGroupName: string, gatewayName: string, options: { location? : string, tags? : any, upgradeMode? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GatewayResource>): void; /** * Upgrades a gateway. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginUpgradeWithHttpOperationResponse(resourceGroupName: string, gatewayName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Upgrades a gateway. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginUpgrade(resourceGroupName: string, gatewayName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginUpgrade(resourceGroupName: string, gatewayName: string, callback: ServiceCallback<void>): void; beginUpgrade(resourceGroupName: string, gatewayName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Regenerate a gateway's profile * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginRegenerateProfileWithHttpOperationResponse(resourceGroupName: string, gatewayName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Regenerate a gateway's profile * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginRegenerateProfile(resourceGroupName: string, gatewayName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginRegenerateProfile(resourceGroupName: string, gatewayName: string, callback: ServiceCallback<void>): void; beginRegenerateProfile(resourceGroupName: string, gatewayName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Gets a gateway profile. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GatewayProfile>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginGetProfileWithHttpOperationResponse(resourceGroupName: string, gatewayName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GatewayProfile>>; /** * Gets a gateway profile. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} gatewayName The gateway name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GatewayProfile} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GatewayProfile} [result] - The deserialized result object if an error did not occur. * See {@link GatewayProfile} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginGetProfile(resourceGroupName: string, gatewayName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.GatewayProfile>; beginGetProfile(resourceGroupName: string, gatewayName: string, callback: ServiceCallback<models.GatewayProfile>): void; beginGetProfile(resourceGroupName: string, gatewayName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GatewayProfile>): void; /** * Returns gateways in a subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GatewayResources>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GatewayResources>>; /** * Returns gateways in a subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GatewayResources} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GatewayResources} [result] - The deserialized result object if an error did not occur. * See {@link GatewayResources} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.GatewayResources>; listNext(nextPageLink: string, callback: ServiceCallback<models.GatewayResources>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GatewayResources>): void; /** * Returns gateways in a resource group. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GatewayResources>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GatewayResources>>; /** * Returns gateways in a resource group. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GatewayResources} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GatewayResources} [result] - The deserialized result object if an error did not occur. * See {@link GatewayResources} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.GatewayResources>; listForResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.GatewayResources>): void; listForResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GatewayResources>): void; } /** * @class * Node * __NOTE__: An instance of this class is automatically created for an * instance of the ServerManagement. */ export interface Node { /** * Creates or updates a management node. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {string} [options.location] Location of the resource. * * @param {object} [options.tags] Resource tags. * * @param {string} [options.gatewayId] Gateway ID which will manage this node. * * @param {string} [options.connectionName] myhost.domain.com * * @param {string} [options.userName] User name to be used to connect to node. * * @param {string} [options.password] Password associated with user name. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NodeResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(resourceGroupName: string, nodeName: string, options?: { location? : string, tags? : any, gatewayId? : string, connectionName? : string, userName? : string, password? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NodeResource>>; /** * Creates or updates a management node. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {string} [options.location] Location of the resource. * * @param {object} [options.tags] Resource tags. * * @param {string} [options.gatewayId] Gateway ID which will manage this node. * * @param {string} [options.connectionName] myhost.domain.com * * @param {string} [options.userName] User name to be used to connect to node. * * @param {string} [options.password] Password associated with user name. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NodeResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NodeResource} [result] - The deserialized result object if an error did not occur. * See {@link NodeResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ create(resourceGroupName: string, nodeName: string, options?: { location? : string, tags? : any, gatewayId? : string, connectionName? : string, userName? : string, password? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.NodeResource>; create(resourceGroupName: string, nodeName: string, callback: ServiceCallback<models.NodeResource>): void; create(resourceGroupName: string, nodeName: string, options: { location? : string, tags? : any, gatewayId? : string, connectionName? : string, userName? : string, password? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NodeResource>): void; /** * Updates a management node. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {string} [options.location] Location of the resource. * * @param {object} [options.tags] Resource tags. * * @param {string} [options.gatewayId] Gateway ID which will manage this node. * * @param {string} [options.connectionName] myhost.domain.com * * @param {string} [options.userName] User name to be used to connect to node. * * @param {string} [options.password] Password associated with user name. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NodeResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(resourceGroupName: string, nodeName: string, options?: { location? : string, tags? : any, gatewayId? : string, connectionName? : string, userName? : string, password? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NodeResource>>; /** * Updates a management node. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {string} [options.location] Location of the resource. * * @param {object} [options.tags] Resource tags. * * @param {string} [options.gatewayId] Gateway ID which will manage this node. * * @param {string} [options.connectionName] myhost.domain.com * * @param {string} [options.userName] User name to be used to connect to node. * * @param {string} [options.password] Password associated with user name. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NodeResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NodeResource} [result] - The deserialized result object if an error did not occur. * See {@link NodeResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName: string, nodeName: string, options?: { location? : string, tags? : any, gatewayId? : string, connectionName? : string, userName? : string, password? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.NodeResource>; update(resourceGroupName: string, nodeName: string, callback: ServiceCallback<models.NodeResource>): void; update(resourceGroupName: string, nodeName: string, options: { location? : string, tags? : any, gatewayId? : string, connectionName? : string, userName? : string, password? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NodeResource>): void; /** * deletes a management node * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, nodeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * deletes a management node * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, nodeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, nodeName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, nodeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Gets a management node. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NodeResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, nodeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NodeResource>>; /** * Gets a management node. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NodeResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NodeResource} [result] - The deserialized result object if an error did not occur. * See {@link NodeResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, nodeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NodeResource>; get(resourceGroupName: string, nodeName: string, callback: ServiceCallback<models.NodeResource>): void; get(resourceGroupName: string, nodeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NodeResource>): void; /** * Lists nodes in a subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NodeResources>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NodeResources>>; /** * Lists nodes in a subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NodeResources} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NodeResources} [result] - The deserialized result object if an error did not occur. * See {@link NodeResources} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NodeResources>; list(callback: ServiceCallback<models.NodeResources>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NodeResources>): void; /** * Lists nodes in a resource group. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NodeResources>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NodeResources>>; /** * Lists nodes in a resource group. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NodeResources} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NodeResources} [result] - The deserialized result object if an error did not occur. * See {@link NodeResources} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NodeResources>; listForResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.NodeResources>): void; listForResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NodeResources>): void; /** * Creates or updates a management node. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {string} [options.location] Location of the resource. * * @param {object} [options.tags] Resource tags. * * @param {string} [options.gatewayId] Gateway ID which will manage this node. * * @param {string} [options.connectionName] myhost.domain.com * * @param {string} [options.userName] User name to be used to connect to node. * * @param {string} [options.password] Password associated with user name. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NodeResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateWithHttpOperationResponse(resourceGroupName: string, nodeName: string, options?: { location? : string, tags? : any, gatewayId? : string, connectionName? : string, userName? : string, password? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NodeResource>>; /** * Creates or updates a management node. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {string} [options.location] Location of the resource. * * @param {object} [options.tags] Resource tags. * * @param {string} [options.gatewayId] Gateway ID which will manage this node. * * @param {string} [options.connectionName] myhost.domain.com * * @param {string} [options.userName] User name to be used to connect to node. * * @param {string} [options.password] Password associated with user name. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NodeResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NodeResource} [result] - The deserialized result object if an error did not occur. * See {@link NodeResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCreate(resourceGroupName: string, nodeName: string, options?: { location? : string, tags? : any, gatewayId? : string, connectionName? : string, userName? : string, password? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.NodeResource>; beginCreate(resourceGroupName: string, nodeName: string, callback: ServiceCallback<models.NodeResource>): void; beginCreate(resourceGroupName: string, nodeName: string, options: { location? : string, tags? : any, gatewayId? : string, connectionName? : string, userName? : string, password? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NodeResource>): void; /** * Updates a management node. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {string} [options.location] Location of the resource. * * @param {object} [options.tags] Resource tags. * * @param {string} [options.gatewayId] Gateway ID which will manage this node. * * @param {string} [options.connectionName] myhost.domain.com * * @param {string} [options.userName] User name to be used to connect to node. * * @param {string} [options.password] Password associated with user name. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NodeResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginUpdateWithHttpOperationResponse(resourceGroupName: string, nodeName: string, options?: { location? : string, tags? : any, gatewayId? : string, connectionName? : string, userName? : string, password? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NodeResource>>; /** * Updates a management node. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {object} [options] Optional Parameters. * * @param {string} [options.location] Location of the resource. * * @param {object} [options.tags] Resource tags. * * @param {string} [options.gatewayId] Gateway ID which will manage this node. * * @param {string} [options.connectionName] myhost.domain.com * * @param {string} [options.userName] User name to be used to connect to node. * * @param {string} [options.password] Password associated with user name. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NodeResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NodeResource} [result] - The deserialized result object if an error did not occur. * See {@link NodeResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginUpdate(resourceGroupName: string, nodeName: string, options?: { location? : string, tags? : any, gatewayId? : string, connectionName? : string, userName? : string, password? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.NodeResource>; beginUpdate(resourceGroupName: string, nodeName: string, callback: ServiceCallback<models.NodeResource>): void; beginUpdate(resourceGroupName: string, nodeName: string, options: { location? : string, tags? : any, gatewayId? : string, connectionName? : string, userName? : string, password? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NodeResource>): void; /** * Lists nodes in a subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NodeResources>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NodeResources>>; /** * Lists nodes in a subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NodeResources} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NodeResources} [result] - The deserialized result object if an error did not occur. * See {@link NodeResources} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NodeResources>; listNext(nextPageLink: string, callback: ServiceCallback<models.NodeResources>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NodeResources>): void; /** * Lists nodes in a resource group. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NodeResources>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NodeResources>>; /** * Lists nodes in a resource group. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NodeResources} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NodeResources} [result] - The deserialized result object if an error did not occur. * See {@link NodeResources} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NodeResources>; listForResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.NodeResources>): void; listForResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NodeResources>): void; } /** * @class * Session * __NOTE__: An instance of this class is automatically created for an * instance of the ServerManagement. */ export interface Session { /** * Creates a session for a node. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {string} [options.userName] Encrypted User name to be used to connect * to node. * * @param {string} [options.password] Encrypted Password associated with user * name. * * @param {string} [options.retentionPeriod] Session retention period. Possible * values include: 'Session', 'Persistent' * * @param {string} [options.credentialDataFormat] Credential data format. * Possible values include: 'RsaEncrypted' * * @param {string} [options.encryptionCertificateThumbprint] Encryption * certificate thumbprint. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SessionResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(resourceGroupName: string, nodeName: string, session: string, options?: { userName? : string, password? : string, retentionPeriod? : string, credentialDataFormat? : string, encryptionCertificateThumbprint? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SessionResource>>; /** * Creates a session for a node. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {string} [options.userName] Encrypted User name to be used to connect * to node. * * @param {string} [options.password] Encrypted Password associated with user * name. * * @param {string} [options.retentionPeriod] Session retention period. Possible * values include: 'Session', 'Persistent' * * @param {string} [options.credentialDataFormat] Credential data format. * Possible values include: 'RsaEncrypted' * * @param {string} [options.encryptionCertificateThumbprint] Encryption * certificate thumbprint. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SessionResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SessionResource} [result] - The deserialized result object if an error did not occur. * See {@link SessionResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ create(resourceGroupName: string, nodeName: string, session: string, options?: { userName? : string, password? : string, retentionPeriod? : string, credentialDataFormat? : string, encryptionCertificateThumbprint? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.SessionResource>; create(resourceGroupName: string, nodeName: string, session: string, callback: ServiceCallback<models.SessionResource>): void; create(resourceGroupName: string, nodeName: string, session: string, options: { userName? : string, password? : string, retentionPeriod? : string, credentialDataFormat? : string, encryptionCertificateThumbprint? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SessionResource>): void; /** * Deletes a session for a node. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, nodeName: string, session: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes a session for a node. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, nodeName: string, session: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, nodeName: string, session: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, nodeName: string, session: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Gets a session for a node. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SessionResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, nodeName: string, session: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SessionResource>>; /** * Gets a session for a node. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SessionResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SessionResource} [result] - The deserialized result object if an error did not occur. * See {@link SessionResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, nodeName: string, session: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SessionResource>; get(resourceGroupName: string, nodeName: string, session: string, callback: ServiceCallback<models.SessionResource>): void; get(resourceGroupName: string, nodeName: string, session: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SessionResource>): void; /** * Creates a session for a node. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {string} [options.userName] Encrypted User name to be used to connect * to node. * * @param {string} [options.password] Encrypted Password associated with user * name. * * @param {string} [options.retentionPeriod] Session retention period. Possible * values include: 'Session', 'Persistent' * * @param {string} [options.credentialDataFormat] Credential data format. * Possible values include: 'RsaEncrypted' * * @param {string} [options.encryptionCertificateThumbprint] Encryption * certificate thumbprint. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SessionResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateWithHttpOperationResponse(resourceGroupName: string, nodeName: string, session: string, options?: { userName? : string, password? : string, retentionPeriod? : string, credentialDataFormat? : string, encryptionCertificateThumbprint? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SessionResource>>; /** * Creates a session for a node. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {string} [options.userName] Encrypted User name to be used to connect * to node. * * @param {string} [options.password] Encrypted Password associated with user * name. * * @param {string} [options.retentionPeriod] Session retention period. Possible * values include: 'Session', 'Persistent' * * @param {string} [options.credentialDataFormat] Credential data format. * Possible values include: 'RsaEncrypted' * * @param {string} [options.encryptionCertificateThumbprint] Encryption * certificate thumbprint. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SessionResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SessionResource} [result] - The deserialized result object if an error did not occur. * See {@link SessionResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCreate(resourceGroupName: string, nodeName: string, session: string, options?: { userName? : string, password? : string, retentionPeriod? : string, credentialDataFormat? : string, encryptionCertificateThumbprint? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.SessionResource>; beginCreate(resourceGroupName: string, nodeName: string, session: string, callback: ServiceCallback<models.SessionResource>): void; beginCreate(resourceGroupName: string, nodeName: string, session: string, options: { userName? : string, password? : string, retentionPeriod? : string, credentialDataFormat? : string, encryptionCertificateThumbprint? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SessionResource>): void; } /** * @class * PowerShell * __NOTE__: An instance of this class is automatically created for an * instance of the ServerManagement. */ export interface PowerShell { /** * Gets a list of the active sessions. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PowerShellSessionResources>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listSessionWithHttpOperationResponse(resourceGroupName: string, nodeName: string, session: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PowerShellSessionResources>>; /** * Gets a list of the active sessions. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PowerShellSessionResources} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PowerShellSessionResources} [result] - The deserialized result object if an error did not occur. * See {@link PowerShellSessionResources} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listSession(resourceGroupName: string, nodeName: string, session: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PowerShellSessionResources>; listSession(resourceGroupName: string, nodeName: string, session: string, callback: ServiceCallback<models.PowerShellSessionResources>): void; listSession(resourceGroupName: string, nodeName: string, session: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PowerShellSessionResources>): void; /** * Creates a PowerShell session. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {string} pssession The PowerShell sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PowerShellSessionResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createSessionWithHttpOperationResponse(resourceGroupName: string, nodeName: string, session: string, pssession: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PowerShellSessionResource>>; /** * Creates a PowerShell session. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {string} pssession The PowerShell sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PowerShellSessionResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PowerShellSessionResource} [result] - The deserialized result object if an error did not occur. * See {@link PowerShellSessionResource} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createSession(resourceGroupName: string, nodeName: string, session: string, pssession: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PowerShellSessionResource>; createSession(resourceGroupName: string, nodeName: string, session: string, pssession: string, callback: ServiceCallback<models.PowerShellSessionResource>): void; createSession(resourceGroupName: string, nodeName: string, session: string, pssession: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PowerShellSessionResource>): void; /** * Gets the status of a command. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {string} pssession The PowerShell sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Gets current output from an ongoing call. * Possible values include: 'output' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PowerShellCommandStatus>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getCommandStatusWithHttpOperationResponse(resourceGroupName: string, nodeName: string, session: string, pssession: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PowerShellCommandStatus>>; /** * Gets the status of a command. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {string} pssession The PowerShell sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Gets current output from an ongoing call. * Possible values include: 'output' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PowerShellCommandStatus} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PowerShellCommandStatus} [result] - The deserialized result object if an error did not occur. * See {@link PowerShellCommandStatus} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getCommandStatus(resourceGroupName: string, nodeName: string, session: string, pssession: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.PowerShellCommandStatus>; getCommandStatus(resourceGroupName: string, nodeName: string, session: string, pssession: string, callback: ServiceCallback<models.PowerShellCommandStatus>): void; getCommandStatus(resourceGroupName: string, nodeName: string, session: string, pssession: string, options: { expand? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PowerShellCommandStatus>): void; /** * Updates a running PowerShell command with more data. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {string} pssession The PowerShell sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PowerShellCommandResults>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateCommandWithHttpOperationResponse(resourceGroupName: string, nodeName: string, session: string, pssession: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PowerShellCommandResults>>; /** * Updates a running PowerShell command with more data. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {string} pssession The PowerShell sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PowerShellCommandResults} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PowerShellCommandResults} [result] - The deserialized result object if an error did not occur. * See {@link PowerShellCommandResults} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ updateCommand(resourceGroupName: string, nodeName: string, session: string, pssession: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PowerShellCommandResults>; updateCommand(resourceGroupName: string, nodeName: string, session: string, pssession: string, callback: ServiceCallback<models.PowerShellCommandResults>): void; updateCommand(resourceGroupName: string, nodeName: string, session: string, pssession: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PowerShellCommandResults>): void; /** * Creates a PowerShell script and invokes it. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {string} pssession The PowerShell sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {string} [options.command] Script to execute. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PowerShellCommandResults>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ invokeCommandWithHttpOperationResponse(resourceGroupName: string, nodeName: string, session: string, pssession: string, options?: { command? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PowerShellCommandResults>>; /** * Creates a PowerShell script and invokes it. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {string} pssession The PowerShell sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {string} [options.command] Script to execute. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PowerShellCommandResults} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PowerShellCommandResults} [result] - The deserialized result object if an error did not occur. * See {@link PowerShellCommandResults} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ invokeCommand(resourceGroupName: string, nodeName: string, session: string, pssession: string, options?: { command? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.PowerShellCommandResults>; invokeCommand(resourceGroupName: string, nodeName: string, session: string, pssession: string, callback: ServiceCallback<models.PowerShellCommandResults>): void; invokeCommand(resourceGroupName: string, nodeName: string, session: string, pssession: string, options: { command? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PowerShellCommandResults>): void; /** * Cancels a PowerShell command. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {string} pssession The PowerShell sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PowerShellCommandResults>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ cancelCommandWithHttpOperationResponse(resourceGroupName: string, nodeName: string, session: string, pssession: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PowerShellCommandResults>>; /** * Cancels a PowerShell command. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {string} pssession The PowerShell sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PowerShellCommandResults} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PowerShellCommandResults} [result] - The deserialized result object if an error did not occur. * See {@link PowerShellCommandResults} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ cancelCommand(resourceGroupName: string, nodeName: string, session: string, pssession: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PowerShellCommandResults>; cancelCommand(resourceGroupName: string, nodeName: string, session: string, pssession: string, callback: ServiceCallback<models.PowerShellCommandResults>): void; cancelCommand(resourceGroupName: string, nodeName: string, session: string, pssession: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PowerShellCommandResults>): void; /** * Gets tab completion values for a command. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {string} pssession The PowerShell sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {string} [options.command] Command to get tab completion for. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PowerShellTabCompletionResults>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ tabCompletionWithHttpOperationResponse(resourceGroupName: string, nodeName: string, session: string, pssession: string, options?: { command? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PowerShellTabCompletionResults>>; /** * Gets tab completion values for a command. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {string} pssession The PowerShell sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {string} [options.command] Command to get tab completion for. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PowerShellTabCompletionResults} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PowerShellTabCompletionResults} [result] - The deserialized result object if an error did not occur. * See {@link PowerShellTabCompletionResults} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ tabCompletion(resourceGroupName: string, nodeName: string, session: string, pssession: string, options?: { command? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.PowerShellTabCompletionResults>; tabCompletion(resourceGroupName: string, nodeName: string, session: string, pssession: string, callback: ServiceCallback<models.PowerShellTabCompletionResults>): void; tabCompletion(resourceGroupName: string, nodeName: string, session: string, pssession: string, options: { command? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PowerShellTabCompletionResults>): void; /** * Creates a PowerShell session. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {string} pssession The PowerShell sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PowerShellSessionResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateSessionWithHttpOperationResponse(resourceGroupName: string, nodeName: string, session: string, pssession: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PowerShellSessionResource>>; /** * Creates a PowerShell session. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {string} pssession The PowerShell sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PowerShellSessionResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PowerShellSessionResource} [result] - The deserialized result object if an error did not occur. * See {@link PowerShellSessionResource} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCreateSession(resourceGroupName: string, nodeName: string, session: string, pssession: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PowerShellSessionResource>; beginCreateSession(resourceGroupName: string, nodeName: string, session: string, pssession: string, callback: ServiceCallback<models.PowerShellSessionResource>): void; beginCreateSession(resourceGroupName: string, nodeName: string, session: string, pssession: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PowerShellSessionResource>): void; /** * Updates a running PowerShell command with more data. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {string} pssession The PowerShell sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PowerShellCommandResults>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginUpdateCommandWithHttpOperationResponse(resourceGroupName: string, nodeName: string, session: string, pssession: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PowerShellCommandResults>>; /** * Updates a running PowerShell command with more data. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {string} pssession The PowerShell sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PowerShellCommandResults} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PowerShellCommandResults} [result] - The deserialized result object if an error did not occur. * See {@link PowerShellCommandResults} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginUpdateCommand(resourceGroupName: string, nodeName: string, session: string, pssession: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PowerShellCommandResults>; beginUpdateCommand(resourceGroupName: string, nodeName: string, session: string, pssession: string, callback: ServiceCallback<models.PowerShellCommandResults>): void; beginUpdateCommand(resourceGroupName: string, nodeName: string, session: string, pssession: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PowerShellCommandResults>): void; /** * Creates a PowerShell script and invokes it. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {string} pssession The PowerShell sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {string} [options.command] Script to execute. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PowerShellCommandResults>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginInvokeCommandWithHttpOperationResponse(resourceGroupName: string, nodeName: string, session: string, pssession: string, options?: { command? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PowerShellCommandResults>>; /** * Creates a PowerShell script and invokes it. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {string} pssession The PowerShell sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {string} [options.command] Script to execute. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PowerShellCommandResults} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PowerShellCommandResults} [result] - The deserialized result object if an error did not occur. * See {@link PowerShellCommandResults} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginInvokeCommand(resourceGroupName: string, nodeName: string, session: string, pssession: string, options?: { command? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.PowerShellCommandResults>; beginInvokeCommand(resourceGroupName: string, nodeName: string, session: string, pssession: string, callback: ServiceCallback<models.PowerShellCommandResults>): void; beginInvokeCommand(resourceGroupName: string, nodeName: string, session: string, pssession: string, options: { command? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PowerShellCommandResults>): void; /** * Cancels a PowerShell command. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {string} pssession The PowerShell sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PowerShellCommandResults>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCancelCommandWithHttpOperationResponse(resourceGroupName: string, nodeName: string, session: string, pssession: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PowerShellCommandResults>>; /** * Cancels a PowerShell command. * * @param {string} resourceGroupName The resource group name uniquely * identifies the resource group within the user subscriptionId. * * @param {string} nodeName The node name (256 characters maximum). * * @param {string} session The sessionId from the user. * * @param {string} pssession The PowerShell sessionId from the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PowerShellCommandResults} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PowerShellCommandResults} [result] - The deserialized result object if an error did not occur. * See {@link PowerShellCommandResults} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCancelCommand(resourceGroupName: string, nodeName: string, session: string, pssession: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PowerShellCommandResults>; beginCancelCommand(resourceGroupName: string, nodeName: string, session: string, pssession: string, callback: ServiceCallback<models.PowerShellCommandResults>): void; beginCancelCommand(resourceGroupName: string, nodeName: string, session: string, pssession: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PowerShellCommandResults>): void; }
the_stack
import * as child_process from 'child_process'; import * as protobufjs from 'protobufjs'; import * as assert from 'assert'; import * as Long from 'long'; import * as fs from 'fs'; import { parseSchema } from './index'; import { Enum, EnumTest, MapTestLongAndBool, MapTestIntAndString, Optional, RepeatedPacked, RepeatedUnpacked, } from './test.proto'; function parseTestProto(): typeof import('./test.proto') { return parseSchema(fs.readFileSync('./test.proto', 'utf8')).compile(); } function prngUint32(): () => number { let seed = 1; return () => { const temp = (seed * 20077 + (seed & 0xFFFF) * 1103495168 + 12345) & 0x7FFFFFFF; seed = (temp * 20077 + (temp & 0xFFFF) * 1103495168 + 12345) & 0x7FFFFFFF; return ((temp & 0xFFFF) | (seed << 16)) >>> 0; }; } function* randomMessageStream(): Iterable<Optional> { const randomUint32 = prngUint32(); const randomFloat64 = () => randomUint32() / (-1 >>> 0); for (let i = 0; i < 1000; i++) { yield { field_int32: randomUint32() | 0, field_int64: new Long(randomUint32(), randomUint32()), field_uint32: randomUint32(), field_uint64: new Long(randomUint32(), randomUint32(), true), field_sint32: randomUint32() | 0, field_sint64: new Long(randomUint32(), randomUint32()), field_fixed64: new Long(randomUint32(), randomUint32(), true), field_sfixed64: new Long(randomUint32(), randomUint32()), field_double: randomFloat64(), field_fixed32: randomUint32(), field_sfixed32: randomUint32() | 0, field_float: Math.fround(randomFloat64()), }; } } //////////////////////////////////////////////////////////////////////////////// it('optional', async () => { const schema = parseTestProto(); const message: Optional = { field_int32: -1, field_int64: new Long(-1, -2), field_uint32: -1 >>> 0, field_uint64: new Long(-1 >>> 0, -2 >>> 0, true), field_sint32: -1, field_sint64: new Long(-1, -2), field_bool: true, field_fixed64: new Long(12345678, 87654321, true), field_sfixed64: new Long(-87654321, -12345678), field_double: 2.5, field_string: 'testing 🙉🙈🙊', field_bytes: new Uint8Array([1, 2, 3, 4, 5]), field_fixed32: -1 >>> 0, field_sfixed32: -1, field_float: 3.25, field_nested: { x: 1.5 }, }; const buffer = schema.encodeOptional(message); const message2 = schema.decodeOptional(buffer); assert.deepEqual(message2, message); const root = new protobufjs.Root(); await root.load('./test.proto', { keepCase: true }); const Optional = root.lookupType('test.Optional'); const message3 = Optional.decode(buffer); assert.deepEqual(message3, message); const buffer2 = Optional.encode(message).finish(); assert.deepEqual(buffer2, buffer); }); //////////////////////////////////////////////////////////////////////////////// it('repeated unpacked', async () => { const schema = parseTestProto(); const message: RepeatedUnpacked = { field_int32: [-1, -2], field_int64: [new Long(-1, -2), new Long(-3, -4)], field_uint32: [-1 >>> 0, -2 >>> 0], field_uint64: [new Long(-1 >>> 0, -2 >>> 0, true), new Long(-3 >>> 0, -4 >>> 0, true)], field_sint32: [-1, -2], field_sint64: [new Long(-1, -2), new Long(-3, -4)], field_bool: [true, false], field_fixed64: [new Long(12345678, 87654321, true), new Long(8765, 1234, true)], field_sfixed64: [new Long(-87654321, -12345678), new Long(-1234, -8765)], field_double: [2.5, -2.5], field_string: ['testing', '🙉🙈🙊'], field_bytes: [new Uint8Array([1, 2, 3, 4, 5]), new Uint8Array([]), new Uint8Array([5, 4, 3])], field_fixed32: [-1 >>> 0, -2 >>> 0], field_sfixed32: [-1, -2], field_float: [3.25, -3.25], field_nested: [{ x: 1.5 }, {}, { y: 0.5 }], }; const buffer = schema.encodeRepeatedUnpacked(message); const message2 = schema.decodeRepeatedUnpacked(buffer); assert.deepEqual(message2, message); const root = new protobufjs.Root(); await root.load('./test.proto', { keepCase: true }); const RepeatedUnpacked = root.lookupType('test.RepeatedUnpacked'); const message3 = RepeatedUnpacked.decode(buffer); assert.deepEqual(message3, message); const buffer2 = RepeatedUnpacked.encode(message).finish(); assert.deepEqual(buffer2, buffer); }); //////////////////////////////////////////////////////////////////////////////// it('repeated packed', async () => { const schema = parseTestProto(); const message: RepeatedPacked = { field_int32: [-1, -2], field_int64: [new Long(-1, -2), new Long(-3, -4)], field_uint32: [-1 >>> 0, -2 >>> 0], field_uint64: [new Long(-1 >>> 0, -2 >>> 0, true), new Long(-3 >>> 0, -4 >>> 0, true)], field_sint32: [-1, -2], field_sint64: [new Long(-1, -2), new Long(-3, -4)], field_bool: [true, false], field_fixed64: [new Long(12345678, 87654321, true), new Long(8765, 1234, true)], field_sfixed64: [new Long(-87654321, -12345678), new Long(-1234, -8765)], field_double: [2.5, -2.5], field_string: ['testing', '🙉🙈🙊'], field_bytes: [new Uint8Array([1, 2, 3, 4, 5]), new Uint8Array([]), new Uint8Array([5, 4, 3])], field_fixed32: [-1 >>> 0, -2 >>> 0], field_sfixed32: [-1, -2], field_float: [3.25, -3.25], field_nested: [{ x: 1.5 }, {}, { y: 0.5 }], }; const buffer = schema.encodeRepeatedPacked(message); const message2 = schema.decodeRepeatedPacked(buffer); assert.deepEqual(message2, message); const root = new protobufjs.Root(); await root.load('./test.proto', { keepCase: true }); const RepeatedPacked = root.lookupType('test.RepeatedPacked'); const message3 = RepeatedPacked.decode(buffer); assert.deepEqual(message3, message); const buffer2 = RepeatedPacked.encode(message).finish(); assert.deepEqual(buffer2, buffer); }); //////////////////////////////////////////////////////////////////////////////// it('enum test', async () => { const schema = parseTestProto(); const message: EnumTest = { a: Enum.B, b: Enum.A, c: [Enum.A, Enum.B], }; const buffer = schema.encodeEnumTest(message); const message2 = schema.decodeEnumTest(buffer); assert.deepEqual(message2, message); }); //////////////////////////////////////////////////////////////////////////////// it('map test (int and string keys)', async () => { const schema = parseTestProto(); const message: MapTestIntAndString = { field_int32: { [-1]: 'testing', [1]: '🙉🙈🙊' }, field_uint32: { [-1 >>> 0]: new Uint8Array([1, 2, 3]), [1]: new Uint8Array([254, 255]) }, field_sint32: { [-1]: new Long(123, 234), [1]: new Long(-1, -2) }, field_string: { 'testing': 12.34, '🙉🙈🙊': 56.78 }, field_fixed32: { [-1 >>> 0]: false, [1]: true }, field_sfixed32: { [-1]: { x: 2 }, [1]: { y: -2 } }, }; const buffer = schema.encodeMapTestIntAndString(message); const message2 = schema.decodeMapTestIntAndString(buffer); assert.deepEqual(message2, message); const root = new protobufjs.Root(); await root.load('./test.proto', { keepCase: true }); const MapTestIntAndString = root.lookupType('test.MapTestIntAndString'); const message3 = MapTestIntAndString.decode(buffer); assert.deepEqual(message3, message); const buffer2 = MapTestIntAndString.encode(message).finish(); assert.deepEqual(buffer2, buffer); }); //////////////////////////////////////////////////////////////////////////////// it('map test (long and bool keys)', async () => { const schema = parseTestProto(); const message: MapTestLongAndBool = { field_int64: { '\uFEDC\uBA98\u7654\u3210': 'testing 🙉🙈🙊' }, field_uint64: { '\uBA98\u7654\u3210\uFEDC': new Uint8Array([0, 1, 254, 255]) }, field_sint64: { '\u7654\u3210\uFEDC\uBA98': new Long(-1, -2) }, field_fixed64: { '\u3210\uFEDC\uBA98\u7654': 12.34 }, field_sfixed64: { '\uFEDC\uBA98\u7654\u3210': true }, field_bool: { false: { x: 2 }, true: { y: -2 } }, }; // Note: The output can't be compared against protobuf.js because it has a // bug that prevents it from round-tripping 64-bit keys correctly. The keys // are encoded in decimal but decoded in binary. Whoops! See this for more // information: https://github.com/protobufjs/protobuf.js/issues/1203. // Because 64-bit keys are broken in protobuf.js, this library uses a more // efficient 16-bit encoding of 64-bit keys instead of an 8-bit encoding. // // It also seems to have a bug that breaks round-tripping boolean keys. I // couldn't find an associated bug but I also couldn't get it to work. const buffer = schema.encodeMapTestLongAndBool(message); const message2 = schema.decodeMapTestLongAndBool(buffer); assert.deepEqual(message2, message); const root = new protobufjs.Root(); await root.load('./test.proto', { keepCase: true }); // Even though we can't compare against the contents, still test that the // buffer is valid and can be decoded without throwing an error. const MapTestLongAndBool = root.lookupType('test.MapTestLongAndBool'); MapTestLongAndBool.decode(buffer); }); //////////////////////////////////////////////////////////////////////////////// it('fuzzing protobufjs', async () => { const schema = parseTestProto(); for (const message of randomMessageStream()) { const buffer = schema.encodeOptional(message); const message2 = schema.decodeOptional(buffer); assert.deepEqual(message2, message); } }); //////////////////////////////////////////////////////////////////////////////// it('fuzzing pbjs', async () => { const root = new protobufjs.Root(); await root.load('./test.proto', { keepCase: true }); const Optional = root.lookupType('test.Optional'); for (const message of randomMessageStream()) { const buffer = Optional.encode(message).finish(); const message2 = Optional.decode(buffer); assert.deepEqual(message2, message); } }); //////////////////////////////////////////////////////////////////////////////// it('javascript (es5)', () => { const js = fs.readFileSync('./test.proto.es5.js', 'utf8'); const js2 = parseSchema(fs.readFileSync('./test.proto', 'utf8')).toJavaScript(); assert.strictEqual(js, js2); }); //////////////////////////////////////////////////////////////////////////////// it('javascript (es6)', () => { const js = fs.readFileSync('./test.proto.es6.js', 'utf8'); const js2 = parseSchema(fs.readFileSync('./test.proto', 'utf8')).toJavaScript({ es6: true }); assert.strictEqual(js, js2); }); //////////////////////////////////////////////////////////////////////////////// it('typescript', () => { const ts = fs.readFileSync('./test.proto.ts', 'utf8'); const ts2 = parseSchema(fs.readFileSync('./test.proto', 'utf8')).toTypeScript(); assert.strictEqual(ts, ts2); }); //////////////////////////////////////////////////////////////////////////////// it('cli: generate javascript (es5)', async () => { try { fs.unlinkSync('./temp.js'); } catch (e) { } const js = fs.readFileSync('./test.proto.es5.js', 'utf8'); const cli = child_process.spawn('node', ['./cli.js', './test.proto', '--es5', './temp.js']); await new Promise(resolve => cli.on('close', resolve)); const js2 = fs.readFileSync('./temp.js', 'utf8'); fs.unlinkSync('./temp.js'); assert.strictEqual(js, js2); }); //////////////////////////////////////////////////////////////////////////////// it('cli: generate javascript (es6)', async () => { try { fs.unlinkSync('./temp.js'); } catch (e) { } const js = fs.readFileSync('./test.proto.es6.js', 'utf8'); const cli = child_process.spawn('node', ['./cli.js', './test.proto', '--es6', './temp.js']); await new Promise(resolve => cli.on('close', resolve)); const js2 = fs.readFileSync('./temp.js', 'utf8'); fs.unlinkSync('./temp.js'); assert.strictEqual(js, js2); }); //////////////////////////////////////////////////////////////////////////////// it('cli: generate typescript', async () => { try { fs.unlinkSync('./temp.ts'); } catch (e) { } const ts = fs.readFileSync('./test.proto.ts', 'utf8'); const cli = child_process.spawn('node', ['./cli.js', './test.proto', '--ts', './temp.ts']); await new Promise(resolve => cli.on('close', resolve)); const ts2 = fs.readFileSync('./temp.ts', 'utf8'); fs.unlinkSync('./temp.ts'); assert.strictEqual(ts, ts2); }); //////////////////////////////////////////////////////////////////////////////// it('cli: encode', async () => { const schema = parseTestProto(); const message = { x: 1.5, y: -2.5, }; const cli = child_process.spawn('node', ['./cli.js', './test.proto', '--encode', 'Nested']); const chunks: Buffer[] = []; cli.stdin.write(JSON.stringify(message)); cli.stdin.end(); cli.stdout.on('data', chunk => chunks.push(chunk)); await new Promise(resolve => cli.on('close', resolve)); assert.deepStrictEqual(new Uint8Array(Buffer.concat(chunks)), schema.encodeNested(message)); }); //////////////////////////////////////////////////////////////////////////////// it('cli: decode', async () => { const schema = parseTestProto(); const message = { x: 1.5, y: -2.5, }; const cli = child_process.spawn('node', ['./cli.js', './test.proto', '--decode', 'Nested']); const chunks: Buffer[] = []; cli.stdin.write(schema.encodeNested(message)); cli.stdin.end(); cli.stdout.on('data', chunk => chunks.push(chunk)); await new Promise(resolve => cli.on('close', resolve)); assert.strictEqual(Buffer.concat(chunks).toString(), JSON.stringify(message, null, 2) + '\n'); });
the_stack
import { App, Editor, FuzzyMatch, FuzzySuggestModal, Modal, Notice, Platform, Scope, Setting, SuggestModal, TextComponent } from "obsidian"; import { createPopper, Instance as PopperInstance } from "@popperjs/core"; import { getIconModuleName, getIconNode, iconDefinitions } from "../util"; import { Admonition, AdmonitionIconDefinition, ObsidianAdmonitionPlugin } from "src/@types"; class Suggester<T> { owner: SuggestModal<T>; items: T[]; suggestions: HTMLDivElement[]; selectedItem: number; containerEl: HTMLElement; constructor( owner: SuggestModal<T>, containerEl: HTMLElement, scope: Scope ) { this.containerEl = containerEl; this.owner = owner; containerEl.on( "click", ".suggestion-item", this.onSuggestionClick.bind(this) ); containerEl.on( "mousemove", ".suggestion-item", this.onSuggestionMouseover.bind(this) ); scope.register([], "ArrowUp", () => { this.setSelectedItem(this.selectedItem - 1, true); return false; }); scope.register([], "ArrowDown", () => { this.setSelectedItem(this.selectedItem + 1, true); return false; }); scope.register([], "Enter", (evt) => { this.useSelectedItem(evt); return false; }); scope.register([], "Tab", (evt) => { this.useSelectedItem(evt); return false; }); } chooseSuggestion(evt: KeyboardEvent | MouseEvent) { if (!this.items || !this.items.length) return; const currentValue = this.items[this.selectedItem]; if (currentValue) { this.owner.selectSuggestion(currentValue, evt); } } onSuggestionClick(event: MouseEvent, el: HTMLDivElement): void { event.preventDefault(); if (!this.suggestions || !this.suggestions.length) return; const item = this.suggestions.indexOf(el); this.setSelectedItem(item, false); this.useSelectedItem(event); } onSuggestionMouseover(event: MouseEvent, el: HTMLDivElement): void { if (!this.suggestions || !this.suggestions.length) return; const item = this.suggestions.indexOf(el); this.setSelectedItem(item, false); } empty() { this.containerEl.empty(); } setSuggestions(items: T[]) { this.containerEl.empty(); const els: HTMLDivElement[] = []; items.forEach((item) => { const suggestionEl = this.containerEl.createDiv("suggestion-item"); this.owner.renderSuggestion(item, suggestionEl); els.push(suggestionEl); }); this.items = items; this.suggestions = els; this.setSelectedItem(0, false); } useSelectedItem(event: MouseEvent | KeyboardEvent) { if (!this.items || !this.items.length) return; const currentValue = this.items[this.selectedItem]; if (currentValue) { this.owner.selectSuggestion(currentValue, event); } if (Platform.isMobile) { this.chooseSuggestion(event); } } wrap(value: number, size: number): number { return ((value % size) + size) % size; } setSelectedItem(index: number, scroll: boolean) { const nIndex = this.wrap(index, this.suggestions.length); const prev = this.suggestions[this.selectedItem]; const next = this.suggestions[nIndex]; if (prev) prev.removeClass("is-selected"); if (next) next.addClass("is-selected"); this.selectedItem = nIndex; if (scroll) { next.scrollIntoView(false); } } } export abstract class SuggestionModal<T> extends FuzzySuggestModal<T> { items: T[] = []; suggestions: HTMLDivElement[]; popper: PopperInstance; scope: Scope = new Scope(); suggester: Suggester<FuzzyMatch<T>>; suggestEl: HTMLDivElement; promptEl: HTMLDivElement; emptyStateText: string = "No match found"; limit: number = 100; constructor(app: App, inputEl: HTMLInputElement, items: T[]) { super(app); this.inputEl = inputEl; this.items = items; this.suggestEl = createDiv("suggestion-container"); this.contentEl = this.suggestEl.createDiv("suggestion"); this.suggester = new Suggester(this, this.contentEl, this.scope); this.scope.register([], "Escape", this.close.bind(this)); this.inputEl.addEventListener("input", this.onInputChanged.bind(this)); this.inputEl.addEventListener("focus", this.onInputChanged.bind(this)); this.inputEl.addEventListener("blur", this.close.bind(this)); this.suggestEl.on( "mousedown", ".suggestion-container", (event: MouseEvent) => { event.preventDefault(); } ); } empty() { this.suggester.empty(); } onInputChanged(): void { const inputStr = this.modifyInput(this.inputEl.value); const suggestions = this.getSuggestions(inputStr); if (suggestions.length > 0) { this.suggester.setSuggestions(suggestions.slice(0, this.limit)); } else { this.onNoSuggestion(); } this.open(); } modifyInput(input: string): string { return input; } onNoSuggestion() { this.empty(); this.renderSuggestion( null, this.contentEl.createDiv("suggestion-item") ); } open(): void { // TODO: Figure out a better way to do this. Idea from Periodic Notes plugin // eslint-disable-next-line @typescript-eslint/no-explicit-any (<any>this.app).keymap.pushScope(this.scope); document.body.appendChild(this.suggestEl); this.popper = createPopper(this.inputEl, this.suggestEl, { placement: "bottom-start", modifiers: [ { name: "offset", options: { offset: [0, 10] } }, { name: "flip", options: { fallbackPlacements: ["top"] } } ] }); } close(): void { // TODO: Figure out a better way to do this. Idea from Periodic Notes plugin // eslint-disable-next-line @typescript-eslint/no-explicit-any (<any>this.app).keymap.popScope(this.scope); this.suggester.setSuggestions([]); if (this.popper) { this.popper.destroy(); } this.suggestEl.detach(); } createPrompt(prompts: HTMLSpanElement[]) { if (!this.promptEl) this.promptEl = this.suggestEl.createDiv("prompt-instructions"); let prompt = this.promptEl.createDiv("prompt-instruction"); for (let p of prompts) { prompt.appendChild(p); } } abstract onChooseItem(item: T, evt: MouseEvent | KeyboardEvent): void; abstract getItemText(arg: T): string; abstract getItems(): T[]; } export class IconSuggestionModal extends SuggestionModal<AdmonitionIconDefinition> { icons: AdmonitionIconDefinition[]; icon: AdmonitionIconDefinition; text: TextComponent; constructor(app: App, input: TextComponent) { super(app, input.inputEl, iconDefinitions); this.icons = iconDefinitions; this.text = input; this.createPrompts(); this.inputEl.addEventListener("input", this.getItem.bind(this)); } createPrompts() {} getItem() { const v = this.inputEl.value, icon = this.icons.find((iconName) => iconName.name === v.trim()); if (icon == this.icon) return; this.icon = icon; if (this.icons) this.onInputChanged(); } getItemText(item: AdmonitionIconDefinition) { return item.name; } onChooseItem(item: AdmonitionIconDefinition) { this.text.setValue(item.name); this.icon = item; } selectSuggestion({ item }: FuzzyMatch<AdmonitionIconDefinition>) { this.text.setValue(item.name); this.icon = item; this.onClose(); this.close(); } renderSuggestion( result: FuzzyMatch<AdmonitionIconDefinition>, el: HTMLElement ) { let { item, match: matches } = result || {}; let content = el.createDiv({ cls: "suggestion-content admonition-icon" }); let text = content.createDiv("suggestion-text admonition-text"); if (!item) { content.setText(this.emptyStateText); content.parentElement.addClass("is-selected"); return; } const matchElements = matches.matches.map((m) => { return createSpan("suggestion-highlight"); }); for (let i = 0; i < item.name.length; i++) { let match = matches.matches.find((m) => m[0] === i); if (match) { let element = matchElements[matches.matches.indexOf(match)]; text.appendChild(element); element.appendText(item.name.substring(match[0], match[1])); i += match[1] - match[0] - 1; continue; } text.appendText(item.name[i]); } const iconDiv = createDiv("suggestion-flair admonition-suggester-icon"); iconDiv.appendChild(getIconNode(item)); content.appendChild(iconDiv); content.createDiv({ cls: "suggestion-note", text: getIconModuleName(item) }); } getItems() { return this.icons; } } class AdmonitionSuggestionModal extends SuggestionModal<Admonition> { admonitions: Admonition[]; admonition: Admonition; text: TextComponent; constructor(app: App, input: TextComponent, items: Admonition[]) { super(app, input.inputEl, items); this.admonitions = [...items]; this.text = input; this.createPrompts(); this.inputEl.addEventListener("input", this.getItem.bind(this)); } createPrompts() {} getItem() { const v = this.inputEl.value, admonition = this.admonitions.find( (admonition) => admonition.type === v.trim() ); if (admonition == this.admonition) return; this.admonition = admonition; if (this.admonitions) this.onInputChanged(); } getItemText(item: Admonition) { return item.type; } onChooseItem(item: Admonition) { this.text.setValue(item.type); this.admonition = item; } selectSuggestion({ item }: FuzzyMatch<Admonition>) { this.text.setValue(item.type); this.onClose(); this.close(); } renderSuggestion(result: FuzzyMatch<Admonition>, el: HTMLElement) { let { item, match: matches } = result || {}; let content = el.createDiv({ cls: "suggestion-content icon" }); if (!item) { content.setText(this.emptyStateText); content.parentElement.addClass("is-selected"); return; } const matchElements = matches.matches.map((m) => { return createSpan("suggestion-highlight"); }); for (let i = 0; i < item.type.length; i++) { let match = matches.matches.find((m) => m[0] === i); if (match) { let element = matchElements[matches.matches.indexOf(match)]; content.appendChild(element); element.appendText(item.type.substring(match[0], match[1])); i += match[1] - match[0] - 1; continue; } content.appendText(item.type[i]); } const iconDiv = createDiv("suggestion-flair admonition-suggester-icon"); iconDiv .appendChild(getIconNode(item.icon)) .setAttribute("color", `rgb(${item.color})`); content.prepend(iconDiv); } getItems() { return this.admonitions; } } export class InsertAdmonitionModal extends Modal { public type: string; public title: string; public noTitle: boolean; public collapse: "open" | "closed" | "none" = this.plugin.data.autoCollapse ? this.plugin.data.defaultCollapseType : "none"; private element: HTMLElement; admonitionEl: HTMLDivElement; constructor( private plugin: ObsidianAdmonitionPlugin, private editor: Editor ) { super(plugin.app); this.containerEl.addClass("insert-admonition-modal"); this.onOpen = () => this.display(true); } private async display(focus?: boolean) { const { contentEl } = this; contentEl.empty(); const typeSetting = new Setting(contentEl); typeSetting.setName("Admonition Type").addText((t) => { t.setPlaceholder("Admonition Type").setValue(this.type); const modal = new AdmonitionSuggestionModal( this.app, t, this.plugin.admonitionArray ); const build = () => { if ( t.inputEl.value && this.plugin.admonitions[t.inputEl.value] ) { this.type = t.inputEl.value; if (!this.title?.length) { this.title = this.type[0].toUpperCase() + this.type.slice(1).toLowerCase(); } titleInput.setValue(this.title); } else { new Notice("No admonition type by that name exists."); t.inputEl.value = ""; } this.buildAdmonition(); }; t.inputEl.onblur = build; modal.onClose = build; if (focus) { modal.open(); t.inputEl.focus(); } }); let titleInput: TextComponent; const titleSetting = new Setting(contentEl); titleSetting .setName("Admonition Title") .setDesc("Leave blank to render without a title.") .addText((t) => { titleInput = t; t.setValue(this.title); t.onChange((v) => { this.title = v; if (v.length == 0) { this.noTitle = true; } else { this.noTitle = false; } if (this.element) { const admonition = this.plugin.admonitions[this.type]; const element = this.plugin.getAdmonitionElement( this.type, this.title, admonition.icon, admonition.injectColor ?? this.plugin.data.injectColor ? admonition.color : null, this.collapse ); element.createDiv({ cls: "admonition-content", text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla et euismod nulla." }); this.element.replaceWith(element); this.element = element; } }); }); const collapseSetting = new Setting(contentEl); collapseSetting.setName("Make Collapsible").addDropdown((d) => { d.addOption("open", "Open"); d.addOption("closed", "Closed"); d.addOption("none", "None"); d.setValue(this.collapse); d.onChange((v: "open" | "closed" | "none") => { this.collapse = v; this.buildAdmonition(); }); }); this.admonitionEl = this.contentEl.createDiv(); this.buildAdmonition(); new Setting(contentEl) .addButton((b) => b .setButtonText("Insert") .setCta() .onClick(() => { try { let titleLine = "", collapseLine = ""; if ( this.title.length && this.title.toLowerCase() != this.type.toLowerCase() ) { titleLine = `title: ${this.title}\n`; } if ( (this.plugin.data.autoCollapse && this.collapse != this.plugin.data.defaultCollapseType) || (!this.plugin.data.autoCollapse && this.collapse != "none") ) { collapseLine = `collapse: ${this.collapse}\n`; } this.editor.getDoc().replaceSelection( `\`\`\`ad-${ this.type }\n${titleLine}${collapseLine} ${this.editor.getDoc().getSelection()} \`\`\`\n` ); const cursor = this.editor.getCursor(); this.editor.setCursor(cursor.line - 3); } catch (e) { new Notice( "There was an issue inserting the admonition." ); } this.close(); }) ) .addExtraButton((b) => { b.setIcon("cross") .setTooltip("Cancel") .onClick(() => this.close()); b.extraSettingsEl.setAttr("tabindex", 0); b.extraSettingsEl.onkeydown = (evt) => { evt.key == "Enter" && this.close(); }; }); } buildAdmonition() { this.admonitionEl.empty(); if (this.type && this.plugin.admonitions[this.type]) { const admonition = this.plugin.admonitions[this.type]; this.element = this.plugin.getAdmonitionElement( this.type, this.title, admonition.icon, admonition.injectColor ?? this.plugin.data.injectColor ? admonition.color : null, this.collapse ); this.element.createDiv({ cls: "admonition-content", text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla et euismod nulla." }); this.admonitionEl.appendChild(this.element); } } }
the_stack
import React, { FunctionComponent } from "react"; import { TimerActionControlProps } from "./types"; import { Capability, useGoToLocationPresetsQuery, useMapSegmentationPropertiesQuery, useSegmentsQuery, useZonePresetsQuery, } from "../../api"; import { Box, Checkbox, CircularProgress, FormControl, FormControlLabel, IconButton, InputLabel, List, ListItem, ListItemText, ListSubheader, MenuItem, Select, Typography, } from "@mui/material"; import { Add as AddIcon, Remove as RemoveIcon } from "@mui/icons-material"; import { deepCopy } from "../../utils"; export const validateParams: Record< string, (props: Record<string, any>) => boolean > = { full_cleanup: () => { return true; }, zone_cleanup: (props) => { return props.zone_id && props.zone_id !== "none"; }, segment_cleanup: (props) => { return props.segment_ids?.length > 0 && (props.iterations ?? 1 > 0); }, goto_location: (props) => { return props.goto_id && props.goto_id !== "none"; }, }; export const FullCleanupControls: FunctionComponent<TimerActionControlProps> = () => { // No params for full_cleanup return null; }; export const ZoneCleanupControls: FunctionComponent<TimerActionControlProps> = ({ disabled, params, setParams }) => { const selectedZoneId = params.zone_id ?? "none"; const { data: zonePresets, isLoading: zonePresetsLoading, isError: zonePresetsError, } = useZonePresetsQuery(); const zoneMenuItems = React.useMemo(() => { if (!zonePresets) { return null; } return zonePresets.map(({ name, id }) => { return ( <MenuItem key={id} value={id}> {name || "Unnamed zone: " + id} </MenuItem> ); }); }, [zonePresets]); if (zonePresetsLoading) { return <CircularProgress />; } if (zonePresetsError) { return ( <Typography color="error"> Error loading {Capability.ZoneCleaning} </Typography> ); } return ( <FormControl> <InputLabel id={"zone-label"}>Select zone</InputLabel> <Select labelId={"zone-label"} id={"zone-select"} value={selectedZoneId} label="Select zone" disabled={disabled} onChange={(e) => { setParams({ zone_id: e.target.value, }); }} > <MenuItem value={"none"}> <em>No zone selected</em> </MenuItem> {zoneMenuItems} </Select> </FormControl> ); }; export const SegmentCleanupControls: FunctionComponent<TimerActionControlProps> = ({ disabled, params, setParams }) => { const segmentIds: Array<string> = React.useMemo(() => { return (params.segment_ids as Array<string>) || []; }, [params.segment_ids]); const iterationCount: number = (params.iterations as number) || 1; const customOrder: boolean = (params.custom_order as boolean) ?? false; const { data: segmentationProps, isLoading: segmentationPropsLoading, isError: segmentationPropsError, } = useMapSegmentationPropertiesQuery(); const { data: segments, isLoading: segmentsLoading, isError: segmentsLoadError, } = useSegmentsQuery(); const getSegmentLabel = React.useCallback( (segmentId: string) => { if (!segments) { return ""; } return ( segments.find((s) => { return s.id === segmentId; })?.name || "Unnamed segment: " + segmentId ); }, [segments] ); const selectedSegmentList = React.useMemo(() => { return segmentIds.map((segmentId) => { return ( <ListItem key={segmentId} secondaryAction={ <IconButton disabled={disabled} edge="end" aria-label="remove" onClick={() => { const newParams = deepCopy(params); const sids: Array<string> = newParams.segment_ids as Array<string>; const removeIdx = sids.indexOf(segmentId); if (removeIdx !== -1) { sids.splice(removeIdx, 1); } setParams(newParams); }} > <RemoveIcon /> </IconButton> } > <ListItemText primary={getSegmentLabel(segmentId)} /> </ListItem> ); }); }, [getSegmentLabel, params, setParams, disabled, segmentIds]); const availableSegmentList = React.useMemo(() => { if (!segments) { return null; } return segments .filter((s) => { return segmentIds.indexOf(s.id) === -1; }) .map((segment) => { return ( <ListItem key={segment.id} secondaryAction={ <IconButton disabled={disabled} edge="end" aria-label="add" onClick={() => { const newParams = deepCopy(params); if (newParams.segment_ids) { const sids: Array<string> = newParams.segment_ids as Array<string>; sids.push(segment.id); } else { newParams.segment_ids = [ segment.id, ]; } setParams(newParams); }} > <AddIcon /> </IconButton> } > <ListItemText primary={ segment.name || "Unnamed segment: " + segment.id } /> </ListItem> ); }); }, [disabled, params, segmentIds, setParams, segments]); if (segmentationPropsLoading || segmentsLoading) { return <CircularProgress />; } if ( segmentationPropsError || segmentsLoadError || !segmentationProps || !segments ) { return ( <Typography color="error"> Error loading {Capability.MapSegmentation} </Typography> ); } const iterationItems = []; for ( let i = segmentationProps.iterationCount.min; i <= segmentationProps.iterationCount.max; i++ ) { iterationItems.push( <MenuItem key={i} value={i}> {i} {i === 1 ? "Iteration" : "Iterations"} </MenuItem> ); } // Since material-ui does not support reordering lists yet, we implement our custom sorting // See https://next.material-ui.com/getting-started/supported-components/#main-content return ( <> <FormControl> <InputLabel id="segment-iterations-label"> Iterations </InputLabel> <Select labelId="segment-iterations-label" id="segment-iterations-select" value={iterationCount} disabled={disabled} label="Iterations" onChange={(e) => { const newParams = deepCopy(params); newParams.iterations = e.target.value; setParams(newParams); }} > {iterationItems} </Select> </FormControl> <Box pt={1} /> {segmentationProps.customOrderSupport && ( <FormControlLabel control={ <Checkbox disabled={disabled} checked={customOrder} onChange={(e) => { const newParams = deepCopy(params); newParams.custom_order = e.target.checked; setParams(newParams); }} /> } label="Use custom order" /> )} <Box pt={1} /> <List dense subheader={ <ListSubheader component="div"> Available segments </ListSubheader> } > {availableSegmentList} </List> <List dense subheader={ <ListSubheader component="div"> Selected segments </ListSubheader> } > {selectedSegmentList} </List> </> ); }; export const GoToLocationControls: FunctionComponent<TimerActionControlProps> = ({ params, setParams, disabled }) => { const selectedGoToId = params.goto_id ?? "none"; const { data: goToLocations, isLoading: goToLocationPresetsLoading, isError: goToLocationPresetLoadError, } = useGoToLocationPresetsQuery(); const goToMenuItems = React.useMemo(() => { if (!goToLocations) { return null; } return goToLocations.map(({ name, id }) => { return ( <MenuItem key={id} value={id}> {name || "Unnamed go to location: " + id} </MenuItem> ); }); }, [goToLocations]); if (goToLocationPresetsLoading) { return <CircularProgress />; } if (goToLocationPresetLoadError) { return ( <Typography color="error"> Error loading {Capability.GoToLocation} </Typography> ); } return ( <FormControl> <InputLabel id={"go-to-location-label"}> Select go to location </InputLabel> <Select labelId={"go-to-location-label"} id={"go-to-location-select"} value={selectedGoToId} label="Select go to location" disabled={disabled} onChange={(e) => { setParams({ goto_id: e.target.value, }); }} > <MenuItem value={"none"}> <em>No go to location selected</em> </MenuItem> {goToMenuItems} </Select> </FormControl> ); };
the_stack
import * as React from 'react'; import styles from './Attachments.module.scss'; import * as tsStyles from './AttachmentsStyles'; import { ITaskExternalReference } from '../../../../services/ITaskExternalReference'; import { DefaultPalette, Icon, DefaultButton, IContextualMenuProps, IContextualMenuItem, IconType, Link, IColumn, DetailsList, DetailsListLayoutMode, getTheme, MessageBar, MessageBarType, Spinner, SpinnerSize, LinkBase, Stack, } from 'office-ui-fabric-react'; import { IAttachmentsProps } from './IAttachmentsProps'; import { IAttachmentsState } from './IAttachmentsState'; import { SelectionMode } from '@pnp/spfx-controls-react'; import { UploadFromSharePoint } from '../../../../Controls/UploadFromSharePoint'; import { AddLink } from './../../../../Controls/AddLink'; import { UploadFile } from './../../../../Controls/UploadFile'; import { IListViewItems } from './IListViewItems'; import { utilities } from '../../../../utilities'; import { IFile } from './IFile'; import { ITaskDetails } from '../../../../services/ITaskDetails'; import { EditLink } from '../../../../Controls/EditLink'; import * as strings from 'MyTasksWebPartStrings'; export class Attachments extends React.Component<IAttachmentsProps, IAttachmentsState> { private _listViewItems: IListViewItems[] = []; private _util = new utilities(); private _selectedItem: IListViewItems = {} as IListViewItems; private _theme = getTheme(); constructor(props: IAttachmentsProps) { super(props); const listAttachmentsItemMenuProps: IContextualMenuProps = { items: [ { key: '0', text: strings.EditLabel, iconProps: { iconName: 'Edit' }, onClick: this._editAttachment.bind(this) // onClick: this.onClickFilterAllTasks.bind(this) }, { key: '1', text: strings.RemoveLabel, iconProps: { iconName: 'Delete' }, onClick: this._removeAttachment.bind(this) // onClick: this.onClickFilterNotStartedTasks.bind(this) } ] }; const columns: IColumn[] = [ { key: 'column1', name: 'File_x0020_Type', className: tsStyles.classNames.fileIconCell, iconClassName: tsStyles.classNames.fileIconHeaderIcon, iconName: 'Page', isIconOnly: true, fieldName: 'name', minWidth: 28, maxWidth: 28, onRender: (item: IListViewItems) => { return ( <div className={tsStyles.classNames.centerColumn}> <Icon iconType={IconType.Image} imageProps={{ src: item.fileTypeImageUrl, height: 26, width: 26 }} /> </div> ); } }, { name: 'Name', key: 'column2', fieldName: 'FileName', minWidth: 430, maxWidth: 430, isResizable: false, data: 'string', isPadded: true, onRender: (item: IListViewItems) => { return ( <div className={tsStyles.classNames.centerColumn}> <Stack horizontal horizontalAlign='start' gap='10'> <Link onClick={(event: React.MouseEvent<HTMLAnchorElement | HTMLElement | HTMLButtonElement | LinkBase, MouseEvent>) => { event.preventDefault(); window.open(decodeURIComponent(item.fileUrl)); }}> {item.fileName} </Link> </Stack> </div> ); } }, { name: 'more', key: 'column3', fieldName: 'FileName', minWidth: 20, maxWidth: 20, isResizable: true, data: 'string', isPadded: true, onRender: (item: IListViewItems) => { return ( <div className={tsStyles.classNames.centerColumn}> <DefaultButton style={{ backgroundColor: '#1fe0' }} iconProps={{ iconName: 'More' }} text={''} menuIconProps={{ iconName: '' }} menuProps={listAttachmentsItemMenuProps} disabled={false} id={item.fileUrl} checked={true} /> </div> ); } } ]; this.state = { value: '', displayUploadFromSharePoint: false, displayLinkAttachment: false, editLinkAttachment: false, uploadFile: false, renderReferences: [], columns: columns, listViewItems: [], taskDetails: this.props.taskDetails, hasError: false, errorMessage: '', isLoading: false, percent: 0, showDefaultLinkImage: false }; } public componentDidUpdate(prevProps: IAttachmentsProps, prevState: IAttachmentsState): void {} private _loadReferences = async () => { const referenceKeys = Object.keys(this.state.taskDetails.references); this._listViewItems = []; for (const key of referenceKeys) { const reference = this.state.taskDetails.references[key]; if (reference) { const fileImageUrl = await this._util.GetFileImageUrl(decodeURIComponent(key)); // reference.type !== 'Other' ? await this._util.GetFileImageUrl(decodeURIComponent(key)) : `${decodeURIComponent(key)}/favicon.ico`; this._listViewItems.push({ fileName: reference.alias, fileUrl: decodeURIComponent(key), fileTypeImageUrl: fileImageUrl, isUploading: false, fileUploadPercent: 0 }); } } this.setState({ listViewItems: this._listViewItems, isLoading: false }); }; /** * Components did mount * @returns did mount */ public async componentDidMount(): Promise<void> { this.setState({ isLoading: true }); await this._loadReferences(); } /** * Determines whether dismiss upload from share point on */ private _onDismissUploadFromSharePoint = () => { this.setState({ displayUploadFromSharePoint: false }); }; /** * Upload from share point of attachments */ private _uploadFromSharePoint = ( ev?: React.MouseEvent<HTMLElement, MouseEvent> | React.KeyboardEvent<HTMLElement>, item?: IContextualMenuItem ) => { this.setState({ displayUploadFromSharePoint: true }); }; /** * Link attachment of attachments */ private _onActiveItemChanged = (item: IListViewItems, index: number, ev: React.FocusEvent<HTMLElement>) => { ev.preventDefault(); this._selectedItem = item; }; /** * Link attachment of attachments */ private _LinkAttachment = ( ev?: React.MouseEvent<HTMLElement, MouseEvent> | React.KeyboardEvent<HTMLElement>, item?: IContextualMenuItem ) => { this.setState({ displayLinkAttachment: true }); }; /** * Edit attachment of attachments */ private _editAttachment = async ( event?: React.MouseEvent<HTMLElement, MouseEvent> | React.KeyboardEvent<HTMLElement>, item?: IContextualMenuItem ): Promise<void> => { event.preventDefault(); this.setState({ editLinkAttachment: true }); }; /** * Remove attachment of attachments */ private _removeAttachment = async ( ev?: React.MouseEvent<HTMLElement, MouseEvent> | React.KeyboardEvent<HTMLElement>, item?: IContextualMenuItem ) => { try { let newReferences: ITaskExternalReference = this.state.taskDetails.references; const fileFullUrl: string = `${this._selectedItem.fileUrl}`.replace(/\./g, '%2E').replace(/\:/g, '%3A'); for (const referenceKey of Object.keys(this.state.taskDetails.references)) { const originalReference = this.state.taskDetails.references[referenceKey]; if (fileFullUrl == referenceKey) { newReferences[referenceKey] = null; } else { newReferences[referenceKey] = { alias: originalReference.alias, '@odata.type': '#microsoft.graph.plannerExternalReference', type: originalReference.type, previewPriority: ' !' }; } } const updatedTaskDetails = await this.props.spservice.updateTaskDetailsProperty( this.state.taskDetails.id, 'References', newReferences, this.state.taskDetails['@odata.etag'] ); delete newReferences[fileFullUrl]; this.setState({ hasError: false, errorMessage: '', taskDetails: updatedTaskDetails }); await this._loadReferences(); } catch (error) { this.setState({ hasError: true, errorMessage: error.message }); } }; /** * Determines whether dismiss link attachment on */ private _onDismissLinkAttachment = (updTaskDetails: ITaskDetails) => { this.setState({ displayLinkAttachment: false, taskDetails: updTaskDetails }); this._loadReferences(); // tslint:disable-next-line: semicolon }; /** * Determines whether dismiss edit link attachment on */ private _onDismissEditLinkAttachment = (updTaskDetails: ITaskDetails) => { this.setState({ editLinkAttachment: false, taskDetails: updTaskDetails }); this._loadReferences(); // tslint:disable-next-line: semicolon }; /** * Upload file of attachments */ private _uploadFile = () => { this.setState({ uploadFile: true }); }; /** * Determines whether file upload on */ private _onFileUpload = async (file: File, groupDefaultLibrary: string) => { const fileUrl = `${decodeURIComponent(groupDefaultLibrary)}/${file.name}`; const fileType = await this._util.getFileType(file.name); let newReferences: ITaskExternalReference = {} as ITaskExternalReference; const fileFullUrl: string = `${fileUrl}`.replace(/\./g, '%2E').replace(/\:/g, '%3A'); newReferences[fileFullUrl] = { alias: file.name, '@odata.type': '#microsoft.graph.plannerExternalReference', type: fileType, previewPriority: ' !' }; for (const referenceKey of Object.keys(this.state.taskDetails.references)) { const originalReference = this.state.taskDetails.references[referenceKey]; newReferences[referenceKey] = { alias: originalReference.alias, '@odata.type': '#microsoft.graph.plannerExternalReference', type: originalReference.type, previewPriority: ' !' }; } this.setState({ hasError: false, errorMessage: '', taskDetails: { ...this.state.taskDetails, references: newReferences } }); await this._loadReferences(); try { const updatedTaskDetails = await this.props.spservice.updateTaskDetailsProperty( this.state.taskDetails.id, 'References', newReferences, this.state.taskDetails['@odata.etag'] ); this.setState({ taskDetails: updatedTaskDetails , uploadFile: false }); // const rs:FileAddResult = await web.getFolderByServerRelativeUrl(documentLibrary).files.add(fileName,fileB64,true); } catch (error) { console.log(error); } }; /** * Determines whether select file on */ private _onSelectFile = async (file: IFile) => { try { const fileType = await this._util.getFileType(file.FileLeafRef); let newReferences: ITaskExternalReference = {} as ITaskExternalReference; const fileFullUrl: string = `${location.origin}${file.fileUrl}`.replace(/\./g, '%2E').replace(/\:/g, '%3A'); newReferences[fileFullUrl] = { alias: file.FileLeafRef, '@odata.type': '#microsoft.graph.plannerExternalReference', type: fileType, previewPriority: ' !' }; for (const referenceKey of Object.keys(this.state.taskDetails.references)) { const originalReference = this.state.taskDetails.references[referenceKey]; newReferences[referenceKey] = { alias: originalReference.alias, '@odata.type': '#microsoft.graph.plannerExternalReference', type: originalReference.type, previewPriority: ' !' }; } const updatedTaskDetails = await this.props.spservice.updateTaskDetailsProperty( this.state.taskDetails.id, 'References', newReferences, this.state.taskDetails['@odata.etag'] ); this.setState({ displayUploadFromSharePoint: false, hasError: false, errorMessage: '', taskDetails: updatedTaskDetails }); await this._loadReferences(); } catch (error) { this.setState({ hasError: true, errorMessage: error.message }); } }; /** * Renders attachments * @returns render */ public render(): React.ReactElement<IAttachmentsProps> { const addAttachmentMenuProps: IContextualMenuProps = { items: [ { key: '0', text: strings.FileLabel, iconProps: { iconName: 'Upload' }, onClick: this._uploadFile // onClick: this.onClickFilterAllTasks.bind(this) }, { key: '1', text: strings.LinkLabel, iconProps: { iconName: 'Link' }, onClick: this._LinkAttachment // onClick: this.onClickFilterNotStartedTasks.bind(this) }, { key: '2', text: strings.SharePointLabel, iconProps: { iconName: 'SharepointLogo', style: { color: this._theme.palette.themePrimary } }, onClick: this._uploadFromSharePoint // onClick: this.onClickFilterStartedTasks.bind(this) } ] }; return ( <div> <DefaultButton style={{ backgroundColor: this._theme.palette.neutralLighter }} iconProps={{ iconName: 'Add' }} text={strings.AddAttachmentLabel} menuIconProps={{ iconName: '' }} menuProps={addAttachmentMenuProps} disabled={false} checked={true} /> {this.state.uploadFile && ( <UploadFile spservice={this.props.spservice} groupId={this.props.groupId} onFileUpload={this._onFileUpload} /> )} <div style={{ width: '100%', marginTop: 15 }} /> {this.state.hasError && <MessageBar messageBarType={MessageBarType.error}>{this.state.errorMessage}</MessageBar>} {this.state.isLoading && <Spinner size={SpinnerSize.medium} />} <div style={{ marginBottom: 40 }}> <DetailsList items={this.state.listViewItems} compact={false} columns={this.state.columns} selectionMode={SelectionMode.none} setKey='none' onActiveItemChanged={this._onActiveItemChanged} layoutMode={DetailsListLayoutMode.justified} isHeaderVisible={false} /> </div> {this.state.displayUploadFromSharePoint && ( <UploadFromSharePoint groupId={this.props.groupId} spservice={this.props.spservice} displayDialog={this.state.displayUploadFromSharePoint} onDismiss={this._onDismissUploadFromSharePoint} onSelectedFile={this._onSelectFile} currentReferences={this.state.taskDetails.references} /> )} {this.state.displayLinkAttachment && ( <AddLink spservice={this.props.spservice} displayDialog={true} onDismiss={this._onDismissLinkAttachment} taskDetails={this.state.taskDetails} /> )} {this.state.editLinkAttachment && ( <EditLink spservice={this.props.spservice} displayDialog={true} onDismiss={this._onDismissEditLinkAttachment} taskDetails={this.state.taskDetails} link={this._selectedItem.fileUrl} /> )} </div> ); } }
the_stack
import { Lifecycle, LifecyclePeer, LifecycleChannel } from '../src'; import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import { Wallet, Wallets } from 'fabric-network'; import * as path from 'path'; import { ConnectOptions } from 'fabric-common'; const should: Chai.Should = chai.should(); chai.use(sinonChai); describe('Lifecycle', () => { describe('addPeer', () => { it('should add a peer', () => { const lifecycle: Lifecycle = new Lifecycle(); lifecycle['peers'].size.should.equal(0); lifecycle.addPeer({ name: 'myPeer', url: 'grpcs://localhost:7051', mspid: 'myMSPID', pem: '-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n' }); lifecycle['peers'].size.should.equal(1); }); it('should handle no options', () => { const lifecycle: Lifecycle = new Lifecycle(); lifecycle['peers'].size.should.equal(0); (() => { // @ts-ignore lifecycle.addPeer(); }).should.throw('Missing options parameter'); lifecycle['peers'].size.should.equal(0); }); it('should handle no name option', () => { const lifecycle: Lifecycle = new Lifecycle(); lifecycle['peers'].size.should.equal(0); (() => { // @ts-ignore lifecycle.addPeer({ url: 'grpcs://localhost:7051', mspid: 'myMSPID', pem: '-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n' }); }).should.throw('Missing option name'); lifecycle['peers'].size.should.equal(0); }); it('should handle no url option', () => { const lifecycle: Lifecycle = new Lifecycle(); lifecycle['peers'].size.should.equal(0); (() => { // @ts-ignore lifecycle.addPeer({ name: 'myPeer', mspid: 'myMSPID', pem: '-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n' }); }).should.throw('Missing option url'); lifecycle['peers'].size.should.equal(0); }); it('should handle no mspid option', () => { const lifecycle: Lifecycle = new Lifecycle(); lifecycle['peers'].size.should.equal(0); (() => { // @ts-ignore lifecycle.addPeer({ name: 'myPeer', url: 'grpcs://localhost:7051', pem: '-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n' }); }).should.throw('Missing option mspid'); lifecycle['peers'].size.should.equal(0); }); }); describe('getPeer', () => { let lifecycle: Lifecycle; let wallet: Wallet; before(async () => { lifecycle = new Lifecycle(); lifecycle.addPeer({ name: 'myPeer', url: 'grpcs://localhost:7051', mspid: 'myMSPID', pem: '-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n' }); wallet = await Wallets.newFileSystemWallet(path.join(__dirname, 'tmp', 'wallet')); }); it('should get the peer and set the credentials', () => { const peer: LifecyclePeer = lifecycle.getPeer('myPeer', wallet, 'myIdentity'); should.exist(peer['wallet']); // @ts-ignore peer['identity'].should.equal('myIdentity'); }); it('should handle no name set', async () => { (() => { // @ts-ignore lifecycle.getPeer(undefined, wallet, 'myIdentity'); }).should.throw('Missing parameter name'); }); it('should handle no wallet set', async () => { (() => { // @ts-ignore lifecycle.getPeer('myPeer', undefined, 'myIdentity'); }).should.throw('Missing parameter wallet'); }); it('should handle no identity set', async () => { (() => { // @ts-ignore lifecycle.getPeer('myPeer', wallet, undefined); }).should.throw('Missing parameter identity'); }); it('should handle peer not existing', async () => { (() => { lifecycle.getPeer('randomPeer', wallet, 'myIdentity'); }).should.throw('Could not get peer randomPeer, no peer with that name has been added'); }); }); describe('peerExists', () => { let lifecycle: Lifecycle; before(async () => { lifecycle = new Lifecycle(); lifecycle.addPeer({ name: 'myPeer', url: 'grpcs://localhost:7051', mspid: 'myMSPID', pem: '-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n' }); }); it('should return true if the peer exists', () => { const exists: boolean = lifecycle.peerExists('myPeer'); exists.should.equal(true); }); it('should return false if the peer does not exist', () => { const exists: boolean = lifecycle.peerExists('myPeer2'); exists.should.equal(false); }); it('should handle no name set', async () => { (() => { // @ts-ignore lifecycle.peerExists(); }).should.throw('Missing parameter name'); }); }); describe('getAllPeerNames', () => { let lifecycle: Lifecycle; before(async () => { lifecycle = new Lifecycle(); lifecycle.addPeer({ name: 'myPeer', url: 'grpcs://localhost:7051', mspid: 'myMSPID', pem: '-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n' }); lifecycle.addPeer({ name: 'anotherMyPeer', url: 'grpcs://localhost:8051', mspid: 'myMSPID', pem: '-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n' }); }); it('should get all the peer names', () => { const result: string[] = lifecycle.getAllPeerNames(); result.should.deep.equal(['anotherMyPeer', 'myPeer']); }); }); describe('getAllPeerNamesForOrg', () => { let lifecycle: Lifecycle; before(async () => { lifecycle = new Lifecycle(); lifecycle.addPeer({ name: 'myPeer', url: 'grpcs://localhost:7051', mspid: 'myMSPID', pem: '-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n' }); lifecycle.addPeer({ name: 'anotherMyPeer', url: 'grpcs://localhost:8051', mspid: 'myMSPID', pem: '-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n' }); lifecycle.addPeer({ name: 'anotherMyPeer2', url: 'grpcs://localhost:8051', mspid: 'myOtherMSPID', pem: '-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n' }); }); it('should get all the peer names for an org', () => { const result: string[] = lifecycle.getAllPeerNamesForOrg('myMSPID'); result.should.deep.equal(['anotherMyPeer', 'myPeer']); }); }); describe('getChannel', () => { let lifecycle: Lifecycle; let wallet: Wallet; before(async () => { lifecycle = new Lifecycle(); wallet = await Wallets.newFileSystemWallet(path.join(__dirname, 'tmp', 'wallet')); }); it('should get an instance of LifecycleChannel', () => { const channel: LifecycleChannel = lifecycle.getChannel('mychannel', wallet, 'myIdentity'); channel['channelName'].should.equal('mychannel'); channel['wallet'].should.deep.equal(wallet); channel['identity'].should.equal('myIdentity'); }); it('should handle channelName not set', () => { (() => { // @ts-ignore lifecycle.getChannel(undefined, wallet, 'myIdentity'); }).should.throw('parameter channelName is missing'); }); it('should handle wallet not set', () => { (() => { // @ts-ignore lifecycle.getChannel('mychannel', undefined, 'myIdentity'); }).should.throw('parameter wallet is missing'); }); it('should handle identity not set', () => { (() => { // @ts-ignore lifecycle.getChannel('mychannel', wallet, undefined); }).should.throw('parameter identity is missing'); }); }); describe('addOrderer', () => { let lifecycle: Lifecycle; before(() => { lifecycle = new Lifecycle(); }); it('should add an orderer', () => { lifecycle.addOrderer({ name: 'myOrderer', url: 'grpcs://localhost:7050', pem: '-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n' }); const ordererOptions: ConnectOptions = lifecycle.getOrderer('myOrderer'); ordererOptions.pem.should.equal('-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n'); ordererOptions.url.should.equal('grpcs://localhost:7050'); }); it('should add an orderer with sslTargetNameOverride', () => { lifecycle.addOrderer({ name: 'myOrderer', url: 'grpcs://localhost:7050', pem: '-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n', sslTargetNameOverride: 'localhost' }); const ordererOptions: ConnectOptions = lifecycle.getOrderer('myOrderer'); ordererOptions.pem.should.equal('-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n'); ordererOptions.url.should.equal('grpcs://localhost:7050'); ordererOptions['ssl-target-name-override'].should.equal('localhost'); }); it('should add an orderer with apiOptions', () => { lifecycle.addOrderer({ name: 'myOrderer', url: 'grpcs://localhost:7050', pem: '-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n', apiOptions: { 'grpc.default_authority': 'orderer.127-0-0-1.nip.io:8080', 'grpc.ssl_target_name_override': 'orderer.127-0-0-1.nip.io:8080' } }); const ordererOptions: ConnectOptions = lifecycle.getOrderer('myOrderer'); ordererOptions.pem.should.equal('-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n'); ordererOptions.url.should.equal('grpcs://localhost:7050'); ordererOptions['grpc.default_authority'].should.equal('orderer.127-0-0-1.nip.io:8080'); ordererOptions['grpc.ssl_target_name_override'].should.equal('orderer.127-0-0-1.nip.io:8080'); }); it('should add an orderer with request timeout', () => { lifecycle.addOrderer({ name: 'myOrderer', url: 'grpcs://localhost:7050', requestTimeout: 70000, pem: '-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n' }); const ordererOptions: ConnectOptions = lifecycle.getOrderer('myOrderer'); ordererOptions.pem.should.equal('-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n'); ordererOptions.url.should.equal('grpcs://localhost:7050'); ordererOptions.requestTimeout.should.equal(70000); }); it('should add an orderer with no pem', () => { lifecycle.addOrderer({ name: 'myOrderer', url: 'grpc://localhost:7050', }); const ordererOptions: ConnectOptions = lifecycle.getOrderer('myOrderer'); ordererOptions.url.should.equal('grpc://localhost:7050'); }); it('should handle no options', () => { (() => { // @ts-ignore lifecycle.addOrderer(); }).should.throw('parameter options is missing'); }); it('should handle no name', () => { (() => { // @ts-ignore lifecycle.addOrderer({ url: 'grpcs://localhost:7050', pem: '-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n' }); }).should.throw('missing option name'); }); it('should handle no url', () => { (() => { // @ts-ignore lifecycle.addOrderer({ name: 'myOrderer', pem: '-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n' }); }).should.throw('missing option url'); }); }); describe('getAllOrdererNames', () => { let lifecycle: Lifecycle; beforeEach(() => { lifecycle = new Lifecycle(); lifecycle.addOrderer({ name: 'myOrderer', url: 'grpcs://localhost:7050', pem: '-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n' }); lifecycle.addOrderer({ name: 'anotherMyOrderer', url: 'grpcs://localhost:7050', pem: '-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n' }); }); it('should get all the names of the orderers', () => { const result: string[] = lifecycle.getAllOrdererNames(); result.should.deep.equal(['anotherMyOrderer', 'myOrderer']); }); }); });
the_stack
namespace com.keyman.osk { // Manages the language selection UI for touch-form factors, which is triggered by an OSK key. // Used by 'native'-mode KMW only - the Android and iOS embedding apps implement their own menus. export class LanguageMenu { keyman: KeymanBase; private lgList: HTMLDivElement; private shim: HTMLDivElement; private scrolling: boolean; private activeLgNo: number; private y0: number; constructor(keyman: KeymanBase) { this.keyman = keyman; this.scrolling = false; this.shim = this.constructShim(); } constructShim(): HTMLDivElement { let languageMenu = this; let shim = this.keyman.util._CreateElement('div'); let osk = this.keyman.osk; shim.id='kmw-language-menu-background'; shim.addEventListener('touchstart', function(e) { e.preventDefault(); languageMenu.hide(); // Display build only if touching menu, space *and* one other point on screen (build 369) if(e.touches.length > 2) { var sX=e.touches[1].pageX,sY=e.touches[1].pageY; let spaceBar = osk.vkbd.spaceBar; if(sX > spaceBar.offsetLeft && sX < spaceBar.offsetLeft+spaceBar.offsetWidth && sY > spaceBar.offsetTop && sY < spaceBar.offsetTop+spaceBar.offsetHeight) { osk.showBuild(); } } },false); return shim; } /** * Display list of installed keyboards in pop-up menu **/ show() { var n=0, kbdList=this.keyman.keyboardManager.keyboardStubs, nKbds=kbdList.length; let util = this.keyman.util; if(nKbds < 1) { return; } // Create the menu list container element var menu=this.lgList=util._CreateElement('div'),ss; this.lgList.id='kmw-language-menu'; // Insert a transparent overlay to prevent anything else happening during keyboard selection, // but allow the menu to be closed if anywhere else on screen is touched let osk = this.keyman.osk; let languageMenu = this; document.body.appendChild(this.shim); // Add two nested DIVs to properly support iOS scrolling with momentum // c.f. https://github.com/joelambert/ScrollFix/issues/2 var m2=util._CreateElement('div'),s2=m2.style, m3=util._CreateElement('div'),s3=m3.style; m2.id='kmw-menu-scroll-container'; m3.id='kmw-menu-scroller'; // Support momentum scrolling on iOS if('WebkitOverflowScrolling' in s2) { s2.WebkitOverflowScrolling='touch'; } m2.appendChild(m3); menu.appendChild(m2); // Add menu index strip var i,x,mx=util._CreateElement('div'); mx.id='kmw-menu-index'; for(i=1; i<=26; i++) { x=util._CreateElement('p'); x.innerHTML=String.fromCharCode(i+64); mx.appendChild(x); } // Add index selection (for a large menu) mx.addEventListener('touchstart',function(e){ languageMenu.scrollToLanguage(e, m2, m3); }, false); mx.addEventListener('touchend',function(e){ e.stopPropagation(); e.preventDefault(); }, false); menu.appendChild(mx); //TODO: not sure if either of these two handlers ar actually needed. touchmove handler may be doing all that is necessary. // Add scroll end event handling to override body scroll menu.addEventListener('scroll',function(e){ languageMenu.scrolling=true; },false); m2.addEventListener('scroll',function(e){ //this.lgList.scrolling=true; if(m2.scrollTop < 1) { m2.scrollTop=1; } if(m2.scrollTop > m2.scrollHeight-m2.offsetHeight-1) { m2.scrollTop=m2.scrollHeight-m2.offsetHeight-1; } },false); // Add a list of keyboards to the innermost DIV this.activeLgNo=this.addLanguages(m3,kbdList); // Get number of visible (language) selectors var nLgs=m3.childNodes.length-1; // Do not display until sizes have been calculated this.lgList.style.visibility='hidden'; // Append menu to document body, not to OSK document.body.appendChild(this.lgList); // Adjust size for viewport scaling (probably not needed for iOS, but check!) if(util.device.OS == 'Android' && 'devicePixelRatio' in window) { this.lgList.style.fontSize=(2/window.devicePixelRatio)+'em'; } // Adjust width for pixel scaling on Android tablets if(util.device.OS == 'Android' && util.device.formFactor == 'tablet' && 'devicePixelRatio' in window) { var w=parseInt(util.getStyleValue(menu,'width'),10), ms=menu.style; if(!isNaN(w)) { ms.width=ms.maxWidth=(2*w/window.devicePixelRatio)+'px'; } w=parseInt(util.getStyleValue(m2,'width'),10); ms=m2.style; if(!isNaN(w)) { ms.width=ms.maxWidth=(2*w/window.devicePixelRatio)+'px'; } w=parseInt(util.getStyleValue(m3,'width'),10); ms=m3.style; if(!isNaN(w)) { ms.width=ms.maxWidth=(2*w/window.devicePixelRatio)+'px'; } } // Adjust initial top and height of menu this.adjust(0); // Adjust the index font size and line height var dy=(<HTMLElement>mx.childNodes[1]).offsetTop-(<HTMLElement>mx.childNodes[0]).offsetTop, lineHeight=Math.floor(menu.offsetHeight/26.0), scale=Math.round(100.0*lineHeight/dy)/100.0, factor=(scale > 0.6 ? 1 : 2); if(scale > 1.25) { scale=1.25; } for(i=0;i<26;i++) { var qs=(<HTMLElement>mx.childNodes[i]).style; if(factor == 2 && (i%2) == 1) { qs.display='none'; } else { qs.fontSize=(scale*factor)+'em'; qs.lineHeight=(lineHeight*factor)+'px'; } } // Increase width of outer menu DIV by index, else hide index var menuWidth=m2.offsetWidth; if(m2.scrollHeight > m2.offsetHeight+3) { menuWidth = menuWidth+mx.offsetWidth; } else { mx.style.display='none'; } menu.style.width=menuWidth+'px'; // Now display the menu this.lgList.style.visibility=''; // Set initial scroll to show current language (but never less than 1, to avoid dragging body) var top=(<HTMLElement>m3.firstChild).offsetHeight*this.activeLgNo+1; m2.scrollTop=top; // The scrollTop value is limited by the device, and must be limited to avoid dragging the document body if(m2.scrollTop < top) { m2.scrollTop=m2.scrollHeight-m2.offsetHeight; } if(m2.scrollTop > m2.scrollHeight-m2.offsetHeight-1) { m2.scrollTop=m2.scrollHeight-m2.offsetHeight-1; } } /** * Adjust top and height of language menu * * @param {number} nKbds number of displayed keyboards to add to number of languages **/ adjust(nKbds: number) { let osk = this.keyman.osk; let util = this.keyman.util; let device = util.device; var menu=this.lgList, m2=<HTMLElement>menu.firstChild, m3=<HTMLElement>m2.firstChild, barWidth=0,s=menu.style,mx=<HTMLElement>menu.childNodes[1], maxHeight=window.innerHeight-osk.vkbd.lgKey.offsetHeight-16, nItems=m3.childNodes.length+nKbds-1, // Number of (visible) keyboard selectors itemHeight=(<HTMLElement>m3.firstChild.firstChild).offsetHeight, menuHeight=nItems*itemHeight; // Correct maxheight for viewport scaling (iPhone/iPod only) and internal position corrections if(device.OS == 'iOS') { if(device.formFactor == 'phone') { barWidth=(util.landscapeView() ? 36 : 0); maxHeight=(window.innerHeight-barWidth-16)*util.getViewportScale(); } else if(device.formFactor == 'tablet') { barWidth=(util.landscapeView() ? 16 : 0); maxHeight=(maxHeight-barWidth); } } // Explicitly set position and height s.left=dom.Utils.getAbsoluteX(osk.vkbd.lgKey)+'px'; if(menuHeight > maxHeight) { menuHeight=maxHeight; } s.height=menuHeight+'px'; // Position menu at bottom of screen using the same positioning model as the OSK. s.bottom='0px'; // Explicitly set the scroller and index heights to the container height mx.style.height=m2.style.height=s.height; } /** * Add an index to the language menu * * @param {Object} e touch start event from index * @param {Object} m2 menu scroller DIV * @param {Object} menu DIV with list of languages */ scrollToLanguage(e: TouchEvent, m2: HTMLDivElement, menu: HTMLDivElement) { e.stopImmediatePropagation(); e.stopPropagation(); e.preventDefault(); let target = <HTMLElement> e.touches[0].target; // Will return 'P', not 'p'. if(target.nodeName != 'P') { return; } var i,t,top=0,initial=target.innerHTML.charCodeAt(0),nn=menu.childNodes; try { for(i=0; i<nn.length-1; i++) { t=(<HTMLElement>nn[i].firstChild).innerHTML.toUpperCase().charCodeAt(0); if(t >= initial) { break; } } } catch(ex){} try { top=(<HTMLElement>menu.firstChild).offsetHeight*i+1; m2.scrollTop=top; } catch(ex) { top=0; } try { if(m2.scrollTop < top) { m2.scrollTop=m2.scrollHeight-m2.offsetHeight; } if(m2.scrollTop > m2.scrollHeight-m2.offsetHeight-1) { m2.scrollTop=m2.scrollHeight-m2.offsetHeight-1; } } catch(ex){} } /** * Display all languages for installed keyboards in scrollable list * * @param {Object} menu DIV to which language selectors will be added * @param {Object} kbdList array of keyboard stub objects * @return {number} index of currently active language **/ addLanguages(menu: HTMLDivElement, kbdList): number { var nStubs=kbdList.length; let util = this.keyman.util let device = util.device; // Create and sort a list of languages var k,n,lg,langs=[]; for(n=0; n<nStubs; n++) { lg=kbdList[n]['KL']; if(langs.indexOf(lg) == -1) { langs.push(lg); } } langs.sort(); // Get current scale factor (reciprocal of viewport scale) var scale=Math.round(100/util.getViewportScale())/100; var dx,lgBar,i,kb,activeLanguageIndex=-1; for(k=0; k<langs.length; k++) { dx=util._CreateElement('div'); dx.className='kbd-list-closed'; lgBar=util._CreateElement('p'); lgBar.kList=[]; for(n=0; n<nStubs; n++) { if(kbdList[n]['KL'] == langs[k]) { lgBar.kList.push(kbdList[n]); } } // Adjust bar size for current viewport scaling (iOS only!) if(device.OS == 'iOS') { lgBar.style.fontSize=scale+'em'; } // Add to menu dx.appendChild(lgBar); menu.appendChild(dx); if(langs[k] == this.keyman.keyboardManager.activeStub['KL']) { activeLanguageIndex=k; } let languageMenu = this; // Several keyboards for this language if(lgBar.kList.length > 1) { lgBar.className='kbd-list'; lgBar.innerHTML=langs[k]+'...'; lgBar.scrolled=false; lgBar.ontouchend=function(e) { e.preventDefault();e.stopPropagation(); if(e.target.scrolled) e.target.scrolled=false; else this.parentNode.className=(this.parentNode.className=='kbd-list-closed'?'kbd-list-open':'kbd-list-closed'); // Adjust top of menu to allow for expanded list languageMenu.adjust(this.parentNode.className=='kbd-list-closed'?0:this.kList.length); } lgBar.addEventListener('touchstart',function(e){e.stopPropagation();},false); lgBar.addEventListener('touchmove',function(e){e.target.scrolled=true;e.stopPropagation();},false); for(i=0; i<lgBar.kList.length; i++) { kb=util._CreateElement('p'); kb.className='kbd-list-entry'; if(device.OS == 'iOS') { kb.style.fontSize=scale+'em'; } this.addKeyboard(lgBar.kList[i],kb,false); dx.appendChild(kb); } // Only one keyboard for this language } else { lgBar.innerHTML=langs[k]; lgBar.className='kbd-single-entry'; this.addKeyboard(lgBar.kList[0],lgBar,true); } if(k == activeLanguageIndex) { lgBar.className=lgBar.className+' current'; } } // Add a non-selectable bottom bar so to allow scrolling to the last language var padLast=util._CreateElement('div'); padLast.id='kmw-menu-footer'; var cancelTouch=function(e){ e.preventDefault(); e.stopPropagation(); }; padLast.addEventListener('touchstart',cancelTouch,false); padLast.addEventListener('touchmove',cancelTouch,false); padLast.addEventListener('touchend',cancelTouch,false); menu.appendChild(padLast); return activeLanguageIndex; } /** * Add a keyboard entry to the language menu * * * @param {Object} kbd keyboard object * @param {Object} kb element being added and styled * @param {boolean} unique is this the only keyboard for the language? */ addKeyboard(kbd, kb, unique: boolean) { kb.kn=kbd['KI']; // InternalName; kb.kc=kbd['KLC']; // LanguageCode; kb.innerHTML=unique?kbd['KL']:kbd['KN'].replace(' Keyboard',''); // Name // We're setting up a few events - this alias helps avoid scoping issues. let languageMenu = this; // Touchstart (or mspointerdown) event highlights the touched list item var touchStart=function(e) { e.stopPropagation(); if(this.className.indexOf('selected') <= 0) { this.className=this.className+' selected'; } languageMenu.scrolling=false; languageMenu.y0=e.touches[0].pageY;//osk.lgList.childNodes[0].scrollTop; return true; }; //TODO: Still drags Android background sometimes (not consistently) // Touchmove drags the list and prevents release from selecting the language var touchMove=function(e: TouchEvent) { e.stopImmediatePropagation(); var scroller=<HTMLElement>languageMenu.lgList.childNodes[0], yMax=scroller.scrollHeight-scroller.offsetHeight, y, dy; if("undefined" != typeof e.pageY) { y = e.pageY; } else if("undefined" != typeof e.touches) { y = e.touches[0].pageY; } else { return; } dy=y-languageMenu.y0; // Scroll up (show later listed languages) if(dy < 0) { if(scroller.scrollTop >= yMax-1) { e.preventDefault(); languageMenu.y0=y; } // Scroll down (show earlier listed languages) } else if(dy > 0) { if(scroller.scrollTop < 2) { e.preventDefault(); languageMenu.y0=y; } // Dont' scroll - can happen if changing scroll direction } else { return; } // Disable selected language if drag more than 5px if(dy < -5 || dy > 5) { languageMenu.scrolling=true; this.className=this.className.replace(/\s*selected/,''); languageMenu.y0=y; } return true; }; // Touch release (click) event selects touched list item var touchEnd=function(e: TouchEvent) { e.preventDefault(); if(typeof(e.stopImmediatePropagation) != 'undefined') { e.stopImmediatePropagation(); } else { e.stopPropagation(); } if(languageMenu.scrolling) { this.className=this.className.replace(/\s*selected/,''); } else { com.keyman.dom.DOMEventHandlers.states.setFocusTimer(); languageMenu.lgList.style.display='none'; //still allows blank menu momentarily on selection languageMenu.keyman.keyboardManager._SetActiveKeyboard(this.kn,this.kc,true); languageMenu.keyman.keyboardManager.doKeyboardChange(this.kn,this.kc); languageMenu.keyman.domManager.focusLastActiveElement(); languageMenu.hide(); } return true; }; kb.onmspointerdown=touchStart; kb.addEventListener('touchstart',touchStart,false); kb.onmspointermove=touchMove; kb.addEventListener('touchmove',touchMove,false); kb.onmspointerout=touchEnd; kb.addEventListener('touchend',touchEnd,false); } /** * Remove the language menu again **/ hide() { let osk = this.keyman.osk; let languageMenu = this; if(this.lgList) { osk.vkbd.highlightKey(osk.vkbd.lgKey,false); this.lgList.style.visibility='hidden'; window.setTimeout(function(){ // In case of extremely rapid keyboard swaps, this event may trigger more than once - // the shim's on-touch event can trigger after a keyboard has been selected! if(languageMenu.shim.parentElement) { document.body.removeChild(languageMenu.shim); document.body.removeChild(languageMenu.lgList); } },500); } } } }
the_stack
import ObjectIdentity from '../../util/ObjectIdentity'; import GraphLayout from './GraphLayout'; import { Graph } from '../Graph'; import Cell from '../cell/Cell'; import CellArray from '../cell/CellArray'; /** * Extends {@link GraphLayout} to implement a fast organic layout algorithm. * The vertices need to be connected for this layout to work, vertices * with no connections are ignored. * * Example: * * ```javascript * let layout = new mxFastOrganicLayout(graph); * layout.execute(graph.getDefaultParent()); * ``` * * Constructor: mxCompactTreeLayout * * Constructs a new fast organic layout for the specified graph. */ class MxFastOrganicLayout extends GraphLayout { constructor(graph: Graph) { super(graph); } /** * Specifies if the top left corner of the input cells should be the origin of the layout result. Default is true. */ useInputOrigin: boolean = true; /** * Specifies if all edge points of traversed edges should be removed. Default is true. */ resetEdges: boolean = true; /** * Specifies if the STYLE_NOEDGESTYLE flag should be set on edges that are modified by the result. Default is true. */ disableEdgeStyle: boolean = true; /** * The force constant by which the attractive forces are divided and the replusive forces are multiple by the square of. The value equates to the average radius there is of free space around each node. Default is 50. */ forceConstant: number = 50; /** * Cache of <forceConstant>^2 for performance. */ forceConstantSquared: any = 0; /** * Minimal distance limit. Default is 2. Prevents of dividing by zero. */ minDistanceLimit: number = 2; /** * Maximal distance limit. Default is 500. Prevents of * dividing by zero. */ maxDistanceLimit: number = 500; /** * Cached version of minDistanceLimit squared. */ minDistanceLimitSquared: number = 4; /** * Start value of temperature. Default is 200. */ initialTemp: number = 200; /** * Temperature to limit displacement at later stages of layout. */ temperature: number = 0; /** * Total number of iterations to run the layout though. */ maxIterations: number = 0; /** * Current iteration count. */ iteration: number = 0; /** * An array of all vertices to be laid out. */ vertexArray: CellArray = new CellArray(); /** * An array of locally stored X co-ordinate displacements for the vertices. */ dispX: number[] = []; /** * An array of locally stored Y co-ordinate displacements for the vertices. */ dispY: number[] = []; /** * An array of locally stored co-ordinate positions for the vertices. */ cellLocation: any[] = []; /** * The approximate radius of each cell, nodes only. */ radius: number[] = []; /** * The approximate radius squared of each cell, nodes only. */ radiusSquared: number[] = []; /** * Array of booleans representing the movable states of the vertices. */ isMoveable: boolean[] = []; /** * Local copy of cell neighbours. */ neighbours: { [key: number]: number[] } = {}; /** * Hashtable from cells to local indices. */ indices: { [key: string]: number } = {}; /** * Boolean flag that specifies if the layout is allowed to run. If this is * set to false, then the layout exits in the following iteration. */ allowedToRun = true; /** * Returns a boolean indicating if the given <Cell> should be ignored as a * vertex. This returns true if the cell has no connections. * * @param vertex <Cell> whose ignored state should be returned. */ isVertexIgnored(vertex: Cell) { return ( super.isVertexIgnored(vertex) || this.graph.getConnections(vertex).length === 0 ); } /** * Implements {@link GraphLayout#execute}. This operates on all children of the * given parent where <isVertexIgnored> returns false. */ execute(parent: Cell) { const model = this.graph.getDataModel(); this.vertexArray = new CellArray(); let cells = this.graph.getChildVertices(parent); for (let i = 0; i < cells.length; i += 1) { if (!this.isVertexIgnored(cells[i])) { this.vertexArray.push(cells[i]); } } const initialBounds = this.useInputOrigin ? this.graph.getBoundingBoxFromGeometry(this.vertexArray) : null; const n = this.vertexArray.length; this.indices = {}; this.dispX = []; this.dispY = []; this.cellLocation = []; this.isMoveable = []; this.neighbours = {}; this.radius = []; this.radiusSquared = []; if (this.forceConstant < 0.001) { this.forceConstant = 0.001; } this.forceConstantSquared = this.forceConstant * this.forceConstant; // Create a map of vertices first. This is required for the array of // arrays called neighbours which holds, for each vertex, a list of // ints which represents the neighbours cells to that vertex as // the indices into vertexArray for (let i = 0; i < this.vertexArray.length; i += 1) { const vertex = this.vertexArray[i]; this.cellLocation[i] = []; // Set up the mapping from array indices to cells const id = <string>ObjectIdentity.get(vertex); this.indices[id] = i; const bounds = this.getVertexBounds(vertex); // Set the X,Y value of the internal version of the cell to // the center point of the vertex for better positioning const { width } = bounds; const { height } = bounds; // Randomize (0, 0) locations const { x } = bounds; const { y } = bounds; this.cellLocation[i][0] = x + width / 2.0; this.cellLocation[i][1] = y + height / 2.0; this.radius[i] = Math.min(width, height); this.radiusSquared[i] = this.radius[i] * this.radius[i]; } // Moves cell location back to top-left from center locations used in // algorithm, resetting the edge points is part of the transaction model.beginUpdate(); try { for (let i = 0; i < n; i += 1) { this.dispX[i] = 0; this.dispY[i] = 0; this.isMoveable[i] = this.isVertexMovable(this.vertexArray[i]); // Get lists of neighbours to all vertices, translate the cells // obtained in indices into vertexArray and store as an array // against the orginial cell index const edges = this.graph.getConnections(this.vertexArray[i], parent); cells = this.graph.getOpposites(edges, this.vertexArray[i]); this.neighbours[i] = []; for (let j = 0; j < cells.length; j += 1) { // Resets the points on the traversed edge if (this.resetEdges) { this.graph.resetEdge(edges[j]); } if (this.disableEdgeStyle) { this.setEdgeStyleEnabled(edges[j], false); } // Looks the cell up in the indices dictionary const id = <string>ObjectIdentity.get(cells[j]); const index = this.indices[id]; // Check the connected cell in part of the vertex list to be // acted on by this layout if (index != null) { this.neighbours[i][j] = index; } // Else if index of the other cell doesn't correspond to // any cell listed to be acted upon in this layout. Set // the index to the value of this vertex (a dummy self-loop) // so the attraction force of the edge is not calculated else { this.neighbours[i][j] = i; } } } this.temperature = this.initialTemp; // If max number of iterations has not been set, guess it if (this.maxIterations === 0) { this.maxIterations = 20 * Math.sqrt(n); } // Main iteration loop for (this.iteration = 0; this.iteration < this.maxIterations; this.iteration += 1) { if (!this.allowedToRun) { return; } // Calculate repulsive forces on all vertices this.calcRepulsion(); // Calculate attractive forces through edges this.calcAttraction(); this.calcPositions(); this.reduceTemperature(); } let minx = null; let miny = null; for (let i = 0; i < this.vertexArray.length; i += 1) { const vertex = this.vertexArray[i]; if (this.isVertexMovable(vertex)) { const bounds = this.getVertexBounds(vertex); if (bounds != null) { this.cellLocation[i][0] -= bounds.width / 2.0; this.cellLocation[i][1] -= bounds.height / 2.0; const x = this.graph.snap(Math.round(this.cellLocation[i][0])); const y = this.graph.snap(Math.round(this.cellLocation[i][1])); this.setVertexLocation(vertex, x, y); if (minx == null) { minx = x; } else { minx = Math.min(minx, x); } if (miny == null) { miny = y; } else { miny = Math.min(miny, y); } } } } // Modifies the cloned geometries in-place. Not needed // to clone the geometries again as we're in the same // undoable change. let dx = -(minx || 0) + 1; let dy = -(miny || 0) + 1; if (initialBounds != null) { dx += initialBounds.x; dy += initialBounds.y; } this.graph.moveCells(this.vertexArray, dx, dy); } finally { model.endUpdate(); } } /** * Takes the displacements calculated for each cell and applies them to the * local cache of cell positions. Limits the displacement to the current * temperature. */ calcPositions() { for (let index = 0; index < this.vertexArray.length; index += 1) { if (this.isMoveable[index]) { // Get the distance of displacement for this node for this // iteration let deltaLength = Math.sqrt( this.dispX[index] * this.dispX[index] + this.dispY[index] * this.dispY[index] ); if (deltaLength < 0.001) { deltaLength = 0.001; } // Scale down by the current temperature if less than the // displacement distance const newXDisp = (this.dispX[index] / deltaLength) * Math.min(deltaLength, this.temperature); const newYDisp = (this.dispY[index] / deltaLength) * Math.min(deltaLength, this.temperature); // reset displacements this.dispX[index] = 0; this.dispY[index] = 0; // Update the cached cell locations this.cellLocation[index][0] += newXDisp; this.cellLocation[index][1] += newYDisp; } } } /** * Calculates the attractive forces between all laid out nodes linked by * edges */ calcAttraction() { // Check the neighbours of each vertex and calculate the attractive // force of the edge connecting them for (let i = 0; i < this.vertexArray.length; i += 1) { for (let k = 0; k < this.neighbours[i].length; k += 1) { // Get the index of the othe cell in the vertex array const j = this.neighbours[i][k]; // Do not proceed self-loops if (i !== j && this.isMoveable[i] && this.isMoveable[j]) { const xDelta = this.cellLocation[i][0] - this.cellLocation[j][0]; const yDelta = this.cellLocation[i][1] - this.cellLocation[j][1]; // The distance between the nodes let deltaLengthSquared = xDelta * xDelta + yDelta * yDelta - this.radiusSquared[i] - this.radiusSquared[j]; if (deltaLengthSquared < this.minDistanceLimitSquared) { deltaLengthSquared = this.minDistanceLimitSquared; } const deltaLength = Math.sqrt(deltaLengthSquared); const force = deltaLengthSquared / this.forceConstant; const displacementX = (xDelta / deltaLength) * force; const displacementY = (yDelta / deltaLength) * force; this.dispX[i] -= displacementX; this.dispY[i] -= displacementY; this.dispX[j] += displacementX; this.dispY[j] += displacementY; } } } } /** * Calculates the repulsive forces between all laid out nodes */ calcRepulsion() { const vertexCount = this.vertexArray.length; for (let i = 0; i < vertexCount; i += 1) { for (let j = i; j < vertexCount; j += 1) { // Exits if the layout is no longer allowed to run if (!this.allowedToRun) { return; } if (j !== i && this.isMoveable[i] && this.isMoveable[j]) { let xDelta = this.cellLocation[i][0] - this.cellLocation[j][0]; let yDelta = this.cellLocation[i][1] - this.cellLocation[j][1]; if (xDelta === 0) { xDelta = 0.01 + Math.random(); } if (yDelta === 0) { yDelta = 0.01 + Math.random(); } // Distance between nodes const deltaLength = Math.sqrt(xDelta * xDelta + yDelta * yDelta); let deltaLengthWithRadius = deltaLength - this.radius[i] - this.radius[j]; if (deltaLengthWithRadius > this.maxDistanceLimit) { // Ignore vertices too far apart continue; } if (deltaLengthWithRadius < this.minDistanceLimit) { deltaLengthWithRadius = this.minDistanceLimit; } const force = this.forceConstantSquared / deltaLengthWithRadius; const displacementX = (xDelta / deltaLength) * force; const displacementY = (yDelta / deltaLength) * force; this.dispX[i] += displacementX; this.dispY[i] += displacementY; this.dispX[j] -= displacementX; this.dispY[j] -= displacementY; } } } } /** * Reduces the temperature of the layout from an initial setting in a linear * fashion to zero. */ reduceTemperature() { this.temperature = this.initialTemp * (1.0 - this.iteration / this.maxIterations); } } export default MxFastOrganicLayout;
the_stack
declare namespace JsHamcrest { /** * Library version. */ export var version: string; // // Description // /** * Defines the method for describing the object to a description. */ interface DescribeTo { (description: Description): void; } /** * Defines the method for describing a value to a description. */ interface DescribeValueTo { (value: any, description: Description): void; } /** * Defines a method for describing the object implementing this interface to a description. * * TODO Remove? Not actually declared by JsHamcrest, but useful for type-checking in Description methods */ export interface SelfDescribing { describeTo: DescribeTo; } /** * Builder for a textual description. */ export class Description { /** * Appends text to this description. * * @param text Text to append to this description * @return {Description} Itself for method chaining */ append(text: any): Description; /** * Appends the description of a self describing object to this description. * * @param selfDescribingObject Any object that has a describeTo() function that accepts a JsHamcrest.Description object as argument * @return {Description} Itself for method chaining */ appendDescriptionOf(selfDescribingObject: SelfDescribing): Description; /** * Appends the description of several self describing objects to this description. * * @param start Start string * @param separator Separator string * @param end End string * @param list Array of self describing objects. These objects must have a describeTo() function that accepts a JsHamcrest.Description object as argument * @return {Description} Itself for method chaining */ appendList(start: string, separator: string, end: string, list: any[]): Description; /** * Appends a JavaScript language’s literal to this description. * * @param literal Literal to append to this description * @return {Description} Itself for method chaining */ appendLiteral(literal: any): Description; /** * Appends an array of values to this description. * * @param start Start string * @param separator Separator string * @param end End string * @param list Array of values to be described to this description * @return {Description} Itself for method chaining */ appendValueList(start: string, separator: string, end: string, list: SelfDescribing[]): Description; /** * Gets the current content of this description. * * @return {string} Current content of this description */ get(): string; } // // Matcher // /** * Defines the method for testing the matcher against an actual value. */ interface Matches { (value: any): boolean; } /** * Defines the minimal interface for every matcher. * * FIXME Remove since isMatcher tests for SimpleMatcher :( */ export interface Matcher extends SelfDescribing { matches: Matches; describeValueTo: DescribeValueTo; } /** * Defines the configurable methods for declaring a new matcher using JsHamcrest.SimpleMatcher. */ interface MatcherConfig { matches: Matches; describeTo: DescribeTo; describeValueTo?: DescribeValueTo | undefined; } /** * Defines a matcher that relies on the external functions provided by the caller in order to shape the current matching logic. */ export class SimpleMatcher implements Matcher { matches: Matches; describeTo: DescribeTo; describeValueTo: DescribeValueTo; constructor(config: MatcherConfig); } /** * Defines a composite matcher, that is, a matcher that wraps several matchers into one. */ export class CombinableMatcher extends SimpleMatcher { /** * Wraps this matcher and the given matcher using JsHamcrest.Matchers.allOf(). * * @param matcherOrValue Instance of JsHamcrest.SimpleMatcher or a value * @return {CombinableMatcher} Instance of JsHamcrest.CombinableMatcher */ and(matcherOrValue: any): CombinableMatcher; /** * Wraps this matcher and the given matcher using JsHamcrest.Matchers.anyOf(). * * @param matcherOrValue Instance of JsHamcrest.SimpleMatcher or a value * @return {CombinableMatcher} Instance of JsHamcrest.CombinableMatcher */ or(matcherOrValue: any): CombinableMatcher; } // // Helpers // /** * Checks if the given object is a matcher or not. * * @param obj Object to check * @return {boolean} True if the given object is a matcher; false otherwise */ export function isMatcher(obj: any): boolean; /** * Delegate function, useful when used to create a matcher that has a value-equalTo semantic. * * @param factory Creates a new matcher that delegates to the passed/wrapped matcherOrValue * @return {function(*): Matcher} Wraps the value with equalTo before passing to factory */ export function EqualTo(factory: (matcher: Matcher) => Matcher): (matcherOrValue: any) => Matcher; /** * Provides the assertion, filtering, and currying methods. */ namespace Operators { /** * Defines the options accepted by assert(). */ interface AssertOptions { message?: any; pass?: ((description: string) => void) | undefined; fail?: ((description: string) => void) | undefined; } /** * Fails if the actual value does not match the matcher. * * @param actual Value to test against the matcher * @param matcherOrValue Applied to the value; wrapped with equalTo() if not a matcher * @param options Provides message and pass/fail handlers * @return {JsHamcrest.Description} Contains the message, actual value, matcher, and result */ export function assert(actual: any, matcherOrValue?: any, options?: AssertOptions): JsHamcrest.Description; /** * Returns those items of the array for which matcher matches. * * @param array The values to filter * @param matcherOrValue Applied to each value * @return {Array.<*>} Contains all values from array matched by the matcher in the original order */ export function filter(array: any[], matcherOrValue: any): any[]; /** * Delegate function, useful when used along with raises() and raisesAnything(). * * @param func Function to delegate to * @param args Passed to func * @return {function(): *} A function that calls func with args and returns its result */ export function callTo(func: (...args: any[]) => any, ...args: any[]): () => any; } /** * Defines all of the built-in matchers grouped into five categories. */ namespace Matchers { // // Collection Matchers // /** * The length of the actual value must be zero. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function empty(): JsHamcrest.SimpleMatcher; /** * The actual value should be an array and matcherOrValue must match all items. * * @param matcherOrValue Instance of JsHamcrest.SimpleMatcher or a value * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function everyItem(matcherOrValue: any): JsHamcrest.SimpleMatcher; /** * The actual value should be an array and it must contain at least one value that matches matcherOrValue. * * @param matcherOrValue Instance of JsHamcrest.SimpleMatcher or a value * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function hasItem(matcherOrValue: any): JsHamcrest.SimpleMatcher; /** * The actual value should be an array and matchersOrValues must match at least one item. * * @param matchersOrValues Instances of JsHamcrest.SimpleMatcher and/or values * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function hasItems(...matchersOrValues: any[]): JsHamcrest.SimpleMatcher; /** * The length of the actual value must match matcherOrValue. * * @param matcherOrValue Instance of JsHamcrest.SimpleMatcher or a value * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function hasSize(matcherOrValue: any): JsHamcrest.SimpleMatcher; /** * The given array or arguments must contain the actual value. * * @param items Array or list of values * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function isIn(...items: any[]): JsHamcrest.SimpleMatcher; /** * Alias to isIn() function. * * @param items Array or list of values * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function oneOf(...items: any[]): JsHamcrest.SimpleMatcher; // // Core Matchers // /** * All matchesOrValues must match the actual value. This matcher behaves pretty much like the JavaScript && (and) operator. * * @param matchersOrValues Instances of JsHamcrest.SimpleMatcher and/or values * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function allOf(...matchersOrValues: any[]): JsHamcrest.SimpleMatcher; /** * At least one of the matchersOrValues should match the actual value. This matcher behaves pretty much like the JavaScript || (or) operator. * * @param matchersOrValues Instances of JsHamcrest.SimpleMatcher and/or values * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function anyOf(...matchersOrValues: any[]): JsHamcrest.SimpleMatcher; /** * Useless always-match matcher. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function anything(): JsHamcrest.SimpleMatcher; /** * Combinable matcher where the actual value must match all the given matchers or values. * * @param matcherOrValue Instance of JsHamcrest.SimpleMatcher or a value * @return {JsHamcrest.CombinableMatcher} Instance of JsHamcrest.CombinableMatcher */ export function both(matcherOrValue: any): JsHamcrest.CombinableMatcher; /** * Combinable matcher where the actual value must match at least one of the given matchers or values. * * @param matcherOrValue Instance of JsHamcrest.SimpleMatcher or a value * @return {JsHamcrest.CombinableMatcher} Instance of JsHamcrest.CombinableMatcher */ export function either(matcherOrValue: any): JsHamcrest.CombinableMatcher; /** * The actual value must be equal to expected. * * @param expected Expected value * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function equalTo(expected: any): JsHamcrest.SimpleMatcher; /** * Delegate-only matcher frequently used to improve readability. * * @param matcherOrValue Instance of JsHamcrest.SimpleMatcher or a value * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function is(matcherOrValue: any): JsHamcrest.SimpleMatcher; /** * The actual value must be null or undefined. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function nil(): JsHamcrest.SimpleMatcher; /** * The actual value must not match matcherOrValue. * * @param matcherOrValue Instance of JsHamcrest.SimpleMatcher or a value * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function not(matcherOrValue: any): JsHamcrest.SimpleMatcher; /** * The actual value is a function and, when invoked, it should throw an exception with the given name. * * @param exceptionName Name of the expected exception * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function raises(exceptionName: string): JsHamcrest.SimpleMatcher; /** * The actual value is a function and, when invoked, it should raise any exception. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function raisesAnything(): JsHamcrest.SimpleMatcher; /** * The actual value must be the same as expected. * * @param expected Expected value * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function sameAs(expected: any): JsHamcrest.SimpleMatcher; /** * Matches any truthy value (not undefined, null, false, 0, NaN, or ""). * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function truth(): JsHamcrest.SimpleMatcher; // // Number Matchers // /** * The actual number must be between the given range (inclusive). * * @param start Range start * @return {JsHamcrest.BetweenBuilder} Builder object with an and(end) method, which returns a JsHamcrest.SimpleMatcher instance and thus should be called to finish the matcher creation */ export function between(start: any): JsHamcrest.BetweenBuilder; /** * The actual number must be close enough to expected, that is, the actual number is equal to a value within some range of acceptable error. * * @param expected Expected number * @param [delta=0] Expected difference delta * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function closeTo(expected: number, delta?: number): JsHamcrest.SimpleMatcher; /** * The actual number must be divisible by divisor. * * @param divisor Divisor * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function divisibleBy(divisor: number): JsHamcrest.SimpleMatcher; /** * The actual number must be even. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function even(): JsHamcrest.SimpleMatcher; /** * The actual number must be greater than expected. * * @param expected Expected number * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function greaterThan(expected: any): JsHamcrest.SimpleMatcher; /** * The actual number must be greater than or equal to expected. * * @param expected Expected number * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function greaterThanOrEqualTo(expected: any): JsHamcrest.SimpleMatcher; /** * The actual number must be less than expected. * * @param expected Expected number * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function lessThan(expected: any): JsHamcrest.SimpleMatcher; /** * The actual number must be less than or equal to expected. * * @param expected Expected number * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function lessThanOrEqualTo(expected: any): JsHamcrest.SimpleMatcher; /** * The actual value must not be a number. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function notANumber(): JsHamcrest.SimpleMatcher; /** * The actual number must be odd. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function odd(): JsHamcrest.SimpleMatcher; /** * The actual number must be zero. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function zero(): JsHamcrest.SimpleMatcher; // // Object Matchers // /** * The actual value must be a boolean. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function bool(): JsHamcrest.SimpleMatcher; /** * The actual value must be a function. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function func(): JsHamcrest.SimpleMatcher; /** * The actual value has a function with the given name. * * @param functionName Function name * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function hasFunction(functionName: string): JsHamcrest.SimpleMatcher; /** * The actual value has an attribute with the given name. * * @param memberName Member name * @param [matcherOrValue] Instance of JsHamcrest.SimpleMatcher or a value * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function hasMember(memberName: string, matcherOrValue?: any): JsHamcrest.SimpleMatcher; /** * The actual value must be an instance of clazz. * * @param clazz Constructor function * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function instanceOf(clazz: new() => any): JsHamcrest.SimpleMatcher; /** * The actual value must be a number. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function number(): JsHamcrest.SimpleMatcher; /** * The actual value must be an object. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function object(): JsHamcrest.SimpleMatcher; /** * The actual value must be a string. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function string(): JsHamcrest.SimpleMatcher; /** * The actual value must be of the given type. * * @param typeName Name of the type * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function typeOf(typeName: string): JsHamcrest.SimpleMatcher; // // Text Matchers // /** * The actual string must have a substring equals to str. * * @param str Substring * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function containsString(str: string): JsHamcrest.SimpleMatcher; /** * The actual string must look like an e-mail address. * * Warning: This matcher is not fully compliant with RFC2822 due to its complexity. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function emailAddress(): JsHamcrest.SimpleMatcher; /** * The actual string must end with str. * * @param str Substring * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function endsWith(str: string): JsHamcrest.SimpleMatcher; /** * The actual string must be equal to str, ignoring case. * * @param str String * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function equalIgnoringCase(str: string): JsHamcrest.SimpleMatcher; /** * The actual string must match regex. * * @param regex String * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function matches(regex: RegExp): JsHamcrest.SimpleMatcher; /** * The actual string must start with str. * * @param str Substring * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ export function startsWith(str: string): JsHamcrest.SimpleMatcher; } /** * Provides methods for exposing matchers and operators for several testing frameworks. */ namespace Integration { /** * Copies all members of the Matchers and Operators modules to target. * * Does not overwrite properties with the same name. * * @param target */ export function copyMembers(target: {}): void; /** * Copies all members of source to target. * * Does not overwrite properties with the same name. * * @param source * @param target */ export function copyMembers(source: {}, target: {}): void; /** * Adds the members of the given object to JsHamcrest.Matchers namespace. * * @param source */ export function installMatchers(source: {}): void; /** * Adds the members of the given object to JsHamcrest.Operators namespace. * * @param source */ export function installOperators(source: {}): void; // // Testing Frameworks // /** * Uses the web browser's alert() function to display the assertion results. * Great for quick prototyping. */ export function WebBrowser(): void; /** * Uses Rhino's print() function to display the assertion results. * Great for quick prototyping. */ export function Rhino(): void; /** * JsTestDriver integration. * * @param params Omit to copy members to global scope */ export function JsTestDriver(params?: { scope?: {} | undefined }): void; /** * NodeUnit (Node.js Unit Testing) integration. * * @param params Omit to copy members to "global" */ export function Nodeunit(params?: { scope?: {} | undefined }): void; /** * JsUnitTest integration. * * @param params Omit to copy members to "JsUnitTest.Unit.Testcase.prototype" */ export function JsUnitTest(params?: { scope?: {} | undefined }): void; /** * YUITest (Yahoo UI) integration. * * @param params Omit to copy members to global scope */ export function YUITest(params?: { scope?: {} | undefined }): void; /** * QUnit (JQuery) integration. * * @param params Omit to copy members to global scope */ export function QUnit(params?: { scope?: {} | undefined }): void; /** * jsUnity integration. * * @param params Omit to copy members to "jsUnity.env.defaultScope" */ export function jsUnity(params?: { scope?: {} | undefined; attachAssertions?: boolean | undefined }): void; /** * Screw.Unit integration. * * @param params Omit to copy members to "Screw.Matchers" */ export function screwunit(params?: { scope?: {} | undefined }): void; /** * Jasmine integration. * * @param params Omit to copy members to global scope */ export function jasmine(params?: { scope?: {} | undefined }): void; } // // Builders // /** * Used by the between() matcher to specify the ending value. */ export class BetweenBuilder { and(end: any): SimpleMatcher; } } // // Functions that are copied by copyMembers() to the global scope are copy-n-pasted here. // // TODO There must be a better way to do this, and not every testing framework places them in the global scope. // // // Assert // /** * Fails if the actual value does not match the matcher. * * @param actual Value to test against the matcher * @param matcher Applied to the value * @param message Prepends the built description * @return {JsHamcrest.Description} Contains the message, actual value, matcher, and result */ declare function assertThat(actual: any, matcher?: JsHamcrest.Matcher, message?: any): JsHamcrest.Description; // // Collection Matchers // /** * The length of the actual value must be zero. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function empty(): JsHamcrest.SimpleMatcher; /** * The actual value should be an array and matcherOrValue must match all items. * * @param matcherOrValue Instance of JsHamcrest.SimpleMatcher or a value * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function everyItem(matcherOrValue: any): JsHamcrest.SimpleMatcher; /** * The actual value should be an array and it must contain at least one value that matches matcherOrValue. * * @param matcherOrValue Instance of JsHamcrest.SimpleMatcher or a value * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function hasItem(matcherOrValue: any): JsHamcrest.SimpleMatcher; /** * The actual value should be an array and matchersOrValues must match at least one item. * * @param matchersOrValues Instances of JsHamcrest.SimpleMatcher and/or values * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function hasItems(...matchersOrValues: any[]): JsHamcrest.SimpleMatcher; /** * The length of the actual value must match matcherOrValue. * * @param matcherOrValue Instance of JsHamcrest.SimpleMatcher or a value * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function hasSize(matcherOrValue: any): JsHamcrest.SimpleMatcher; /** * The given array or arguments must contain the actual value. * * @param items Array or list of values * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function isIn(...items: any[]): JsHamcrest.SimpleMatcher; /** * Alias to isIn() function. * * @param items Array or list of values * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function oneOf(...items: any[]): JsHamcrest.SimpleMatcher; // // Core Matchers // /** * All matchesOrValues must match the actual value. This matcher behaves pretty much like the JavaScript && (and) operator. * * @param matchersOrValues Instances of JsHamcrest.SimpleMatcher and/or values * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function allOf(...matchersOrValues: any[]): JsHamcrest.SimpleMatcher; /** * At least one of the matchersOrValues should match the actual value. This matcher behaves pretty much like the JavaScript || (or) operator. * * @param matchersOrValues Instances of JsHamcrest.SimpleMatcher and/or values * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function anyOf(...matchersOrValues: any[]): JsHamcrest.SimpleMatcher; /** * Useless always-match matcher. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function anything(): JsHamcrest.SimpleMatcher; /** * Combinable matcher where the actual value must match all the given matchers or values. * * @param matcherOrValue Instance of JsHamcrest.SimpleMatcher or a value * @return {JsHamcrest.CombinableMatcher} Instance of JsHamcrest.CombinableMatcher */ declare function both(matcherOrValue: any): JsHamcrest.CombinableMatcher; /** * Combinable matcher where the actual value must match at least one of the given matchers or values. * * @param matcherOrValue Instance of JsHamcrest.SimpleMatcher or a value * @return {JsHamcrest.CombinableMatcher} Instance of JsHamcrest.CombinableMatcher */ declare function either(matcherOrValue: any): JsHamcrest.CombinableMatcher; /** * The actual value must be equal to expected. * * @param expected Expected value * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function equalTo(expected: any): JsHamcrest.SimpleMatcher; /** * Delegate-only matcher frequently used to improve readability. * * @param matcherOrValue Instance of JsHamcrest.SimpleMatcher or a value * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function is(matcherOrValue: any): JsHamcrest.SimpleMatcher; /** * The actual value must be null or undefined. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function nil(): JsHamcrest.SimpleMatcher; /** * The actual value must not match matcherOrValue. * * @param matcherOrValue Instance of JsHamcrest.SimpleMatcher or a value * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function not(matcherOrValue: any): JsHamcrest.SimpleMatcher; /** * The actual value is a function and, when invoked, it should throw an exception with the given name. * * @param exceptionName Name of the expected exception * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function raises(exceptionName: string): JsHamcrest.SimpleMatcher; /** * The actual value is a function and, when invoked, it should raise any exception. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function raisesAnything(): JsHamcrest.SimpleMatcher; /** * The actual value must be the same as expected. * * @param expected Expected value * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function sameAs(expected: any): JsHamcrest.SimpleMatcher; /** * Matches any truthy value (not undefined, null, false, 0, NaN, or ""). * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function truth(): JsHamcrest.SimpleMatcher; // // Number Matchers // /** * The actual number must be between the given range (inclusive). * * @param start Range start * @return {JsHamcrest.BetweenBuilder} Builder object with an and(end) method, which returns a JsHamcrest.SimpleMatcher instance and thus should be called to finish the matcher creation */ declare function between(start: any): JsHamcrest.BetweenBuilder; /** * The actual number must be close enough to expected, that is, the actual number is equal to a value within some range of acceptable error. * * @param expected Expected number * @param [delta=0] Expected difference delta * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function closeTo(expected: number, delta?: number): JsHamcrest.SimpleMatcher; /** * The actual number must be divisible by divisor. * * @param divisor Divisor * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function divisibleBy(divisor: number): JsHamcrest.SimpleMatcher; /** * The actual number must be even. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function even(): JsHamcrest.SimpleMatcher; /** * The actual number must be greater than expected. * * @param expected Expected number * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function greaterThan(expected: any): JsHamcrest.SimpleMatcher; /** * The actual number must be greater than or equal to expected. * * @param expected Expected number * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function greaterThanOrEqualTo(expected: any): JsHamcrest.SimpleMatcher; /** * The actual number must be less than expected. * * @param expected Expected number * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function lessThan(expected: any): JsHamcrest.SimpleMatcher; /** * The actual number must be less than or equal to expected. * * @param expected Expected number * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function lessThanOrEqualTo(expected: any): JsHamcrest.SimpleMatcher; /** * The actual value must not be a number. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function notANumber(): JsHamcrest.SimpleMatcher; /** * The actual number must be odd. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function odd(): JsHamcrest.SimpleMatcher; /** * The actual number must be zero. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function zero(): JsHamcrest.SimpleMatcher; // // Object Matchers // /** * The actual value must be a boolean. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function bool(): JsHamcrest.SimpleMatcher; /** * The actual value must be a function. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function func(): JsHamcrest.SimpleMatcher; /** * The actual value has a function with the given name. * * @param functionName Function name * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function hasFunction(functionName: string): JsHamcrest.SimpleMatcher; /** * The actual value has an attribute with the given name. * * @param memberName Member name * @param [matcherOrValue] Instance of JsHamcrest.SimpleMatcher or a value * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function hasMember(memberName: string, matcherOrValue?: any): JsHamcrest.SimpleMatcher; /** * The actual value must be an instance of clazz. * * @param clazz Constructor function * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function instanceOf(clazz: new() => any): JsHamcrest.SimpleMatcher; /** * The actual value must be a number. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function number(): JsHamcrest.SimpleMatcher; /** * The actual value must be an object. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function object(): JsHamcrest.SimpleMatcher; /** * The actual value must be a string. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function string(): JsHamcrest.SimpleMatcher; /** * The actual value must be of the given type. * * @param typeName Name of the type * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function typeOf(typeName: string): JsHamcrest.SimpleMatcher; // // Text Matchers // /** * The actual string must have a substring equals to str. * * @param str Substring * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function containsString(str: string): JsHamcrest.SimpleMatcher; /** * The actual string must look like an e-mail address. * * Warning: This matcher is not fully compliant with RFC2822 due to its complexity. * * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function emailAddress(): JsHamcrest.SimpleMatcher; /** * The actual string must end with str. * * @param str Substring * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function endsWith(str: string): JsHamcrest.SimpleMatcher; /** * The actual string must be equal to str, ignoring case. * * @param str String * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function equalIgnoringCase(str: string): JsHamcrest.SimpleMatcher; /** * The actual string must match regex. * * @param regex String * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function matches(regex: RegExp): JsHamcrest.SimpleMatcher; /** * The actual string must start with str. * * @param str Substring * @return {JsHamcrest.SimpleMatcher} Instance of JsHamcrest.SimpleMatcher */ declare function startsWith(str: string): JsHamcrest.SimpleMatcher;
the_stack
module Kiwi.Geom { /** * A Circle object is an area defined by its position, * as indicated by its center point (x,y) and diameter. * * @class Circle * @namespace Kiwi.Geom * @constructor * @param [x=0] {Number} The x coordinate of the center of the circle. * @param [y=0] {Number} The y coordinate of the center of the circle. * @param [diameter=0] {number} The diameter of the circle. * @return {Kiwi.Geom.Circle} This circle object * */ export class Circle { constructor (x: number = 0, y: number = 0, diameter: number = 0) { this.setTo(x, y, diameter); } /** * The type of this object. * @method objType * @return {String} "Circle" * @public */ public objType() { return "Circle"; } /** * The diameter of the circle * @property _diameter * @type Number * @default 0 * @private */ private _diameter: number = 0; /** * The radius of the circle * @property _radius * @type Number * @default 0 * @private */ private _radius: number = 0; /** * The x coordinate of the center of the circle * @property x * @type Number * @default 0 * @public */ public x: number = 0; /** * The y coordinate of the center of the circle * @property y * @type Number * @default 0 * @public */ public y: number = 0; /** * The diameter of the circle. * The largest distance between any two points on the circle. * The same as the radius * 2. * * @property diameter * @type number * @public */ public set diameter(value: number) { if (value > 0) { this._diameter = value; this._radius = value * 0.5; } } public get diameter(): number { return this._diameter; } /** * The radius of the circle. * The length of a line extending from the center of the circle to any point on the circle itself. * The same as half the diameter. * * @property radius * @type number * @public */ public set radius(value: number) { if (value > 0) { this._radius = value; this._diameter = value * 2; } } public get radius(): number { return this._radius; } /** * The circumference of the circle. This is READ ONLY. * @property circumference * @type number * @readOnly * @public */ public get circumference(): number { return 2 * (Math.PI * this._radius); } /** * The sum of the y and radius properties. * Changing the bottom property of a Circle object has no effect on the x and y properties, * but does change the diameter. * @property bottom * @type number * @public */ public set bottom(value: number) { if (!isNaN(value)) { if (value < this.y) { this._radius = 0; this._diameter = 0; } else { this.radius = value - this.y; } } } public get bottom(): number { return this.y + this._radius; } /** * The x coordinate of the leftmost point of the circle. * Changing the left property of a Circle object has no effect on the x and y properties. * However it does affect the diameter, whereas changing the x value does not affect the diameter property. * * @property left * @type number * @public */ public set left(value: number) { if (!isNaN(value)) { if (value < this.x) { this.radius = this.x - value; } else { this._radius = 0; this._diameter = 0; } } } public get left(): number { return this.x - this._radius; } /** * The x coordinate of the rightmost point of the circle. * Changing the right property of a Circle object has no effect on the x and y properties. * However it does affect the diameter, whereas changing the x value does not affect the diameter property. * * @property right * @type number * @public */ public set right(value: number) { if (value && !isNaN(value)) { if (value > this.x) { this.radius = value - this.x; } else { this._radius = 0; this._diameter = 0; } } } public get right(): number { return this.x + this._radius; } /** * The sum of the y minus the radius property. * Changing the top property of a Circle object has no effect on the x and y properties, * but does change the diameter. * * @property top * @type number * @public */ public set top(value: number) { if (value && !isNaN(value)) { if (value > this.y) { this._radius = 0; this._diameter = 0; } else { this.radius = this.y - value; } } } public get top(): number { return this.y - this._radius; } /** * Gets the area of this Circle. Note this is READ ONLY. * @property area * @type number * @readOnly * @public */ public get area(): number { if (this._radius > 0) { return Math.PI * this._radius * this._radius; } else { return 0; } } /** * Determines whether or not this Circle object is empty. * @method isEmpty * @return {boolean} A value of true if the Circle objects diameter is less than or equal to 0; otherwise false. * @public */ public get isEmpty(): boolean { if (this._diameter <= 0) { return true; } return false; } /** * Returns a new Circle object with the same values for the x, y, diameter, and radius properties as the original Circle object. * @method clone * @param [output=Circle] {Kiwi.Geom.Circle} If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. * @return {Kiwi.Geom.Circle} * @public */ public clone(output: Circle = new Circle): Circle { return output.setTo(this.x, this.y, this._diameter); } /** * Copies all of circle data from a Circle object passed (the source) into this Circle object. * @method copyFrom * @param source {Kiwi.Geom.Circle} The source circle object to copy from * @return {Kiwi.Geom.Circle} This circle object * @public */ public copyFrom(source: Circle): Circle { return this.setTo(source.x, source.y, source.diameter); } /** * Copies all of circle data from this Circle object into a passed Circle object (destination). * @method copyTo * @param circle {Kiwi.Geom.Circle} The destination circle object to copy in to * @return {Kiwi.Geom.Circle} The destination circle object * @public */ public copyTo(target: Circle) { return target.copyFrom(this); } /** * Returns the distance from the center of this Circle object to the passed object. * The passed object can be a Circle, Point, or anything with x/y values. * * @method distanceTo * @param target {Any} The destination Point object. * @param [round=false] {boolean} Round the distance to the nearest integer (default false) * @return {Number} The distance between this Point object and the destination Point object. * @public */ public distanceTo(target: any, round: boolean = false): number { var dx = this.x - target.x; var dy = this.y - target.y; if (round === true) { return Math.round(Math.sqrt(dx * dx + dy * dy)); } else { return Math.sqrt(dx * dx + dy * dy); } } /** * Determines whether a Circle passed is equal to this Circle. * They are considered 'equal' if both circles have the same values for x, y, and diameter properties. * * @method equals * @param toCompare {Kiwi.Geom.Circle} The circle to compare to this Circle object. * @return {boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. * @public */ public equals(toCompare: Circle): boolean { if (this.x === toCompare.x && this.y === toCompare.y && this.diameter === toCompare.diameter) { return true; } return false; } /** * Determines whether a Circle passed intersects with this Circle. * Returns a boolean indicating if the two circles intersect. * * @method intersects * @param toIntersect {Kiwi.Geom.Circle} The Circle object to compare against to see if it intersects with this Circle object. * @return {boolean} A value of true if the specified object intersects with this Circle object; otherwise false. * @public */ public intersects(toIntersect: Circle): boolean { if (this.distanceTo(toIntersect, false) < (this._radius + toIntersect._radius)) { return true; } return false; } /** * Returns a Point object containing the coordinates of a point on the circumference of this Circle based on the given angle. * * @method circumferencePoint * @param angle {Number} The angle in radians (unless asDegrees is true) to return the point from. * @param [asDegress=false] {boolean} Is the given angle in radians (false) or degrees (true)? * @param [output] {Kiwi.Geom.Point} A Point object to put the result in to. If none specified a new Point object will be created. * @return {Kiwi.Geom.Point} The Point object holding the result. * @public */ public circumferencePoint(angle: number, asDegrees: boolean = false, output: Point = new Point): Point { if (asDegrees === true) { angle = angle * (Math.PI / 180); // Radians to Degrees //angle = angle * (180 / Math.PI); // Degrees to Radians } output.x = this.x + this._radius * Math.cos(angle); output.y = this.y + this._radius * Math.sin(angle); return output; } /** * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts. * @method offset * @param dx {Number} Moves the x value of the Circle object by this amount. * @param dy {Number} Moves the y value of the Circle object by this amount. * @return {Kiwi.Geom.Circle} This Circle object. * @public */ public offset(dx: number, dy: number): Circle { if (!isNaN(dx) && !isNaN(dy)) { this.x += dx; this.y += dy; } return this; } /** * Adjusts the location of the Circle object using a Point object as a parameter. * This method is similar to the 'offset' method, except that it takes a Point object as a parameter. * * @method offsetPoint * @param {Kiwi.Geom.Point} point A Point object to use to offset this Circle object. * @return {Kiwi.Geom.Circle} This Circle object. * @public */ public offsetPoint(point: Point): Circle { return this.offset(point.x, point.y); } /** * Sets the members of Circle to the specified values. * * @method setTo * @param x {Number} The x coordinate of the center of the circle. * @param y {Number} The y coordinate of the center of the circle. * @param diameter {Number} The diameter of the circle in pixels. * @return {Kiwi.Geom.Circle} This circle object * @public */ public setTo(x: number, y: number, diameter: number): Circle { this.x = x; this.y = y; this._diameter = diameter; this._radius = diameter * 0.5; return this; } /** * Returns a string representation of this object. * @method toString * @return {string} a string representation of the instance. * @public */ public toString(): string { return "[{Circle (x=" + this.x + " y=" + this.y + " diameter=" + this.diameter + " radius=" + this.radius + ")}]"; } } }
the_stack
import { Component, ReactElement } from 'react'; import { Icon } from '@alifd/next'; import classNames from 'classnames'; import { Title, observer, Tip, globalContext, Editor } from '@alilc/lowcode-editor-core'; import { DockProps } from '../../types'; import PanelDock from '../../widget/panel-dock'; import { composeTitle } from '../../widget/utils'; import WidgetContainer from '../../widget/widget-container'; import Panel from '../../widget/panel'; import { IWidget } from '../../widget/widget'; import { SkeletonEvents } from '../../skeleton'; import DraggableLine from '../draggable-line'; import PanelOperationRow from './panel-operation-row'; import './index.less'; export function DockView({ title, icon, description, size, className, onClick }: DockProps) { return ( <Title title={composeTitle(title, icon, description)} className={classNames('lc-dock', className, { [`lc-dock-${size}`]: size, })} onClick={onClick} /> ); } function HelpTip({ tip }: any) { if (tip && tip.url) { return ( <div> <a href={tip.url} target="_blank" rel="noopener noreferrer"> <Icon type="help" size="small" className="lc-help-tip" /> </a> <Tip>{tip.content}</Tip> </div> ); } return ( <div> <Icon type="help" size="small" className="lc-help-tip" /> <Tip>{tip.content}</Tip> </div> ); } @observer export class PanelDockView extends Component<DockProps & { dock: PanelDock }> { componentDidMount() { this.checkActived(); } componentDidUpdate() { this.checkActived(); } private lastActived = false; checkActived() { const { dock } = this.props; if (dock.actived !== this.lastActived) { this.lastActived = dock.actived; if (this.lastActived) { dock.skeleton.postEvent(SkeletonEvents.PANEL_DOCK_ACTIVE, dock.name, dock); } else { dock.skeleton.postEvent(SkeletonEvents.PANEL_DOCK_UNACTIVE, dock.name, dock); } } } render() { const { dock, className, onClick, ...props } = this.props; return DockView({ ...props, className: classNames(className, { actived: dock.actived, }), onClick: () => { onClick && onClick(); dock.togglePanel(); }, }); } } export class DialogDockView extends Component {} export class DraggableLineView extends Component<{ panel: Panel }> { private shell: any; private defaultWidth: number; private getDefaultWidth() { const configWidth = this.props.panel?.config.props?.width; if (configWidth) { return configWidth; } if (this.defaultWidth) { return this.defaultWidth; } const containerRef = this.shell?.getParent(); if (containerRef) { this.defaultWidth = containerRef.offsetWidth; return this.defaultWidth; } return 300; } onDrag(value: number) { const defaultWidth = this.getDefaultWidth(); const width = defaultWidth + value; const containerRef = this.shell?.getParent(); if (containerRef) { containerRef.style.width = `${width}px`; } // 抛出事件,对于有些需要 panel 插件随着 度变化进行再次渲染的,由panel插件内部监听事件实现 const editor = globalContext.get(Editor); editor?.emit('dockpane.drag', width); } onDragChange(type: 'start' | 'end') { const editor = globalContext.get(Editor); editor?.emit('dockpane.dragchange', type); // builtinSimulator 屏蔽掉 鼠标事件 editor?.emit('designer.builtinSimulator.disabledEvents', type === 'start'); } render() { // left fixed 下不允许改变宽度 // 默认 关闭,通过配置开启 const enableDrag = this.props.panel.config.props?.enableDrag; const isRightArea = this.props.panel.config?.area === 'rightArea'; if (isRightArea || !enableDrag || this.props.panel?.parent.name === 'leftFixedArea') { return null; } return ( <DraggableLine ref={(ref) => { this.shell = ref; }} position="right" className="lc-engine-slate-draggable-line-right" onDrag={(e) => this.onDrag(e)} onDragStart={() => this.onDragChange('start')} onDragEnd={() => this.onDragChange('end')} maxIncrement={500} maxDecrement={0} // TODO: 优化 // maxIncrement={dock.getMaxWidth() - this.cachedSize.width} // maxDecrement={this.cachedSize.width - dock.getWidth()} /> ); } } @observer export class TitledPanelView extends Component<{ panel: Panel; area?: string }> { componentDidMount() { this.checkVisible(); } componentDidUpdate() { this.checkVisible(); } private lastVisible = false; checkVisible() { const { panel } = this.props; const currentVisible = panel.inited && panel.visible; if (currentVisible !== this.lastVisible) { this.lastVisible = currentVisible; if (this.lastVisible) { panel.skeleton.postEvent(SkeletonEvents.PANEL_SHOW, panel.name, panel); } else { panel.skeleton.postEvent(SkeletonEvents.PANEL_HIDE, panel.name, panel); } } } render() { const { panel, area } = this.props; if (!panel.inited) { return null; } const editor = globalContext.get(Editor); const panelName = area ? `${area}-${panel.name}` : panel.name; editor?.emit('skeleton.panel.toggle', { name: panelName || '', status: panel.visible ? 'show' : 'hide', }); return ( <div className={classNames('lc-titled-panel', { hidden: !panel.visible, })} id={panelName} data-keep-visible-while-dragging={panel.config.props?.keepVisibleWhileDragging} > <PanelOperationRow panel={panel} /> <PanelTitle panel={panel} /> <div className="lc-panel-body">{panel.body}</div> <DraggableLineView panel={panel} /> </div> ); } } @observer export class PanelView extends Component<{ panel: Panel; area?: string; hideOperationRow?: boolean; hideDragLine?: boolean; }> { componentDidMount() { this.checkVisible(); } componentDidUpdate() { this.checkVisible(); } private lastVisible = false; checkVisible() { const { panel } = this.props; const currentVisible = panel.inited && panel.visible; if (currentVisible !== this.lastVisible) { this.lastVisible = currentVisible; if (this.lastVisible) { panel.skeleton.postEvent(SkeletonEvents.PANEL_SHOW, panel.name, panel); // FIXME! remove this line panel.skeleton.postEvent('leftPanel.show' as any, panel.name, panel); } else { panel.skeleton.postEvent(SkeletonEvents.PANEL_HIDE, panel.name, panel); // FIXME! remove this line panel.skeleton.postEvent('leftPanel.hide' as any, panel.name, panel); } } } render() { const { panel, area, hideOperationRow, hideDragLine } = this.props; if (!panel.inited) { return null; } const editor = globalContext.get(Editor); const panelName = area ? `${area}-${panel.name}` : panel.name; editor?.emit('skeleton.panel.toggle', { name: panelName || '', status: panel.visible ? 'show' : 'hide', }); return ( <div className={classNames('lc-panel', { hidden: !panel.visible, })} id={panelName} data-keep-visible-while-dragging={panel.config.props?.keepVisibleWhileDragging} > {!hideOperationRow && <PanelOperationRow panel={panel} />} {panel.body} {!hideDragLine && <DraggableLineView panel={panel} />} </div> ); } } @observer export class TabsPanelView extends Component<{ container: WidgetContainer<Panel> }> { render() { const { container } = this.props; const titles: ReactElement[] = []; const contents: ReactElement[] = []; container.items.forEach((item: any) => { titles.push(<PanelTitle key={item.id} panel={item} className="lc-tab-title" />); contents.push(<PanelView key={item.id} panel={item} hideOperationRow hideDragLine />); }); return ( <div className="lc-tabs"> <div className="lc-tabs-title" onClick={(e) => { const shell = e.currentTarget; const t = e.target as Element; let elt = shell.firstElementChild; while (elt) { if (elt.contains(t)) { break; } elt = elt.nextElementSibling; } if (elt) { container.active((elt as any).dataset.name); } }} > {titles} </div> <div className="lc-tabs-content">{contents}</div> </div> ); } } @observer class PanelTitle extends Component<{ panel: Panel; className?: string }> { render() { const { panel, className } = this.props; return ( <div className={classNames('lc-panel-title', className, { actived: panel.actived, })} data-name={panel.name} > <Title title={panel.title || panel.name} /> {panel.help ? <HelpTip tip={panel.help} /> : null} </div> ); } } @observer export class WidgetView extends Component<{ widget: IWidget }> { componentDidMount() { this.checkVisible(); this.checkDisabled(); } componentDidUpdate() { this.checkVisible(); this.checkDisabled(); } private lastVisible = false; private lastDisabled = false; checkVisible() { const { widget } = this.props; const currentVisible = widget.visible; if (currentVisible !== this.lastVisible) { this.lastVisible = currentVisible; if (this.lastVisible) { widget.skeleton.postEvent(SkeletonEvents.WIDGET_SHOW, widget.name, widget); } else { widget.skeleton.postEvent(SkeletonEvents.WIDGET_SHOW, widget.name, widget); } } } checkDisabled() { const { widget } = this.props; const currentDisabled = widget.disabled; if (currentDisabled !== this.lastDisabled) { this.lastDisabled = currentDisabled; if (this.lastDisabled) { widget.skeleton.postEvent(SkeletonEvents.WIDGET_DISABLE, widget.name, widget); } else { widget.skeleton.postEvent(SkeletonEvents.WIDGET_ENABLE, widget.name, widget); } } } render() { const { widget } = this.props; if (!widget.visible) { return null; } if (widget.disabled) { return <div className="lc-widget-disabled">{widget.body}</div>; } return widget.body; } }
the_stack
interface JQuery { embed: SemanticUI.Embed; } declare namespace SemanticUI { interface Embed { settings: EmbedSettings; /** * Changes iframe to a new content source */ (behavior: 'change', source: string, id: string, url: string): JQuery; /** * Removes embed and shows placeholder content if available */ (behavior: 'reset'): JQuery; /** * Shows embed content */ (behavior: 'show'): JQuery; /** * Hides embed content and shows placeholder content */ (behavior: 'hide'): JQuery; /** * Returns current content id */ (behavior: 'get id'): string; /** * Returns placeholder image url */ (behavior: 'get placeholder'): string; /** * Returns source name */ (behavior: 'get sources'): string; /** * Returns source type */ (behavior: 'get type'): string; /** * Returns URL with all parameters added */ (behavior: 'get url'): string; /** * Returns whether embed content has placeholder */ (behavior: 'has placeholder'): boolean; /** * Destroys instance and removes all events */ (behavior: 'destroy'): JQuery; <K extends keyof EmbedSettings>(behavior: 'setting', name: K, value?: undefined): EmbedSettings._Impl[K]; <K extends keyof EmbedSettings>(behavior: 'setting', name: K, value: EmbedSettings._Impl[K]): JQuery; (behavior: 'setting', value: EmbedSettings): JQuery; (settings?: EmbedSettings): JQuery; } /** * @see {@link http://semantic-ui.com/modules/embed.html#/settings} */ type EmbedSettings = EmbedSettings.Param; namespace EmbedSettings { type Param = (Pick<_Impl, 'url'> | Pick<_Impl, 'icon'> | Pick<_Impl, 'source'> | Pick<_Impl, 'id'> | Pick<_Impl, 'parameters'> | Pick<_Impl, 'autoplay'> | Pick<_Impl, 'color'> | Pick<_Impl, 'hd'> | Pick<_Impl, 'brandedUI'> | Pick<_Impl, 'onCreate'> | Pick<_Impl, 'onDisplay'> | Pick<_Impl, 'onPlaceholderDisplay'> | Pick<_Impl, 'onEmbed'> | Pick<_Impl, 'selector'> | Pick<_Impl, 'metadata'> | Pick<_Impl, 'className'> | Pick<_Impl, 'templates'> | 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 { /** * Specifies a url to use for embed * * @default false */ url: false | string; // region Embed Settings /** * Specifies an icon to use with placeholder content * * @default false */ icon: false | string; /** * Specifies a source to use, if no source is provided it will be determined from the domain of a specified url. * * @default false */ source: false | string; /** * Specifies an id value to replace with the {id} value found in templated urls * * @default false */ id: false | string; /** * Specify an object containing key/value pairs to add to the iframes GET parameters * * @default false */ parameters: false | Embed.ParametersSettings; // endregion // region Video Settings /** * Default setting auto will only autoplay content when a placeholder is specified. Setting to true or false will force autoplay. * * @default 'auto' */ autoplay: 'auto' | boolean; /** * Specifies a default chrome color with Vimeo or YouTube. * * @default '#444444' */ color: string; /** * Whether to prefer HD content * * @default true */ hd: boolean; /** * Whether to show networks branded UI like title cards, or after video calls to action. * * @default false */ brandedUI: boolean; // endregion // region Callbacks /** * Callback when iframe is generated */ onCreate(this: JQuery, url: string): void; /** * Whenever an iframe contents is shown */ onDisplay(this: JQuery): void; /** * Callback immediately before Embed is removed from DOM */ onPlaceholderDisplay(this: JQuery): void; /** * Callback when module parameters are determined. Allows you to adjust parameters at run time by returning a new parameters object. */ onEmbed(this: JQuery, parameters: Embed.ParametersSettings): Embed.ParametersSettings; // endregion // region DOM Settings /** * DOM Selectors used internally */ selector: Embed.SelectorSettings; /** * HTML Data attributes used to store data */ metadata: Embed.MetadataSettings; /** * Class names used to attach style to state */ className: Embed.ClassNameSettings; templates: Embed.TemplatesSettings; // endregion // region Debug Settings error: Embed.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 Embed { type ParametersSettings = ParametersSettings._Impl; namespace ParametersSettings { type Param = _Impl; interface _Impl { [key: string]: any; } } type SelectorSettings = SelectorSettings.Param; namespace SelectorSettings { type Param = (Pick<_Impl, 'embed'> | Pick<_Impl, 'placeholder'> | Pick<_Impl, 'play'>) & Partial<Pick<_Impl, keyof _Impl>>; interface _Impl { /** * @default '.embed' */ embed: string; /** * @default '.placeholder' */ placeholder: string; /** * @default '.play' */ play: string; } } type MetadataSettings = MetadataSettings.Param; namespace MetadataSettings { type Param = (Pick<_Impl, 'id'> | Pick<_Impl, 'icon'> | Pick<_Impl, 'placeholder'> | Pick<_Impl, 'source'> | Pick<_Impl, 'url'>) & Partial<Pick<_Impl, keyof _Impl>>; interface _Impl { /** * @default 'id' */ id: string; /** * @default 'icon' */ icon: string; /** * @default 'placeholder' */ placeholder: string; /** * @default 'source' */ source: string; /** * @default 'url' */ url: string; } } type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { type Param = (Pick<_Impl, 'active'> | Pick<_Impl, 'embed'>) & Partial<Pick<_Impl, keyof _Impl>>; interface _Impl { /** * @default 'active' */ active: string; /** * @default 'embed' */ embed: string; } } type TemplatesSettings = TemplatesSettings.Param; namespace TemplatesSettings { type Param = (Pick<_Impl, 'iframe'> | Pick<_Impl, 'placeholder'>) & Partial<Pick<_Impl, keyof _Impl>>; interface _Impl { /** * returns html for iframe */ iframe(url: string, parameters: string): string; /** * returns html for placeholder element */ placeholder(image: string, icon: string): string; } } type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { type Param = (Pick<_Impl, 'noURL'> | Pick<_Impl, 'method'>) & Partial<Pick<_Impl, keyof _Impl>>; interface _Impl { /** * @default 'No URL specified' */ noURL: string; /** * @default 'The method you called is not defined' */ method: string; } } } }
the_stack
// Copyright (c) 2015 Vadim Macagon // MIT License, see LICENSE file for full terms. import * as readline from 'readline'; import * as events from 'events'; import * as stream from 'stream'; import * as parser from './mi_output_parser'; import { RecordType } from './mi_output'; // import * as bunyan from 'bunyan'; import Logger = require('bunyan'); import * as LLDBEvents from './events'; import { IBreakpointInfo, IBreakpointLocationInfo, IStackFrameInfo, IStackFrameArgsInfo, IStackFrameVariablesInfo, IVariableInfo, IWatchInfo, IWatchUpdateInfo, IWatchChildInfo, IMemoryBlock, IAsmInstruction, ISourceLineAsm, IThreadFrameInfo, IThreadInfo, IMultiThreadInfo, VariableDetailLevel, WatchFormatSpec, WatchAttribute, RegisterValueFormatSpec } from './types'; import { extractBreakpointInfo, extractStackFrameInfo, extractWatchChildren, extractAsmInstructions, extractAsmBySourceLine, extractThreadInfo } from './extractors'; import { CommandFailedError, MalformedResponseError } from './errors'; import * as rawCommandOuputParser from './raw_command_output_parser'; // aliases type ReadLine = readline.ReadLine; type ErrDataCallback = (err: Error, data: any) => void; class DebugCommand { //JIN isRawCommand: boolean //workaround persist the output (state) between lines output = [] /** * Optional token that can be used to match up the command with a response, * if provided it must only contain digits. */ token: string; /** The MI command string that will be sent to debugger (minus the token and dash prefix). */ text: string; /** Optional callback to invoke once a response is received for the command. */ done: ErrDataCallback; /** * @param cmd MI command string (minus the token and dash prefix). * @param token Token that can be used to match up the command with a response. * @param done Callback to invoke once a response is received for the command. */ constructor(cmd: string, token?: string, done?: ErrDataCallback, isRawCommand: boolean = false) { this.token = token; this.text = cmd; this.done = done; this.isRawCommand = isRawCommand } } /** * A debug session provides two-way communication with a debugger process via the GDB/LLDB * machine interface. * * Currently commands are queued and executed one at a time in the order they are issued, * a command will not be executed until all the previous commands have been acknowledged by the * debugger. * * Out of band notifications from the debugger are emitted via events, the names of these events * are provided by the EVENT_XXX static constants. */ export default class DebugSession extends events.EventEmitter { // the stream to which debugger commands will be written private outStream: stream.Writable; // reads input from the debugger's stdout one line at a time private lineReader: ReadLine; // used to generate to auto-generate tokens for commands // FIXME: this is currently unused since I need to decide if tokens should be auto-generated // when the user doesn't supply them. private nextCmdId: number; // commands to be processed (one at a time) private cmdQueue: DebugCommand[]; // used to to ensure session cleanup is only done once private cleanupWasCalled: boolean; private _logger: Logger; get logger(): Logger { return this._logger; } set logger(logger: Logger) { this._logger = logger; } /** * In most cases [[startDebugSession]] should be used to construct new instances. * * @param inStream Debugger responses and notifications will be read from this stream. * @param outStream Debugger commands will be written to this stream. */ constructor(inStream: stream.Readable, outStream: stream.Writable) { super(); this.outStream = outStream; this.lineReader = readline.createInterface({ input: inStream, output: null }); this.lineReader.on('line', this.parseDebbugerOutput.bind(this)); this.nextCmdId = 1; this.cmdQueue = []; this.cleanupWasCalled = false; } /** * Ends the debugging session. * * @param notifyDebugger If **false** the session is cleaned up immediately without waiting for * the debugger to respond (useful in cases where the debugger terminates * unexpectedly). If **true** the debugger is asked to exit, and once the * request is acknowldeged the session is cleaned up. */ end(notifyDebugger: boolean = true): Promise<void> { return new Promise<void>((resolve, reject) => { var cleanup = (err: Error, data: any) => { this.cleanupWasCalled = true; this.lineReader.close(); err ? reject(err) : resolve(); }; if (!this.cleanupWasCalled) { notifyDebugger ? this.enqueueCommand(new DebugCommand('gdb-exit', null, cleanup)) : cleanup(null, null); }; }); } /** * Returns `true` if [[EVENT_FUNCTION_FINISHED]] can be emitted during this debugging session. * * LLDB-MI currently doesn't emit [[EVENT_FUNCTION_FINISHED]] after stepping out of a function, * instead it emits [[EVENT_STEP_FINISHED]] just like it does for any other stepping operation. */ canEmitFunctionFinishedNotification(): boolean { return false; } private emitExecNotification(name: string, data: any) { let events = LLDBEvents.createEventsForExecNotification(name, data); events.forEach((event: LLDBEvents.IDebugSessionEvent) => { this.emit(event.name, event.data); }); } private emitAsyncNotification(name: string, data: any) { let event = LLDBEvents.createEventForAsyncNotification(name, data); if (event) { this.emit(event.name, event.data); } else { if (this.logger) { this.logger.warn({ name: name, data: data }, 'Unhandled notification.'); } } } /** * Parse a single line containing a response to a MI command or some sort of async notification. */ private parseDebbugerOutput(line: string): void { // '(gdb)' (or '(gdb) ' in some cases) is used to indicate the end of a set of output lines // from the debugger, but since we process each line individually as it comes in this // particular marker is of no use if (line.match(/^\(gdb\)\s*/) || (line === '')) { return; } //JIN add adhoc logics for the output of raw command exec let result: parser.Record; var ccmd: DebugCommand = this.cmdQueue[0];//FIXME ?this.cmdQueue[0] != undefined/null if (ccmd && ccmd.isRawCommand) {// if (line != "^done") { ccmd.output.push(line) return } else { result = { recordType: RecordType.Done, data: ccmd.output } } } else {//original logics var cmdQueuePopped: boolean = false; try { result = parser.parse(line); } catch (err) { if (this.logger) { this.logger.error(err, 'Attempted to parse: ->' + line + '<-'); } // throw err; //FIXME some mi outputs can not be handled correctly result = { recordType: RecordType.AsyncNotify, data: [LLDBEvents.EVENT_TARGET_OUTPUT, ""] } } } switch (result.recordType) { case RecordType.Done: case RecordType.Running: case RecordType.Connected: case RecordType.Exit: case RecordType.Error: // this record is a response for the last command that was sent to the debugger, // which is the command at the front of the queue var cmd = this.cmdQueue.shift(); cmdQueuePopped = true; // todo: check that the token in the response matches the one sent with the command if (cmd.done) { if (result.recordType === RecordType.Error) { cmd.done( new CommandFailedError(result.data.msg, cmd.text, result.data.code, cmd.token), null ); } else { cmd.done(null, result.data); } } break; case RecordType.AsyncExec: this.emitExecNotification(result.data[0], result.data[1]); break; case RecordType.AsyncNotify: this.emitAsyncNotification(result.data[0], result.data[1]); break; case RecordType.DebuggerConsoleOutput: this.emit(LLDBEvents.EVENT_DBG_CONSOLE_OUTPUT, result.data); break; case RecordType.TargetOutput: this.emit(LLDBEvents.EVENT_TARGET_OUTPUT, result.data); break; case RecordType.DebuggerLogOutput: this.emit(LLDBEvents.EVENT_DBG_LOG_OUTPUT, result.data); break; } // if a command was popped from the qeueu we can send through the next command if (cmdQueuePopped && (this.cmdQueue.length > 0)) { this.sendCommandToDebugger(this.cmdQueue[0]); } } /** * Sends an MI command to the debugger process. */ private sendCommandToDebugger(command: DebugCommand): void { var cmdStr: string; if (command.token) { cmdStr = `${command.token}-${command.text}`; } else { cmdStr = command.isRawCommand ? command.text : '-' + command.text; } if (this.logger) { this.logger.info(cmdStr); } this.outStream.write(cmdStr + '\n'); } /** * Adds an MI command to the back of the command queue. * * If the command queue is empty when this method is called then the command is dispatched * immediately, otherwise it will be dispatched after all the previously queued commands are * processed. */ private enqueueCommand(command: DebugCommand): void { this.cmdQueue.push(command); if (this.cmdQueue.length === 1) { this.sendCommandToDebugger(this.cmdQueue[0]); } } /** * Sends an MI command to the debugger. * * @param command Full MI command string, excluding the optional token and dash prefix. * @param token Token to be prefixed to the command string (must consist only of digits). * @returns A promise that will be resolved when the command response is received. */ private executeCommand(command: string, token?: string): Promise<void> { return new Promise<void>((resolve, reject) => { this.enqueueCommand( new DebugCommand(command, token, (err, data) => { err ? reject(err) : resolve(); }) ); }); } /** * Sends an MI command to the debugger and returns the response. * * @param command Full MI command string, excluding the optional token and dash prefix. * @param token Token to be prefixed to the command string (must consist only of digits). * @param transformOutput This function will be invoked with the output of the MI Output parser * and should transform that output into an instance of type `T`. * @returns A promise that will be resolved when the command response is received. */ private getCommandOutput<T>(command: string, token?: string, transformOutput?: (data: any) => T, isRawCommand: boolean = false) : Promise<T> { return new Promise<T>((resolve, reject) => { this.enqueueCommand( new DebugCommand(command, token, (err, data) => { if (err) { reject(err); } else { try { resolve(transformOutput ? transformOutput(data) : data); } catch (err) { reject(err); } } }, isRawCommand) ); }); } /** * Sets the executable file to be debugged, the symbol table will also be read from this file. * * This must be called prior to [[connectToRemoteTarget]] when setting up a remote debugging * session. * * @param file This would normally be a full path to the host's copy of the executable to be * debugged. */ setExecutableFile(file: string): Promise<void> { // NOTE: While the GDB/MI spec. contains multiple -file-XXX commands that allow the // executable and symbol files to be specified separately the LLDB MI driver // currently (30-Mar-2015) only supports this one command. return this.executeCommand(`file-exec-and-symbols ${file}`); } /** * Sets the terminal to be used by the next inferior that's launched. * * @param slaveName Name of the slave end of a pseudoterminal that should be associated with * the inferior, see `man pty` for an overview of pseudoterminals. */ setInferiorTerminal(slaveName: string): Promise<void> { return this.executeCommand('inferior-tty-set ' + slaveName); } /** * Connects the debugger to a remote target. * * @param host * @param port */ connectToRemoteTarget(host: string, port: number): Promise<void> { return this.executeCommand(`target-select remote ${host}:${port}`); } // // Breakpoint Commands // /** * Adds a new breakpoint. * * @param location The location at which a breakpoint should be added, can be specified in the * following formats: * - function_name * - filename:line_number * - filename:function_name * - address * @param options.isTemp Set to **true** to create a temporary breakpoint which will be * automatically removed after being hit. * @param options.isHardware Set to **true** to create a hardware breakpoint * (presently not supported by LLDB MI). * @param options.isPending Set to **true** if the breakpoint should still be created even if * the location cannot be parsed (e.g. it refers to uknown files or * functions). * @param options.isDisabled Set to **true** to create a breakpoint that is initially disabled, * otherwise the breakpoint will be enabled by default. * @param options.isTracepoint Set to **true** to create a tracepoint * (presently not supported by LLDB MI). * @param options.condition The debugger will only stop the program execution when this * breakpoint is hit if the condition evaluates to **true**. * @param options.ignoreCount The number of times the breakpoint should be hit before it takes * effect, zero (the default) means the breakpoint will stop the * program every time it's hit. * @param options.threadId Restricts the new breakpoint to the given thread. */ addBreakpoint( location: string, options?: { isTemp?: boolean; isHardware?: boolean; isPending?: boolean; isDisabled?: boolean; isTracepoint?: boolean; condition?: string; ignoreCount?: number; threadId?: number; } ): Promise<IBreakpointInfo> { var cmd: string = 'break-insert'; if (options) { if (options.isTemp) { cmd = cmd + ' -t'; } if (options.isHardware) { cmd = cmd + ' -h'; } if (options.isPending) { cmd = cmd + ' -f'; } if (options.isDisabled) { cmd = cmd + ' -d'; } if (options.isTracepoint) { cmd = cmd + ' -a'; } if (options.condition) { cmd = cmd + ' -c ' + options.condition; } if (options.ignoreCount !== undefined) { cmd = cmd + ' -i ' + options.ignoreCount; } if (options.threadId !== undefined) { cmd = cmd + ' -p ' + options.threadId; } } return this.getCommandOutput<IBreakpointInfo>(cmd + ' ' + location, null, extractBreakpointInfo); } /** * Removes a breakpoint. */ removeBreakpoint(breakId: number): Promise<void> { return this.executeCommand('break-delete ' + breakId); } /** * Removes multiple breakpoints. */ removeBreakpoints(breakIds: number[]): Promise<void> { // FIXME: LLDB MI driver only supports removing one breakpoint at a time, // so multiple breakpoints need to be removed one by one. return this.executeCommand('break-delete ' + breakIds.join(' ')); } /** * Enables a breakpoint. */ enableBreakpoint(breakId: number): Promise<void> { return this.executeCommand('break-enable ' + breakId); } /** * Enables multiple breakpoints. */ enableBreakpoints(breakIds: number[]): Promise<void> { return this.executeCommand('break-enable ' + breakIds.join(' ')); } /** * Disables a breakpoint. */ disableBreakpoint(breakId: number): Promise<void> { return this.executeCommand('break-disable ' + breakId); } /** * Disables multiple breakpoints. */ disableBreakpoints(breakIds: number[]): Promise<void> { return this.executeCommand('break-disable ' + breakIds.join(' ')); } /** * Tells the debugger to ignore a breakpoint the next `ignoreCount` times it's hit. * * @param breakId Identifier of the breakpoint for which the ignore count should be set. * @param ignoreCount The number of times the breakpoint should be hit before it takes effect, * zero means the breakpoint will stop the program every time it's hit. */ ignoreBreakpoint( breakId: number, ignoreCount: number): Promise<IBreakpointInfo> { return this.getCommandOutput<IBreakpointInfo>( `break-after ${breakId} ${ignoreCount}`, null, extractBreakpointInfo ); } /** * Sets the condition under which a breakpoint should take effect when hit. * * @param breakId Identifier of the breakpoint for which the condition should be set. * @param condition Expression to evaluate when the breakpoint is hit, if it evaluates to * **true** the breakpoint will stop the program, otherwise the breakpoint * will have no effect. */ setBreakpointCondition( breakId: number, condition: string): Promise<void> { return this.executeCommand(`break-condition ${breakId} ${condition}`); } // // Program Execution Commands // /** * Sets the commandline arguments to be passed to the inferior next time it is started * using [[startInferior]]. */ setInferiorArguments(args: string): Promise<void> { return this.executeCommand('exec-arguments ' + args); } /** * Executes an inferior from the beginning until it exits. * * Execution may stop before the inferior finishes running due to a number of reasons, * for example a breakpoint being hit. * [[EVENT_TARGET_STOPPED]] will be emitted when execution stops. * * @param options.threadGroup *(GDB specific)* The identifier of the thread group to start, * if omitted the currently selected inferior will be started. * @param options.stopAtStart *(GDB specific)* If `true` then execution will stop at the start * of the main function. */ startInferior( options?: { threadGroup?: string; stopAtStart?: boolean }): Promise<void> { var fullCmd: string = 'exec-run'; if (options) { if (options.threadGroup) { fullCmd = fullCmd + ' --thread-group ' + options.threadGroup; } if (options.stopAtStart) { fullCmd = fullCmd + ' --start'; } } return this.executeCommand(fullCmd, null); } /** * Executes all inferiors from the beginning until they exit. * * Execution may stop before an inferior finishes running due to a number of reasons, * for example a breakpoint being hit. * [[EVENT_TARGET_STOPPED]] will be emitted when execution stops. * * @param stopAtStart *(GDB specific)* If `true` then execution will stop at the start * of the main function. */ startAllInferiors(stopAtStart?: boolean): Promise<void> { var fullCmd: string = 'exec-run --all'; if (stopAtStart) { fullCmd = fullCmd + ' --start'; } return this.executeCommand(fullCmd, null); } /** * Kills the currently selected inferior. */ abortInferior(): Promise<void> { return this.executeCommand('exec-abort'); } /** * Resumes execution of an inferior, execution may stop at any time due to a number of reasons, * for example a breakpoint being hit. * [[EVENT_TARGET_STOPPED]] will be emitted when execution stops. * * @param options.threadGroup *(GDB specific)* Identifier of the thread group to resume, * if omitted the currently selected inferior is resumed. * @param options.reverse *(GDB specific)* If **true** the inferior is executed in reverse. */ resumeInferior( options?: { threadGroup?: string; reverse?: boolean }): Promise<void> { var fullCmd: string = 'exec-continue'; if (options) { if (options.threadGroup) { fullCmd = fullCmd + ' --thread-group ' + options.threadGroup; } if (options.reverse) { fullCmd = fullCmd + ' --reverse'; } } return this.executeCommand(fullCmd, null); } /** * Resumes execution of all inferiors. * * @param reverse *(GDB specific)* If `true` the inferiors are executed in reverse. */ resumeAllInferiors(reverse?: boolean): Promise<void> { var fullCmd: string = 'exec-continue --all'; if (reverse) { fullCmd = fullCmd + ' --reverse'; } return this.executeCommand(fullCmd, null); } /** * Interrupts execution of an inferior. * [[EVENT_TARGET_STOPPED]] will be emitted when execution stops. * * @param options.threadGroup The identifier of the thread group to interrupt, if omitted the * currently selected inferior will be interrupted. */ interruptInferior(threadGroup?: string): Promise<void> { var fullCmd: string = 'exec-interrupt'; if (threadGroup) { fullCmd = fullCmd + ' --thread-group ' + threadGroup; } return this.executeCommand(fullCmd, null); } /** * Interrupts execution of all threads in all inferiors. * * [[EVENT_TARGET_STOPPED]] will be emitted when execution stops. */ interruptAllInferiors(): Promise<void> { return this.executeCommand('exec-interrupt --all', null); } /** * Resumes execution of the target until the beginning of the next source line is reached. * If a function is called while the target is running then execution stops on the first * source line of the called function. * [[EVENT_TARGET_STOPPED]] will be emitted when execution stops. * * @param options.threadId Identifier of the thread to execute the command on. * @param options.reverse *(GDB specific)* If **true** the target is executed in reverse. */ stepIntoLine(options?: { threadId?: number; reverse?: boolean }): Promise<void> { return this.executeCommand(appendExecCmdOptions('exec-step', options)); } /** * Resumes execution of the target until the beginning of the next source line is reached. * [[EVENT_TARGET_STOPPED]] will be emitted when execution stops. * * @param options.threadId Identifier of the thread to execute the command on. * @param options.reverse *(GDB specific)* If **true** the target is executed in reverse until * the beginning of the previous source line is reached. */ stepOverLine(options?: { threadId?: number; reverse?: boolean }): Promise<void> { return this.executeCommand(appendExecCmdOptions('exec-next', options)); } /** * Executes one instruction, if the instruction is a function call then execution stops at the * beginning of the function. * [[EVENT_TARGET_STOPPED]] will be emitted when execution stops. * * @param options.threadId Identifier of the thread to execute the command on. * @param options.reverse *(GDB specific)* If **true** the target is executed in reverse until * the previous instruction is reached. */ stepIntoInstruction( options?: { threadId?: number; reverse?: boolean }): Promise<void> { return this.executeCommand(appendExecCmdOptions('exec-step-instruction', options)); } /** * Executes one instruction, if the instruction is a function call then execution continues * until the function returns. * [[EVENT_TARGET_STOPPED]] will be emitted when execution stops. * * @param options.threadId Identifier of the thread to execute the command on. * @param options.reverse *(GDB specific)* If **true** the target is executed in reverse until * the previous instruction is reached. */ stepOverInstruction( options?: { threadId?: number; reverse?: boolean }): Promise<void> { return this.executeCommand(appendExecCmdOptions('exec-next-instruction', options)); } /** * Resumes execution of the target until the current function returns. * [[EVENT_TARGET_STOPPED]] will be emitted when execution stops. * * @param options.threadId Identifier of the thread to execute the command on. * @param options.reverse *(GDB specific)* If **true** the target is executed in reverse. */ stepOut(options?: { threadId?: number; reverse?: boolean }): Promise<void> { return this.executeCommand(appendExecCmdOptions('exec-finish', options)); } // // Stack Inspection Commands // /** * Retrieves information about a stack frame. * * @param options.threadId The thread for which the stack depth should be retrieved, * defaults to the currently selected thread if not specified. * @param options.frameLevel Stack index of the frame for which to retrieve locals, * zero for the innermost frame, one for the frame from which the call * to the innermost frame originated, etc. Defaults to the currently * selected frame if not specified. If a value is provided for this * option then `threadId` must be specified as well. */ getStackFrame( options?: { threadId?: number; frameLevel?: number }): Promise<IStackFrameInfo> { let fullCmd = 'stack-info-frame'; if (options) { if (options.threadId !== undefined) { fullCmd = fullCmd + ' --thread ' + options.threadId; } if (options.frameLevel !== undefined) { fullCmd = fullCmd + ' --frame ' + options.frameLevel; } } return this.getCommandOutput(fullCmd, null, (output: any) => { return extractStackFrameInfo(output.frame); }); } /** * Retrieves the current depth of the stack. * * @param options.threadId The thread for which the stack depth should be retrieved, * defaults to the currently selected thread if not specified. * @param options.maxDepth *(GDB specific)* If specified the returned stack depth will not exceed * this number. */ getStackDepth( options?: { threadId?: number; maxDepth?: number }): Promise<number> { var fullCmd: string = 'stack-info-depth'; if (options) { if (options.threadId !== undefined) { fullCmd = fullCmd + ' --thread ' + options.threadId; } if (options.maxDepth !== undefined) { fullCmd = fullCmd + ' ' + options.maxDepth; } } return this.getCommandOutput(fullCmd, null, (output: any) => { return parseInt(output.depth, 10); }); } /** * Retrieves the frames currently on the stack. * * The `lowFrame` and `highFrame` options can be used to limit the number of frames retrieved, * if both are supplied only the frame with levels in that range (inclusive) are retrieved. * If either `lowFrame` or `highFrame` option is omitted (but not both) then only a single * frame corresponding to that level is retrieved. * * @param options.threadId The thread for which the stack frames should be retrieved, * defaults to the currently selected thread if not specified. * @param options.noFrameFilters *(GDB specific)* If `true` the Python frame filters will not be * executed. * @param options.lowFrame Must not be larger than the actual number of frames on the stack. * @param options.highFrame May be larger than the actual number of frames on the stack, in which * case only the existing frames will be retrieved. */ getStackFrames( options?: { threadId?: number; lowFrame?: number; highFrame?: number; noFrameFilters?: boolean }) : Promise<IStackFrameInfo[]> { var fullCmd: string = 'stack-list-frames'; if (options) { if (options.threadId !== undefined) { fullCmd = fullCmd + ' --thread' + options.threadId; } if (options.noFrameFilters === true) { fullCmd = fullCmd + ' --no-frame-filters'; } if ((options.lowFrame !== undefined) && (options.highFrame !== undefined)) { fullCmd = fullCmd + ` ${options.lowFrame} ${options.highFrame}`; } else if (options.lowFrame !== undefined) { fullCmd = fullCmd + ` ${options.lowFrame} ${options.lowFrame}`; } else if (options.highFrame !== undefined) { fullCmd = fullCmd + ` ${options.highFrame} ${options.highFrame}`; } } return this.getCommandOutput(fullCmd, null, (output: any) => { var data = output.stack.frame; if (Array.isArray(data)) { return data.map((frame: any) => { return extractStackFrameInfo(frame); }); } else { return [extractStackFrameInfo(data)]; } }); } /** * Retrieves a list of all the arguments for the specified frames. * * The `lowFrame` and `highFrame` options can be used to limit the frames for which arguments * are retrieved. If both are supplied only the frames with levels in that range (inclusive) are * taken into account, if both are omitted the arguments of all frames currently on the stack * will be retrieved. * * Note that while it's possible to specify a frame range of one frame in order to retrieve the * arguments of a single frame it's better to just use [[getStackFrameVariables]] instead. * * @param detail Specifies what information should be retrieved for each argument. * @param options.threadId The thread for which arguments should be retrieved, * defaults to the currently selected thread if not specified. * @param options.noFrameFilters *(GDB specific)* If `true` then Python frame filters will not be * executed. * @param options.skipUnavailable If `true` information about arguments that are not available * will not be retrieved. * @param options.lowFrame Must not be larger than the actual number of frames on the stack. * @param options.highFrame May be larger than the actual number of frames on the stack, in which * case only the existing frames will be retrieved. */ getStackFrameArgs( detail: VariableDetailLevel, options?: { threadId?: number; noFrameFilters?: boolean; skipUnavailable?: boolean; lowFrame?: number; highFrame?: number; } ): Promise<IStackFrameArgsInfo[]> { var fullCmd: string = 'stack-list-arguments'; if (options) { if (options.threadId !== undefined) { fullCmd = fullCmd + ' --thread ' + options.threadId; } if (options.noFrameFilters === true) { fullCmd = fullCmd + ' --no-frame-filters'; } if (options.skipUnavailable === true) { fullCmd = fullCmd + ' --skip-unavailable'; } } fullCmd = fullCmd + ' ' + detail; if (options) { if ((options.lowFrame !== undefined) && (options.highFrame !== undefined)) { fullCmd = fullCmd + ` ${options.lowFrame} ${options.highFrame}`; } else if ((options.lowFrame !== undefined) && (options.highFrame === undefined)) { throw new Error("highFrame option must be provided to getStackFrameArgs() if lowFrame option is used."); } else if ((options.lowFrame === undefined) && (options.highFrame !== undefined)) { throw new Error("lowFrame option must be provided to getStackFrameArgs() if highFrame option is used."); } } return this.getCommandOutput(fullCmd, null, (output: any) => { var data = output['stack-args']; if (Array.isArray(data.frame)) { // data is in the form: { frame: [{ level: 0, args: [...] }, { level: 1, args: arg1 }, ...] return data.frame.map((frame: any): IStackFrameArgsInfo => { return { level: parseInt(frame.level, 10), args: Array.isArray(frame.args) ? frame.args : [frame.args] }; }); } else { // data is in the form: { frame: { level: 0, args: [...] } return [{ level: parseInt(data.frame.level, 10), args: Array.isArray(data.frame.args) ? data.frame.args : [data.frame.args] }]; } }); } /** * Retrieves a list of all arguments and local variables in the specified frame. * * @param detail Specifies what information to retrieve for each argument or local variable. * @param options.threadId The thread for which variables should be retrieved, * defaults to the currently selected thread if not specified. * @param options.frameLevel Stack index of the frame for which to retrieve locals, * zero for the innermost frame, one for the frame from which the call * to the innermost frame originated, etc. Defaults to the currently * selected frame if not specified. * @param options.noFrameFilters *(GDB specific)* If `true` then Python frame filters will not be * executed. * @param options.skipUnavailable If `true` information about variables that are not available * will not be retrieved. */ // getStackFrameVariables( // detail: VariableDetailLevel, // options?: { // threadId?: number; // frameLevel: number; // noFrameFilters?: boolean; // skipUnavailable?: boolean; // } // ): Promise<IStackFrameVariablesInfo> { // let fullCmd: string = 'stack-list-variables'; // if (options) { // if (options.threadId !== undefined) { // fullCmd = fullCmd + ' --thread ' + options.threadId; // } // if (options.frameLevel !== undefined) { // fullCmd = fullCmd + ' --frame ' + options.frameLevel; // } // if (options.noFrameFilters === true) { // fullCmd = fullCmd + ' --no-frame-filters'; // } // if (options.skipUnavailable === true) { // fullCmd = fullCmd + ' --skip-unavailable'; // } // } // fullCmd = fullCmd + ' ' + detail; // return this.getCommandOutput(fullCmd, null, (output: any) => { // let args: IVariableInfo[] = []; // let locals: IVariableInfo[] = []; // output.variables.forEach((varInfo: any) => { // if (varInfo.arg === '1') { // args.push({ name: varInfo.name, value: varInfo.value, type: varInfo.type }); // } else { // locals.push({ name: varInfo.name, value: varInfo.value, type: varInfo.type }); // } // }); // return { args: args, locals: locals }; // }); // } // // Watch Manipulation (aka Variable Objects) // /** * Creates a new watch to monitor the value of the given expression. * * @param expression Any expression valid in the current language set (so long as it doesn't * begin with a `*`), or one of the following: * - a memory cell address, e.g. `*0x0000000000400cd0` * - a CPU register name, e.g. `$sp` * @param options.id Unique identifier for the new watch, if omitted one is auto-generated. * Auto-generated identifiers begin with the letters `var` and are followed by * one or more digits, when providing your own identifiers it's best to use a * different naming scheme that doesn't clash with auto-generated identifiers. * @param options.threadId The thread within which the watch expression will be evaluated. * *Default*: the currently selected thread. * @param options.threadGroup * @param options.frameLevel The index of the stack frame within which the watch expression will * be evaluated initially, zero for the innermost stack frame. Note that * if `frameLevel` is specified then `threadId` must also be specified. * *Default*: the currently selected frame. * @param options.frameAddress *(GDB specific)* Address of the frame within which the expression * should be evaluated. * @param options.isFloating Set to `true` if the expression should be re-evaluated every time * within the current frame, i.e. it's not bound to a specific frame. * Set to `false` if the expression should be bound to the frame within * which the watch is created. * *Default*: `false`. */ addWatch( expression: string, options?: { id?: string; threadId?: number; threadGroup?: string; frameLevel?: number; frameAddress?: string; isFloating?: boolean; } ): Promise<IWatchInfo> { var fullCmd: string = 'var-create'; var id = '-'; // auto-generate id var addr = '*'; // use current frame if (options) { if (options.id) { id = options.id; } if (options.threadId !== undefined) { fullCmd = fullCmd + ' --thread ' + options.threadId; } if (options.threadGroup) { fullCmd = fullCmd + ' --thread-group ' + options.threadGroup; } if (options.frameLevel !== undefined) { fullCmd = fullCmd + ' --frame ' + options.frameLevel; } if (options.isFloating === true) { addr = '@'; } else if (options.frameAddress) { addr = options.frameAddress; } } fullCmd = fullCmd + ` ${id} ${addr} ${expression}`; return this.getCommandOutput(fullCmd, null, (output: any) => { return { id: output.name, childCount: parseInt(output.numchild, 10), value: output.value, expressionType: output['type'], threadId: parseInt(output['thread-id'], 10), hasMoreChildren: output.has_more !== '0', isDynamic: output.dynamic === '1', displayHint: output.displayhint }; }); } /** * Destroys a previously created watch. * * @param id Identifier of the watch to destroy. */ removeWatch(id: string): Promise<void> { return this.executeCommand('var-delete ' + id); } /** * Updates the state of an existing watch. * * @param id Identifier of the watch to update. */ updateWatch(id: string, detail?: VariableDetailLevel): Promise<IWatchUpdateInfo[]> { var fullCmd: string = 'var-update'; if (detail !== undefined) { fullCmd = fullCmd + ' ' + detail; } fullCmd = fullCmd + ' ' + id; return this.getCommandOutput(fullCmd, null, (output: any) => { return output.changelist.map((data: any) => { return { id: data.name, childCount: (data.new_num_children ? parseInt(data.new_num_children, 10) : undefined), value: data.value, expressionType: data.new_type, isInScope: data.in_scope === 'true', isObsolete: data.in_scope === 'invalid', hasTypeChanged: data.type_changed === 'true', isDynamic: data.dynamic === '1', displayHint: data.displayhint, hasMoreChildren: data.has_more === '1', newChildren: data.new_children }; }); }); } /** * Retrieves a list of direct children of the specified watch. * * A watch is automatically created for each child that is retrieved (if one doesn't already exist). * The `from` and `to` options can be used to retrieve a subset of children starting from child * index `from` and up to (but excluding) child index `to`, note that this currently doesn't work * on LLDB. * * @param id Identifier of the watch whose children should be retrieved. * @param options.detail One of: * - [[VariableDetailLevel.None]]: Do not retrieve values of children, this is the default. * - [[VariableDetailLevel.All]]: Retrieve values for all children. * - [[VariableDetailLevel.Simple]]: Only retrieve values of children that have a simple type. * @param options.from Zero-based index of the first child to retrieve, if less than zero the * range is reset. `to` must also be set in order for this option to have any * effect. * @param options.to Zero-based index +1 of the last child to retrieve, if less than zero the * range is reset. `from` must also be set in order for this option to have any * effect. */ getWatchChildren( id: string, options?: { detail?: VariableDetailLevel; from?: number; to?: number; }): Promise<IWatchChildInfo[]> { var fullCmd: string = 'var-list-children'; if (options && (options.detail !== undefined)) { fullCmd = fullCmd + ' ' + options.detail; } fullCmd = fullCmd + ' ' + id; if (options && (options.from !== undefined) && (options.to !== undefined)) { fullCmd = fullCmd + ' ' + options.from + ' ' + options.to; } return this.getCommandOutput(fullCmd, null, (output: any) => { return extractWatchChildren(output.children); }); } /** * Sets the output format for the value of a watch. * * @param id Identifier of the watch for which the format specifier should be set. * @param formatSpec The output format for the watch value. * @returns A promise that will be resolved with the value of the watch formatted using the * provided `formatSpec`. */ setWatchValueFormat(id: string, formatSpec: WatchFormatSpec): Promise<string> { var fullCmd: string = `var-set-format ${id} ` + watchFormatSpecToStringMap.get(formatSpec); return this.getCommandOutput<string>(fullCmd, null, (output: any) => { if (output.value) { return output.value; // GDB-MI } else { return output.changelist[0].value; // LLDB-MI } }); } /** * Evaluates the watch expression and returns the result. * * @param id Identifier of the watch whose value should be retrieved. * @param formatSpec The output format for the watch value. * @returns A promise that will be resolved with the value of the watch. */ getWatchValue(id: string, formatSpec?: WatchFormatSpec): Promise<string> { var fullCmd: string = 'var-evaluate-expression'; if (formatSpec !== undefined) { fullCmd = fullCmd + ' -f ' + watchFormatSpecToStringMap.get(formatSpec); } fullCmd = fullCmd + ' ' + id; return this.getCommandOutput(fullCmd, null, (output: any) => { return output.value; }); } /** * Sets the value of the watch expression to the value of the given expression. * * @param id Identifier of the watch whose value should be modified. * @param expression The value of this expression will be assigned to the watch expression. * @returns A promise that will be resolved with the new value of the watch. */ setWatchValue(id: string, expression: string): Promise<string> { return this.getCommandOutput(`var-assign ${id} "${expression}"`, null, (output: any) => { return output.value; }); } /** * Retrives a list of attributes for the given watch. * * @param id Identifier of the watch whose attributes should be retrieved. * @returns A promise that will be resolved with the list of watch attributes. */ getWatchAttributes(id: string): Promise<WatchAttribute[]> { var cmd = 'var-show-attributes ' + id; return this.getCommandOutput(cmd, null, (output: any) => { if (output.status) { // LLDB-MI return [stringToWatchAttributeMap.get(output.status)]; } else if (output.attr) { // GDB-MI if (Array.isArray(output.attr)) { return output.attr.map((attr: string) => { return stringToWatchAttributeMap.get(attr); }); } else { return [stringToWatchAttributeMap.get(output.attr)]; } } throw new MalformedResponseError( 'Expected to find "status" or "attr", found neither.', output, cmd ); }); } /** * Retrieves an expression that can be evaluated in the current context to obtain the watch value. * * @param id Identifier of the watch whose path expression should be retrieved. * @returns A promise that will be resolved with the path expression of the watch. */ getWatchExpression(id: string): Promise<string> { var cmd = 'var-info-path-expression ' + id; return this.getCommandOutput(cmd, null, (output: any) => { if (output.path_expr) { return output.path_expr; } throw new MalformedResponseError('Expected to find "path_expr".', output, cmd); }); } // // Data Inspection & Manipulation // /** * Evaluates the given expression within the target process and returns the result. * * The expression may contain function calls, which will be executed synchronously. * * @param expression The expression to evaluate. * @param options.threadId The thread within which the expression should be evaluated. * *Default*: the currently selected thread. * @param options.frameLevel The index of the stack frame within which the expression should * be evaluated, zero for the innermost stack frame. Note that * if `frameLevel` is specified then `threadId` must also be specified. * *Default*: the currently selected frame. * @returns A promise that will be resolved with the value of the expression. */ evaluateExpression( expression: string, options?: { threadId?: number; frameLevel?: number }): Promise<string> { var fullCmd = 'data-evaluate-expression'; if (options) { if (options.threadId !== undefined) { fullCmd = fullCmd + ' --thread ' + options.threadId; } if (options.frameLevel !== undefined) { fullCmd = fullCmd + ' --frame ' + options.frameLevel; } } fullCmd = fullCmd + ` "${expression}"`; return this.getCommandOutput(fullCmd, null, (output: any) => { if (output.value) { return output.value; } throw new MalformedResponseError('Expected to find "value".', output, fullCmd); }); } /** * Attempts to read all accessible memory regions in the given range. * * @param address Start of the range from which memory should be read, this can be a literal * address (e.g. `0x00007fffffffed30`) or an expression (e.g. `&someBuffer`) that * evaluates to the desired address. * @param numBytesToRead Number of bytes that should be read. * @param options.byteOffset Offset in bytes relative to `address` from which to begin reading. * @returns A promise that will be resolved with a list of memory blocks that were read. */ readMemory(address: string, numBytesToRead: number, options?: { byteOffset?: number }) : Promise<IMemoryBlock[]> { var fullCmd = 'data-read-memory-bytes'; if (options && options.byteOffset) { fullCmd = fullCmd + ' -o ' + options.byteOffset; } fullCmd = fullCmd + ` "${address}" ${numBytesToRead}`; return this.getCommandOutput(fullCmd, null, (output: any) => { if (output.memory) { return output.memory; } throw new MalformedResponseError('Expected to find "memory".', output, fullCmd); }); } /** * Retrieves a list of register names for the current target. * * @param registers List of numbers corresponding to the register names to be retrieved. * If this argument is omitted all register names will be retrieved. * @returns A promise that will be resolved with a list of register names. */ getRegisterNames(registers?: number[]): Promise<string[]> { var fullCmd = 'data-list-register-names'; if (registers && (registers.length > 0)) { fullCmd = fullCmd + ' ' + registers.join(' '); } return this.getCommandOutput(fullCmd, null, (output: any) => { if (output['register-names']) { return output['register-names']; } throw new MalformedResponseError('Expected to find "register-names".', output, fullCmd); }); } /** * Retrieves the values of registers. * * @param formatSpec Specifies how the register values should be formatted. * @param options.registers Register numbers of the registers for which values should be retrieved. * If this option is omitted the values of all registers will be retrieved. * @param options.skipUnavailable *(GDB specific)* If `true` only values of available registers * will be retrieved. * @param options.threadId Identifier of the thread from which register values should be retrieved. * If this option is omitted it will default to the currently selected thread. * NOTE: This option is not currently supported by LLDB-MI. * @param options.frameLevel Index of the frame from which register values should be retrieved. * This is a zero-based index, zero corresponds to the innermost frame * on the stack. If this option is omitted it will default to the * currently selected frame. * NOTE: This option is not currently supported by LLDB-MI. * @returns A promise that will be resolved with a map of register numbers to register values. */ getRegisterValues( formatSpec: RegisterValueFormatSpec, options?: { registers?: number[]; skipUnavailable?: boolean; threadId?: number; frameLevel?: number } ): Promise<Map<number, string>> { var fullCmd = 'data-list-register-values'; if (options) { if (options.threadId !== undefined) { fullCmd = fullCmd + ' --thread ' + options.threadId; } if (options.frameLevel !== undefined) { fullCmd = fullCmd + ' --frame ' + options.frameLevel; } if (options.skipUnavailable) { fullCmd = fullCmd + ' --skip-unavailable'; } } fullCmd = fullCmd + ' ' + registerValueFormatSpecToCodeMap.get(formatSpec); if (options && options.registers && (options.registers.length > 0)) { fullCmd = fullCmd + ' ' + options.registers.join(' '); } return this.getCommandOutput(fullCmd, null, (output: any) => { var registers: { number: string; value: string }[] = output['register-values']; var registerMap = new Map<number, string>(); if (registers) { registers.forEach((register) => { registerMap.set(parseInt(register.number, 10), register.value); }); return registerMap; } throw new MalformedResponseError('Expected to find "register-values".', output, fullCmd); }); } /** * Retrieves assembly instructions within the specified address range. * * No source line information will be provided for the assembly instructions that are retrieved, * if such information is required [[disassembleAddressRangeByLine]] should be used instead. * * @param start Start of the address range to disassemble. GDB allows this to be an expression * that can be evaluated to obtain the address (e.g. $pc), however LLDB-MI only * accepts number literals (e.g. 0x4009cc). * @param end End of the address range to disassemble, same caveats apply as for `start`. * @param showOpcodes If `true` the raw opcode bytes will be retrieved for each instruction. * @returns A promise that will be resolved with a list of assembly instructions (and associated * meta-data). */ disassembleAddressRange(start: string, end: string, showOpcodes?: boolean) : Promise<IAsmInstruction[]> { var fullCmd = `data-disassemble -s ${start} -e ${end} -- ` + (showOpcodes ? '2' : '0'); return this.getCommandOutput(fullCmd, null, (output: any) => { if (output.asm_insns) { return extractAsmInstructions(output.asm_insns); } throw new MalformedResponseError('Expected to find "asm_insns".', output, fullCmd); }); } /** * Retrieves assembly instructions within a specified address range grouped by source line. * * If source line information is not required [[disassembleAddressRange]] should be used instead. * * @param start Start of the address range to disassemble. GDB allows this to be an expression * that can be evaluated to obtain the address (e.g. $pc), however LLDB-MI only * accepts number literals (e.g. 0x4009cc). * @param end End of the address range to disassemble, same caveats apply as for `start`. * @param showOpcodes If `true` the raw opcode bytes will be retrieved for each instruction. * @returns A promise that will be resolved with a list lines, each of which will contain one * or more assembly instructions (and associated meta-data). */ disassembleAddressRangeByLine(start: string, end: string, showOpcodes?: boolean) : Promise<ISourceLineAsm[]> { var fullCmd = `data-disassemble -s ${start} -e ${end} -- ` + (showOpcodes ? '3' : '1'); return this.getCommandOutput(fullCmd, null, (output: any) => { if (output.asm_insns) { return extractAsmBySourceLine(output.asm_insns); } throw new MalformedResponseError('Expected to find "asm_insns".', output, fullCmd); }); } /** * Retrieves assembly instructions for the specified source file. * * No source line information will be provided for the assembly instructions that are retrieved, * if such information is required [[disassembleFileByLine]] should be used instead. * * @param filename Source file to disassemble, e.g. main.cpp * @param line Line number in `filename` to disassemble around. * @param options.maxInstructions Maximum number of assembly instructions to retrieve. * If this option is ommitted the entire function at the specified * source line will be disassembled. * @param options.showOpcodes If `true` the raw opcode bytes will be retrieved for each instruction. * @returns A promise that will be resolved with a list of assembly instructions (and associated * meta-data). */ disassembleFile( filename: string, line: number, options?: { maxInstructions?: number; showOpcodes?: boolean } ): Promise<IAsmInstruction[]> { var fullCmd = `data-disassemble -f ${filename} -l ${line}`; if (options && (options.maxInstructions !== undefined)) { fullCmd = fullCmd + ' -n ' + options.maxInstructions; } fullCmd = fullCmd + ' -- ' + ((options && options.showOpcodes) ? '2' : '0'); return this.getCommandOutput(fullCmd, null, (output: any) => { if (output.asm_insns) { return extractAsmInstructions(output.asm_insns); } throw new MalformedResponseError('Expected to find "asm_insns".', output, fullCmd); }); } /** * Retrieves assembly instructions for the specified source file grouped by source line. * * If source line information is not required [[disassembleFile]] should be used instead. * * @param filename Source file to disassemble, e.g. main.cpp * @param line Line number in `filename` to disassemble around. * @param options.maxInstructions Maximum number of assembly instructions to retrieve. * If this option is ommitted the entire function at the specified * source line will be disassembled. * @param options.showOpcodes If `true` the raw opcode bytes will be retrieved for each instruction. * @returns A promise that will be resolved with a list lines, each of which will contain one * or more assembly instructions (and associated meta-data). */ disassembleFileByLine( filename: string, line: number, options?: { maxInstructions?: number; showOpcodes?: boolean } ): Promise<ISourceLineAsm[]> { var fullCmd = `data-disassemble -f ${filename} -l ${line}`; if (options && (options.maxInstructions !== undefined)) { fullCmd = fullCmd + ' -n ' + options.maxInstructions; } fullCmd = fullCmd + ' -- ' + ((options && options.showOpcodes) ? '3' : '1'); return this.getCommandOutput(fullCmd, null, (output: any) => { if (output.asm_insns) { return extractAsmBySourceLine(output.asm_insns); } throw new MalformedResponseError('Expected to find "asm_insns".', output, fullCmd); }); } /** * Gets information about a thread in an inferior. * @returns A promise that will be resolved with information about a thread. */ getThread(threadId: number): Promise<IThreadInfo> { let fullCmd = 'thread-info ' + threadId; return this.getCommandOutput(fullCmd, null, (output: any) => { if (output.threads && (output.threads.length === 1)) { return extractThreadInfo(output.threads[0]); } throw new MalformedResponseError( 'Expected to find "threads" list with a single element.', output, fullCmd ); }); } /** * Gets information about all threads in all inferiors. * @returns A promise that will be resolved with information about all threads. */ getThreads(): Promise<IMultiThreadInfo> { let fullCmd = 'thread-info'; return this.getCommandOutput(fullCmd, null, (output: any) => { let currentThreadId: number = parseInt(output['current-thread-id'], 10); if (Array.isArray(output.threads)) { let currentThread: IThreadInfo; let threads: IThreadInfo[] = output.threads.map((data: any) => { let thread: IThreadInfo = extractThreadInfo(data); if (thread.id === currentThreadId) { currentThread = thread; } return thread; }); return { all: threads, current: currentThread }; } throw new MalformedResponseError('Expected to find "threads" list.', output, fullCmd); }); } //=== //JIN //global scope variables getGlobalVariables(): Promise<IVariableInfo[]> { let fullCmd: string = 'ta v -T -D1' return this.getCommandOutput(fullCmd, null, (output: any) => { if (output) {//FIXME output = output.slice(1, output.length) let current: any = rawCommandOuputParser.parse(`(0) 0 = { ${output.join("\n")} }`) return current[0].variables } else { return [] } }, true) } //stack frame variables getStackFrameVariables(threadId?: number, frameLevel?: number): Promise<IVariableInfo[]> { let fullCmd: string = 'fr v -T -D1' return this.getCommandOutput(fullCmd, null, (output: any) => { if (output) {//FIXME let current: any = rawCommandOuputParser.parse(`(0) 0 = { ${output.join("\n")} \n}`) return current[0].variables } else { return [] } }, true) } getVariableContent(variableName: string, threadId?: number, frameLevel?: number): Promise<IVariableInfo[]> { let fullCmd: string = 'fr v -T -D2 ' + variableName; return this.getCommandOutput(fullCmd, null, (output: any) => { if (output) {//FIXME let current: any = rawCommandOuputParser.parse(output.join("\n")) return current[0].variables } else { return [] } }, true); } } /** * Appends some common options used by -exec-* MI commands to the given string. * * @returns The result of appending the options to the input string. */ function appendExecCmdOptions( input: string, options: { threadId?: number; reverse?: boolean }): string { var cmd: string = input; if (options) { if (options.threadId !== undefined) { cmd = cmd + ' --thread ' + options.threadId; } if (options.reverse) { cmd = cmd + ' --reverse'; } } return cmd; } // maps WatchFormatSpec enum members to the corresponding MI string var watchFormatSpecToStringMap = new Map<WatchFormatSpec, string>() .set(WatchFormatSpec.Binary, 'binary') .set(WatchFormatSpec.Decimal, 'decimal') .set(WatchFormatSpec.Hexadecimal, 'hexadecimal') .set(WatchFormatSpec.Octal, 'octal') .set(WatchFormatSpec.Default, 'natural'); var stringToWatchAttributeMap = new Map<string, WatchAttribute>() .set('editable', WatchAttribute.Editable) .set('noneditable', WatchAttribute.NonEditable); // maps RegisterValueFormatSpec enum members to the corresponding MI code var registerValueFormatSpecToCodeMap = new Map<RegisterValueFormatSpec, string>() .set(RegisterValueFormatSpec.Binary, 't') .set(RegisterValueFormatSpec.Decimal, 'd') .set(RegisterValueFormatSpec.Hexadecimal, 'x') .set(RegisterValueFormatSpec.Octal, 'o') .set(RegisterValueFormatSpec.Raw, 'r') .set(RegisterValueFormatSpec.Default, 'N');
the_stack
import { JSDOM } from "jsdom" import * as WebSocket from "ws" const { window, window: { document, HTMLElement }, } = new JSDOM() Object.assign(global, { window, document, HTMLElement, WebSocket }) import * as http from "http" import * as net from "net" import Purview from "../src/purview" import AsyncQueue from "./async_queue" import { connectWebSocket } from "../src/client" import { SeenEventNamesMessage, EventMessage, ConnectMessage, UpdateMessage, ClientMessage, PNodeRegular, } from "../src/types/ws" import { virtualize, concretize } from "../src/helpers" test("connectWebSocket", async () => { document.body.innerHTML = ` <p data-root="true" data-component-id="foo">Paragraph</p> <div data-component-id="bar" /> <section><a data-root="true" data-component-id="baz"></a></section> ` await connect(async conn => { const message = (await conn.messages.next()) as ConnectMessage expect(message.type).toBe("connect") expect(message.rootIDs).toEqual(["foo", "baz"]) return conn }) }) test("connectWebSocket update", async () => { populate( <p data-root="true" data-component-id="foo"> This is a paragraph. </p>, ) await connect(async conn => { const updateMessage: UpdateMessage = { type: "update", componentID: "foo", pNode: virtualize( <div data-root="true" data-component-id="foo"> <a href="#">Link</a> </div>, ), newEventNames: [], } conn.ws.send(JSON.stringify(updateMessage)) await new Promise(resolve => { conn.wsClient.addEventListener("message", resolve) }) const div = document.querySelector('[data-component-id="foo"]') as Element expect(div.nodeName).toBe("DIV") expect(div.getAttribute("data-root")).toBe("true") const a = div.children[0] expect(a.nodeName).toBe("A") expect(a.getAttribute("href")).toBe("#") expect(a.textContent).toBe("Link") }) }) test("events", async () => { const pNode = populate( <p data-root="true" data-component-id="foo" data-click-capture="bar"> This is <a data-click="baz">a link</a>. </p>, ) await connect(async conn => { const message1 = (await conn.messages.next()) as ConnectMessage expect(message1.type).toBe("connect") expect(message1.rootIDs).toEqual(["foo"]) const updateMessage: UpdateMessage = { type: "update", componentID: "foo", pNode, newEventNames: ["click"], } conn.ws.send(JSON.stringify(updateMessage)) const message2 = (await conn.messages.next()) as SeenEventNamesMessage expect(message2.type).toBe("seenEventNames") expect(message2.seenEventNames).toEqual(["click"]) const event = new window.MouseEvent("click", { bubbles: true }) const a = document.body.querySelector("a") as Element a.dispatchEvent(event) // Capture event should be triggered first. const message3 = (await conn.messages.next()) as EventMessage expect(message3.type).toBe("event") expect(message3.rootID).toBe("foo") expect(message3.eventID).toBe("bar") const message4 = (await conn.messages.next()) as EventMessage expect(message4.type).toBe("event") expect(message4.rootID).toBe("foo") expect(message4.eventID).toBe("baz") }) }) test("events after update", async () => { populate( <p data-root="true" data-component-id="foo"> This is a paragraph. </p>, ) await connect(async conn => { const message1 = (await conn.messages.next()) as ConnectMessage expect(message1.type).toBe("connect") expect(message1.rootIDs).toEqual(["foo"]) const updateMessage: UpdateMessage = { type: "update", componentID: "foo", pNode: virtualize( <p data-root="true" data-component-id="foo" data-click-capture="bar"> <a href="#" data-click="baz"> Link </a> </p>, ), newEventNames: ["click"], } conn.ws.send(JSON.stringify(updateMessage)) const message2 = (await conn.messages.next()) as SeenEventNamesMessage expect(message2.type).toBe("seenEventNames") expect(message2.seenEventNames).toEqual(["click"]) const event = new window.MouseEvent("click", { bubbles: true }) const a = document.body.querySelector("a") as Element a.dispatchEvent(event) // Capture event should be triggered first. const message3 = (await conn.messages.next()) as EventMessage expect(message3.type).toBe("event") expect(message3.rootID).toBe("foo") expect(message3.eventID).toBe("bar") const message4 = (await conn.messages.next()) as EventMessage expect(message4.type).toBe("event") expect(message4.rootID).toBe("foo") expect(message4.eventID).toBe("baz") }) }) test("input/change event", async () => { const pNode = populate( <div data-root="true" data-component-id="foo"> <input type="text" name="text-input" data-input="bar" /> <input type="checkbox" data-input="baz" /> <select name="multi-select" multiple data-change="other"> <option>Foo</option> <option>Bar</option> <option>Baz</option> </select> </div>, ) await connect(async conn => { const updateMessage: UpdateMessage = { type: "update", componentID: "foo", pNode, newEventNames: ["input", "change"], } conn.ws.send(JSON.stringify(updateMessage)) // Ignore connect and seenEventNames messages. await conn.messages.next() await conn.messages.next() const event1 = new window.Event("input", { bubbles: true }) const input = document.body.querySelector("input") as HTMLInputElement input.value = "value" input.dispatchEvent(event1) // Capture event should be triggered first. const message1 = (await conn.messages.next()) as EventMessage expect(message1.type).toBe("event") expect(message1.rootID).toBe("foo") expect(message1.eventID).toBe("bar") expect(message1.event).toEqual({ name: "text-input", value: "value" }) const event2 = new window.Event("input", { bubbles: true }) const checkbox = document.body.querySelector( 'input[type="checkbox"]', ) as HTMLInputElement checkbox.checked = true checkbox.dispatchEvent(event2) // Capture event should be triggered first. const message2 = (await conn.messages.next()) as EventMessage expect(message2.type).toBe("event") expect(message2.rootID).toBe("foo") expect(message2.eventID).toBe("baz") expect(message2.event).toEqual({ name: "", value: true }) const event3 = new window.Event("change", { bubbles: true }) const select = document.body.querySelector("select") as HTMLSelectElement select.options[1].selected = true select.options[2].selected = true select.dispatchEvent(event3) const message3 = (await conn.messages.next()) as EventMessage expect(message3.type).toBe("event") expect(message3.rootID).toBe("foo") expect(message3.eventID).toBe("other") expect(message3.event).toEqual({ name: "multi-select", value: ["Bar", "Baz"], }) }) }) test("key event", async () => { const pNode = populate( <div data-root="true" data-component-id="foo"> <input type="text" name="text-input" data-keydown="bar" /> </div>, ) await connect(async conn => { const updateMessage: UpdateMessage = { type: "update", componentID: "foo", pNode, newEventNames: ["keydown"], } conn.ws.send(JSON.stringify(updateMessage)) // Ignore connect and seenEventNames messages. await conn.messages.next() await conn.messages.next() const key = "b" const event = new window.KeyboardEvent("keydown", { bubbles: true, key }) const input = document.body.querySelector("input") as HTMLInputElement input.dispatchEvent(event) // Capture event should be triggered first. const message = (await conn.messages.next()) as EventMessage expect(message.type).toBe("event") expect(message.rootID).toBe("foo") expect(message.eventID).toBe("bar") expect(message.event).toEqual({ name: "text-input", key }) }) }) test("submit event", async () => { const pNode = populate( <form data-root="true" data-component-id="foo" data-submit="bar"> <input name="input" value="input-value" /> <input name="input-disabled" disabled /> <input type="checkbox" name="checkbox" /> <input type="checkbox" /> <input type="radio" name="radio" value="radio-value1" /> <input type="radio" name="radio" value="radio-value2" checked /> <input type="radio" name="radio" value="radio-value3" /> <input type="number" name="number" value="17" /> <button name="button" value="button-value" /> <select name="select"> <option>select-value1</option> <option value="select-value2" selected> sv2 </option> </select> <select name="select-multiple" multiple> <option selected>select-value1</option> <option selected>select-value2</option> <option>select-value3</option> </select> <textarea name="textarea">textarea-value</textarea> </form>, ) await connect(async conn => { const updateMessage: UpdateMessage = { type: "update", componentID: "foo", pNode, newEventNames: ["submit"], } conn.ws.send(JSON.stringify(updateMessage)) // Ignore connect and seenEventNames messages. await conn.messages.next() await conn.messages.next() const event = new window.Event("submit", { bubbles: true }) const preventDefault = jest.fn() event.preventDefault = preventDefault const form = document.body.querySelector("form") as HTMLFormElement form.dispatchEvent(event) expect(preventDefault).toBeCalled() // Capture event should be triggered first. const message = (await conn.messages.next()) as EventMessage expect(message.type).toBe("event") expect(message.rootID).toBe("foo") expect(message.eventID).toBe("bar") expect(message.event).toEqual({ fields: { input: "input-value", checkbox: false, radio: "radio-value2", number: 17, button: "button-value", select: "select-value2", "select-multiple": ["select-value1", "select-value2"], textarea: "textarea-value", }, }) }) }) function populate(jsx: JSX.Element): PNodeRegular { const pNode = virtualize(jsx) const elem = concretize(pNode, document) document.body.innerHTML = "" document.body.appendChild(elem) return pNode } async function connect<T>( callback: ( conn: { ws: WebSocket wsClient: WebSocket messages: AsyncQueue<ClientMessage> }, ) => Promise<T>, ): Promise<T> { const server = http.createServer() await new Promise(resolve => server.listen(resolve)) const addr = server.address() as net.AddressInfo const wsServer = new WebSocket.Server({ server }) const messages = new AsyncQueue<ClientMessage>() const wsConnPromise = new Promise((resolve: (ws: WebSocket) => void) => { wsServer.on("connection", ws => { ws.on("message", data => messages.push(JSON.parse(data.toString()))) resolve(ws) }) }) const location: Location = { protocol: "http:", host: `localhost:${addr.port}`, pathname: "", search: "", } as any const wsClient: WebSocket = connectWebSocket(location) as any const wsConn = await wsConnPromise let result try { result = await callback({ ws: wsConn, wsClient, messages }) } finally { server.close() wsConn.close() } return result }
the_stack
import { browser, protractor, $} from 'protractor'; import { OverviewCompliance } from '../page-objects/overview.po'; import { PatchingCompliance } from '../page-objects/patching-compliance.po'; import { Login } from '../page-objects/login.po'; import { AssetDetails } from '../page-objects/asset-details.po'; import { AssetList } from '../page-objects/asset-list.po'; const timeOutHigh = 180000; describe('PatchingCompliance', () => { let OverviewCompliance_po: OverviewCompliance; let PatchingCompliance_po: PatchingCompliance; let Login_po: Login; let AssetDetails_po: AssetDetails; let AssetList_po: AssetList; const EC = protractor.ExpectedConditions; beforeAll(() => { OverviewCompliance_po = new OverviewCompliance(); PatchingCompliance_po = new PatchingCompliance(); AssetDetails_po = new AssetDetails(); AssetList_po = new AssetList(); Login_po = new Login(); }); it('Check title of page', () => { browser.wait(EC.visibilityOf( OverviewCompliance_po.getPatchingClick()), timeOutHigh); browser.wait(EC.elementToBeClickable( OverviewCompliance_po.getPatchingClick()), timeOutHigh); OverviewCompliance_po.getPatchingClick().click(); browser.wait(EC.visibilityOf(PatchingCompliance_po.getPatchingHeaderText()), timeOutHigh); expect(PatchingCompliance_po.getPatchingHeaderText().getText()).toContain('Patching'); }); it('Verify list table filter search', () => { browser.wait(EC.visibilityOf(PatchingCompliance_po.getTableTotal()), timeOutHigh); browser.wait(EC.visibilityOf(PatchingCompliance_po.getSearchLabel()), timeOutHigh); browser.wait(EC.elementToBeClickable(PatchingCompliance_po.getSearchLabel()), timeOutHigh); PatchingCompliance_po.getSearchLabel().click(); browser.sleep(201); PatchingCompliance_po.getSearchInput().sendKeys('dev'); browser.actions().sendKeys(protractor.Key.ENTER).perform(); browser.sleep(201); browser.wait(EC.visibilityOf(PatchingCompliance_po.getTableTotal()), timeOutHigh); PatchingCompliance_po.getFirstRowCell().getText().then(function(text) { expect(text.toLowerCase()).toContain('dev'); browser.sleep(401); PatchingCompliance_po.getSearchInput().sendKeys(''); }); }); it('Check table sort functionality', () => { browser.wait(EC.visibilityOf(PatchingCompliance_po.getTableTotal()), timeOutHigh); PatchingCompliance_po.getTableSort().click(); let first_row; PatchingCompliance_po.getFirstRowCell().getText().then(function(text) { first_row = text.toLowerCase(); }); let second_row; PatchingCompliance_po.getSecondRowCell().getText().then(function(text) { second_row = text.toLowerCase(); expect(first_row < second_row).toEqual(true); }); }); it('Check table additional details functionality', () => { browser.wait(EC.visibilityOf( PatchingCompliance_po.getTableTotal()), timeOutHigh); browser.wait(EC.visibilityOf( PatchingCompliance_po.getFirstRowCell()), timeOutHigh); browser.wait(EC.elementToBeClickable( PatchingCompliance_po.getFirstRowCell()), timeOutHigh); PatchingCompliance_po.getFirstRowCell().click(); browser.wait(EC.visibilityOf( PatchingCompliance_po.additionalDetailsTxt()), timeOutHigh); expect(PatchingCompliance_po.additionalDetailsTxt().getText()).toEqual('Additional Details'); browser.wait(EC.visibilityOf( PatchingCompliance_po.additionalDetailsClose()), timeOutHigh); browser.wait(EC.elementToBeClickable( PatchingCompliance_po.additionalDetailsClose()), timeOutHigh); PatchingCompliance_po.additionalDetailsClose().click(); }); it('verify csv download', () => { let download_successful = false; browser.wait(EC.visibilityOf( PatchingCompliance_po.getTableTotal()), timeOutHigh); const filename = process.cwd() + '/e2e/downloads/Patching Compliance Details.csv'; const fs = require('fs'); const myDir = process.cwd() + '/e2e/downloads'; if (!PatchingCompliance_po.checkDirExists(myDir)) { fs.mkdirSync(myDir); } else if ((fs.readdirSync(myDir).length) > 0 && fs.existsSync(filename)) { fs.unlinkSync(filename); } browser.wait(EC.visibilityOf(PatchingCompliance_po.getdownloadIcon()), timeOutHigh); browser.wait(EC.elementToBeClickable(PatchingCompliance_po.getdownloadIcon()), timeOutHigh); PatchingCompliance_po.getdownloadIcon().click(); browser.wait(EC.visibilityOf(PatchingCompliance_po.getToastMsg()), timeOutHigh).then(function() { browser.wait(EC.invisibilityOf(PatchingCompliance_po.getDownloadRunningIcon()), 600000).then(function() { browser.sleep(4000); browser.driver.wait(function() { if (fs.existsSync(filename)) { download_successful = true; const fileContent = fs.readFileSync(filename, { encoding: 'utf8' }); expect(fileContent.toString().indexOf('\n')).toBeGreaterThan(0); } expect(download_successful).toEqual(true); return fs.existsSync(filename); }, timeOutHigh); }); }); }); it('Verify redirect to asset details clicking resourceId', () => { browser.wait(EC.visibilityOf( PatchingCompliance_po.getResourceId()), timeOutHigh); browser.wait(EC.elementToBeClickable( PatchingCompliance_po.getResourceId()), timeOutHigh); PatchingCompliance_po.getResourceId().click(); browser.wait(EC.visibilityOf(AssetDetails_po.getAssetHeaderText()), timeOutHigh); expect(AssetDetails_po.getAssetHeaderText().getText()).toEqual('Asset Details'); browser.sleep(401); browser.wait(EC.elementToBeClickable(AssetDetails_po.getBackArrow()), timeOutHigh); AssetDetails_po.getBackArrow().click(); }); it('Verify total patched and scan %', () => { browser.wait(EC.visibilityOf( PatchingCompliance_po.getPatchedAssets()), timeOutHigh); browser.wait(EC.visibilityOf( PatchingCompliance_po.getTotalAssets()), timeOutHigh); browser.wait(EC.visibilityOf( PatchingCompliance_po.getUnPatchedAssets()), timeOutHigh); browser.wait(EC.visibilityOf( PatchingCompliance_po.getPatchedPercent()), timeOutHigh); browser.wait(EC.visibilityOf( PatchingCompliance_po.getTableTotal()), timeOutHigh); let total; let patched; let unpatched; let percent; let table_total; PatchingCompliance_po.getPatchedAssets().getText().then(function(text) { patched = parseInt(text.replace(/,/g, ''), 10); }); PatchingCompliance_po.getTotalAssets().getText().then(function(text) { total = parseInt(text.replace(/,/g, ''), 10); }); PatchingCompliance_po.getUnPatchedAssets().getText().then(function(text) { unpatched = parseInt(text.replace(/,/g, ''), 10); }); PatchingCompliance_po.getTableTotal().getText().then(function(text) { table_total = parseInt(text.replace(/,/g, ''), 10); }); PatchingCompliance_po.getPatchedPercent().getText().then(function(text) { percent = parseInt(text.replace(/,/g, ''), 10); expect(total).toEqual(unpatched + patched); expect(total).toEqual(table_total); expect(Math.floor((patched * 100) / total)).toEqual(percent); let is_percent = false; if ( percent <= 100 && percent >= 0 ) { is_percent = true; } expect(is_percent).toEqual(true); browser.wait(EC.visibilityOf(PatchingCompliance_po.clickQuarters()), timeOutHigh); PatchingCompliance_po.getLatestWeek().then(function(items){ const latest_week = items.length; const latest_percent = $('.percent-wrap .x-percent:nth-child(' + latest_week + ')').getText().then(function(subtext) { expect(percent).toEqual(parseInt(subtext, 10)); }); }); }); }); it('Verify help text modal is opening', () => { browser.wait(EC.visibilityOf( PatchingCompliance_po.openHelp()), timeOutHigh); browser.wait(EC.elementToBeClickable( PatchingCompliance_po.openHelp()), timeOutHigh); PatchingCompliance_po.openHelp().click(); browser.wait(EC.visibilityOf( PatchingCompliance_po.getHelpTitle()), timeOutHigh); const help_title = PatchingCompliance_po.getHelpTitle().getText(); expect(help_title).toEqual('Help'); $('.help-text-modal .close-popup').click(); }); it('Check quarter details match summary', () => { let percent; let patched; let unpatched; browser.wait(EC.visibilityOf( PatchingCompliance_po.getPatchedAssets()), timeOutHigh); PatchingCompliance_po.getPatchedAssets().getText().then(function(text) { patched = parseInt(text.replace(/,/g, ''), 10); }); PatchingCompliance_po.getPatchedPercent().getText().then(function(text) { percent = parseInt(text.replace(/,/g, ''), 10); }); PatchingCompliance_po.getUnPatchedAssets().getText().then(function(text) { unpatched = parseInt(text.replace(/,/g, ''), 10); }); browser.wait(EC.visibilityOf( PatchingCompliance_po.clickQuarters()), timeOutHigh); browser.wait(EC.elementToBeClickable( PatchingCompliance_po.clickQuarters()), timeOutHigh); PatchingCompliance_po.clickQuarters().click(); PatchingCompliance_po.getQuarters().then(function(items) { const i = items.length; let q_percent; let q_patched; let q_unpatched; $('ul.patching-quarter-wrapper .li-container .patching-each-quarter:nth-child(' + i + ') .patching-each-quarter-desc .stats-wrap .pp-stats:nth-child(1) .pp-stats-txt').getText().then(function(text) { q_percent = parseInt(text.replace(/,/g, ''), 10); }); $('ul.patching-quarter-wrapper .li-container .patching-each-quarter:nth-child(' + i + ') .patching-each-quarter-desc .stats-wrap .pp-stats:nth-child(2) .pp-stats-txt').getText().then(function(text) { q_patched = parseInt(text.replace(/,/g, ''), 10); }); $('ul.patching-quarter-wrapper .li-container .patching-each-quarter:nth-child(' + i + ') .patching-each-quarter-desc .stats-wrap .pp-stats:nth-child(3) .pp-stats-txt').getText().then(function(text) { q_unpatched = parseInt(text.replace(/,/g, ''), 10); expect(q_percent).toEqual(percent); expect(q_patched).toEqual(patched); expect(q_unpatched).toEqual(unpatched); browser.wait(EC.visibilityOf( PatchingCompliance_po.closeQuarters()), timeOutHigh); browser.wait(EC.elementToBeClickable( PatchingCompliance_po.closeQuarters()), timeOutHigh); PatchingCompliance_po.closeQuarters().click(); }); }); }); it('Check view current quarter details', () => { browser.wait(EC.visibilityOf(PatchingCompliance_po.viewCurrentQuarter()), timeOutHigh); browser.wait(EC.elementToBeClickable(PatchingCompliance_po.viewCurrentQuarter()), timeOutHigh); PatchingCompliance_po.viewCurrentQuarter().click(); browser.wait(EC.visibilityOf(PatchingCompliance_po.clickQuarters()), timeOutHigh); browser.wait(EC.visibilityOf(PatchingCompliance_po.getPatchedPercent()), timeOutHigh); let percent; PatchingCompliance_po.getPatchedPercent().getText().then(function(text) { percent = parseInt(text.replace(/,/g, ''), 10); }); PatchingCompliance_po.getLatestWeek().then(function(items){ const latest_week = items.length; const latest_percent = $('.percent-wrap .x-percent:nth-child(' + latest_week + ')').getText().then(function(subtext) { expect(percent).toEqual(parseInt(subtext, 10)); }); }); }); it('Check redirect to asset list page with matching count', () => { browser.wait(EC.visibilityOf(PatchingCompliance_po.getTotalAssets()), timeOutHigh); browser.wait(EC.elementToBeClickable(PatchingCompliance_po.getTotalAssets()), timeOutHigh); let total; PatchingCompliance_po.getTotalAssets().getText().then(function(text) { total = parseInt(text.replace(/,/g, ''), 10); }); PatchingCompliance_po.getTotalAssets().click(); browser.wait(EC.visibilityOf(AssetList_po.getAssetHeaderText()), timeOutHigh); expect(AssetList_po.getAssetHeaderText().getText()).toEqual('Asset List'); browser.wait(EC.visibilityOf(AssetList_po.getAssetTotalRows()), timeOutHigh); AssetList_po.getAssetTotalRows().getText().then(function(text) { expect(parseInt(text.replace(/,/g, ''), 10)).toEqual(total); browser.wait(EC.visibilityOf(AssetList_po.getBackArrow()), timeOutHigh); browser.wait(EC.elementToBeClickable(AssetList_po.getBackArrow()), timeOutHigh); AssetList_po.getBackArrow().click(); }); }); it('Check redirect to asset list page with filter passed', () => { browser.wait(EC.visibilityOf(PatchingCompliance_po.getTopDirector()), timeOutHigh); browser.wait(EC.elementToBeClickable(PatchingCompliance_po.getTopDirector()), timeOutHigh); browser.wait(EC.visibilityOf(PatchingCompliance_po.getDirectorAppl()), timeOutHigh); let total; let appl_name; PatchingCompliance_po.getDirectorAppl().getText().then(function(text) { appl_name = text; }); PatchingCompliance_po.getTopDirector().getText().then(function(text) { total = parseInt(text.replace(/,/g, ''), 10); }); PatchingCompliance_po.getTopDirector().click(); browser.wait(EC.visibilityOf(AssetList_po.getAssetHeaderText()), timeOutHigh); expect(AssetList_po.getAssetHeaderText().getText()).toEqual('Asset List'); browser.wait(EC.visibilityOf(AssetList_po.getAssetTotalRows()), timeOutHigh); AssetList_po.getAssetTotalRows().getText().then(function(text) { expect(parseInt(text.replace(/,/g, ''), 10)).toEqual(total); browser.wait(EC.visibilityOf(AssetList_po.getFirstFilter()), timeOutHigh); AssetList_po.getAllFilters().then(function(items) { for ( let i = 1; i <= items.length; i++) { $('.floating-widgets-filter-wrapper .each-filter:nth-child(' + i + ')').getText().then(function(subtext) { if (subtext.toLowerCase().match(appl_name.toLowerCase())) { expect(subtext.toLowerCase()).toContain(appl_name.toLowerCase()); } }); } }); browser.wait(EC.visibilityOf(AssetList_po.getBackArrow()), timeOutHigh); browser.wait(EC.elementToBeClickable(AssetList_po.getBackArrow()), timeOutHigh); AssetList_po.getBackArrow().click(); }); }); });
the_stack
module android.widget { import Gravity = android.view.Gravity; import View = android.view.View; import ViewGroup = android.view.ViewGroup; import Drawable = android.graphics.drawable.Drawable; import Rect = android.graphics.Rect; import Canvas = android.graphics.Canvas; import AttrBinder = androidui.attr.AttrBinder; import Context = android.content.Context; /** * FrameLayout is designed to block out an area on the screen to display * a single item. Generally, FrameLayout should be used to hold a single child view, because it can * be difficult to organize child views in a way that's scalable to different screen sizes without * the children overlapping each other. You can, however, add multiple children to a FrameLayout * and control their position within the FrameLayout by assigning gravity to each child, using the * <a href="FrameLayout.LayoutParams.html#attr_android:layout_gravity">{@code * android:layout_gravity}</a> attribute. * <p>Child views are drawn in a stack, with the most recently added child on top. * The size of the FrameLayout is the size of its largest child (plus padding), visible * or not (if the FrameLayout's parent permits). Views that are {@link android.view.View#GONE} are * used for sizing * only if {@link #setMeasureAllChildren(boolean) setConsiderGoneChildrenWhenMeasuring()} * is set to true. * * @attr ref android.R.styleable#FrameLayout_foreground * @attr ref android.R.styleable#FrameLayout_foregroundGravity * @attr ref android.R.styleable#FrameLayout_measureAllChildren */ export class FrameLayout extends ViewGroup { static DEFAULT_CHILD_GRAVITY = Gravity.TOP | Gravity.LEFT; mMeasureAllChildren = false; mForeground:Drawable; private mForegroundPaddingLeft = 0; private mForegroundPaddingTop = 0; private mForegroundPaddingRight = 0; private mForegroundPaddingBottom = 0; private mSelfBounds = new Rect(); private mOverlayBounds = new Rect(); private mForegroundGravity = Gravity.FILL; mForegroundInPadding = true; mForegroundBoundsChanged = false; private mMatchParentChildren = new Array<View>(1); constructor(context:android.content.Context, bindElement?:HTMLElement, defStyle?:Map<string, string>) { super(context, bindElement, defStyle); const a = context.obtainStyledAttributes(bindElement, defStyle); this.mForegroundGravity = Gravity.parseGravity(a.getAttrValue('foregroundGravity'), this.mForegroundGravity); const d = a.getDrawable('foreground'); if (d != null) { this.setForeground(d); } if (a.getBoolean('measureAllChildren', false)) { this.setMeasureAllChildren(true); } this.mForegroundInPadding = a.getBoolean('foregroundInsidePadding', true); a.recycle(); } protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap { return super.createClassAttrBinder().set('foregroundGravity', { setter(v:FrameLayout, value:any, attrBinder:AttrBinder) { v.mForegroundGravity = attrBinder.parseGravity(value, v.mForegroundGravity); }, getter(v:FrameLayout) { return v.mForegroundGravity; } }).set('foreground', { setter(v:FrameLayout, value:any, attrBinder:AttrBinder) { v.setForeground(attrBinder.parseDrawable(value)); }, getter(v:FrameLayout) { return v.getForeground(); } }).set('measureAllChildren', { setter(v:FrameLayout, value:any, attrBinder:AttrBinder) { if (attrBinder.parseBoolean(value)) { v.setMeasureAllChildren(true); } }, getter(v:FrameLayout) { return v.mMeasureAllChildren; } }); } /** * Describes how the foreground is positioned. * * @return foreground gravity. * * @see #setForegroundGravity(int) * * @attr ref android.R.styleable#FrameLayout_foregroundGravity */ getForegroundGravity():number { return this.mForegroundGravity; } /** * Describes how the foreground is positioned. Defaults to START and TOP. * * @param foregroundGravity See {@link android.view.Gravity} * * @see #getForegroundGravity() * * @attr ref android.R.styleable#FrameLayout_foregroundGravity */ setForegroundGravity(foregroundGravity:number) { if (this.mForegroundGravity != foregroundGravity) { if ((foregroundGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == 0) { foregroundGravity |= Gravity.LEFT; } if ((foregroundGravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { foregroundGravity |= Gravity.TOP; } this.mForegroundGravity = foregroundGravity; if (this.mForegroundGravity == Gravity.FILL && this.mForeground != null) { let padding = new Rect(); if (this.mForeground.getPadding(padding)) { this.mForegroundPaddingLeft = padding.left; this.mForegroundPaddingTop = padding.top; this.mForegroundPaddingRight = padding.right; this.mForegroundPaddingBottom = padding.bottom; } } else { this.mForegroundPaddingLeft = 0; this.mForegroundPaddingTop = 0; this.mForegroundPaddingRight = 0; this.mForegroundPaddingBottom = 0; } this.requestLayout(); } } protected verifyDrawable(who:Drawable):boolean { return super.verifyDrawable(who) || (who == this.mForeground); } jumpDrawablesToCurrentState() { super.jumpDrawablesToCurrentState(); if (this.mForeground != null) this.mForeground.jumpToCurrentState(); } protected drawableStateChanged() { super.drawableStateChanged(); if (this.mForeground != null && this.mForeground.isStateful()) { this.mForeground.setState(this.getDrawableState()); } } /** * Returns a set of layout parameters with a width of * {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT}, * and a height of {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT}. */ protected generateDefaultLayoutParams():FrameLayout.LayoutParams { return new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT); } /** * Supply a Drawable that is to be rendered on top of all of the child * views in the frame layout. Any padding in the Drawable will be taken * into account by ensuring that the children are inset to be placed * inside of the padding area. * * @param drawable The Drawable to be drawn on top of the children. * * @attr ref android.R.styleable#FrameLayout_foreground */ setForeground(drawable:Drawable) { if (this.mForeground != drawable) { if (this.mForeground != null) { this.mForeground.setCallback(null); this.unscheduleDrawable(this.mForeground); } this.mForeground = drawable; this.mForegroundPaddingLeft = 0; this.mForegroundPaddingTop = 0; this.mForegroundPaddingRight = 0; this.mForegroundPaddingBottom = 0; if (drawable != null) { this.setWillNotDraw(false); drawable.setCallback(this); if (drawable.isStateful()) { drawable.setState(this.getDrawableState()); } if (this.mForegroundGravity == Gravity.FILL) { let padding = new Rect(); if (drawable.getPadding(padding)) { this.mForegroundPaddingLeft = padding.left; this.mForegroundPaddingTop = padding.top; this.mForegroundPaddingRight = padding.right; this.mForegroundPaddingBottom = padding.bottom; } } } else { this.setWillNotDraw(true); } this.requestLayout(); this.invalidate(); } } /** * Returns the drawable used as the foreground of this FrameLayout. The * foreground drawable, if non-null, is always drawn on top of the children. * * @return A Drawable or null if no foreground was set. */ getForeground():Drawable { return this.mForeground; } getPaddingLeftWithForeground():number { return this.mForegroundInPadding ? Math.max(this.mPaddingLeft, this.mForegroundPaddingLeft) : this.mPaddingLeft + this.mForegroundPaddingLeft; } getPaddingRightWithForeground():number { return this.mForegroundInPadding ? Math.max(this.mPaddingRight, this.mForegroundPaddingRight) : this.mPaddingRight + this.mForegroundPaddingRight; } getPaddingTopWithForeground():number { return this.mForegroundInPadding ? Math.max(this.mPaddingTop, this.mForegroundPaddingTop) : this.mPaddingTop + this.mForegroundPaddingTop; } getPaddingBottomWithForeground() { return this.mForegroundInPadding ? Math.max(this.mPaddingBottom, this.mForegroundPaddingBottom) : this.mPaddingBottom + this.mForegroundPaddingBottom; } protected onMeasure(widthMeasureSpec:number, heightMeasureSpec:number) { let count = this.getChildCount(); let measureMatchParentChildren = View.MeasureSpec.getMode(widthMeasureSpec) != View.MeasureSpec.EXACTLY || View.MeasureSpec.getMode(heightMeasureSpec) != View.MeasureSpec.EXACTLY; this.mMatchParentChildren = []; let maxHeight = 0; let maxWidth = 0; let childState = 0; for (let i = 0; i < count; i++) { let child = this.getChildAt(i); if (this.mMeasureAllChildren || child.getVisibility() != View.GONE) { this.measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0); let lp = <FrameLayout.LayoutParams> child.getLayoutParams(); maxWidth = Math.max(maxWidth, child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin); maxHeight = Math.max(maxHeight, child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin); childState = View.combineMeasuredStates(childState, child.getMeasuredState()); if (measureMatchParentChildren) { if (lp.width == FrameLayout.LayoutParams.MATCH_PARENT || lp.height == FrameLayout.LayoutParams.MATCH_PARENT) { this.mMatchParentChildren.push(child); } } } } // Account for padding too maxWidth += this.getPaddingLeftWithForeground() + this.getPaddingRightWithForeground(); maxHeight += this.getPaddingTopWithForeground() + this.getPaddingBottomWithForeground(); // Check against our minimum height and width maxHeight = Math.max(maxHeight, this.getSuggestedMinimumHeight()); maxWidth = Math.max(maxWidth, this.getSuggestedMinimumWidth()); // Check against our foreground's minimum height and width let drawable = this.getForeground(); if (drawable != null) { maxHeight = Math.max(maxHeight, drawable.getMinimumHeight()); maxWidth = Math.max(maxWidth, drawable.getMinimumWidth()); } this.setMeasuredDimension(View.resolveSizeAndState(maxWidth, widthMeasureSpec, childState), View.resolveSizeAndState(maxHeight, heightMeasureSpec, childState << View.MEASURED_HEIGHT_STATE_SHIFT)); count = this.mMatchParentChildren.length; if (count > 1) { for (let i = 0; i < count; i++) { let child = this.mMatchParentChildren[i]; let lp = <ViewGroup.MarginLayoutParams> child.getLayoutParams(); let childWidthMeasureSpec; let childHeightMeasureSpec; if (lp.width == FrameLayout.LayoutParams.MATCH_PARENT) { childWidthMeasureSpec = View.MeasureSpec.makeMeasureSpec(this.getMeasuredWidth() - this.getPaddingLeftWithForeground() - this.getPaddingRightWithForeground() - lp.leftMargin - lp.rightMargin, View.MeasureSpec.EXACTLY); } else { childWidthMeasureSpec = ViewGroup.getChildMeasureSpec(widthMeasureSpec, this.getPaddingLeftWithForeground() + this.getPaddingRightWithForeground() + lp.leftMargin + lp.rightMargin, lp.width); } if (lp.height == FrameLayout.LayoutParams.MATCH_PARENT) { childHeightMeasureSpec = View.MeasureSpec.makeMeasureSpec(this.getMeasuredHeight() - this.getPaddingTopWithForeground() - this.getPaddingBottomWithForeground() - lp.topMargin - lp.bottomMargin, View.MeasureSpec.EXACTLY); } else { childHeightMeasureSpec = ViewGroup.getChildMeasureSpec(heightMeasureSpec, this.getPaddingTopWithForeground() + this.getPaddingBottomWithForeground() + lp.topMargin + lp.bottomMargin, lp.height); } child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } } } protected onLayout(changed:boolean, left:number, top:number, right:number, bottom:number):void { this.layoutChildren(left, top, right, bottom, false /* no force left gravity */); } layoutChildren(left:number, top:number, right:number, bottom:number, forceLeftGravity:boolean):void { const count = this.getChildCount(); const parentLeft = this.getPaddingLeftWithForeground(); const parentRight = right - left - this.getPaddingRightWithForeground(); const parentTop = this.getPaddingTopWithForeground(); const parentBottom = bottom - top - this.getPaddingBottomWithForeground(); this.mForegroundBoundsChanged = true; for (let i = 0; i < count; i++) { let child = this.getChildAt(i); if (child.getVisibility() != View.GONE) { const lp = <FrameLayout.LayoutParams> child.getLayoutParams(); const width = child.getMeasuredWidth(); const height = child.getMeasuredHeight(); let childLeft; let childTop; let gravity = lp.gravity; if (gravity == -1) { gravity = FrameLayout.DEFAULT_CHILD_GRAVITY; } //const layoutDirection = getLayoutDirection(); const absoluteGravity = gravity;//Gravity.getAbsoluteGravity(gravity, layoutDirection); const verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK; switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { case Gravity.CENTER_HORIZONTAL: childLeft = parentLeft + (parentRight - parentLeft - width) / 2 + lp.leftMargin - lp.rightMargin; break; case Gravity.RIGHT: if (!forceLeftGravity) { childLeft = parentRight - width - lp.rightMargin; break; } case Gravity.LEFT: default: childLeft = parentLeft + lp.leftMargin; } switch (verticalGravity) { case Gravity.TOP: childTop = parentTop + lp.topMargin; break; case Gravity.CENTER_VERTICAL: childTop = parentTop + (parentBottom - parentTop - height) / 2 + lp.topMargin - lp.bottomMargin; break; case Gravity.BOTTOM: childTop = parentBottom - height - lp.bottomMargin; break; default: childTop = parentTop + lp.topMargin; } child.layout(childLeft, childTop, childLeft + width, childTop + height); } } } protected onSizeChanged(w:number, h:number, oldw:number, oldh:number):void { super.onSizeChanged(w, h, oldw, oldh); this.mForegroundBoundsChanged = true; } draw(canvas:Canvas){ super.draw(canvas); if (this.mForeground != null) { const foreground = this.mForeground; if (this.mForegroundBoundsChanged) { this.mForegroundBoundsChanged = false; const selfBounds = this.mSelfBounds; const overlayBounds = this.mOverlayBounds; const w = this.mRight - this.mLeft; const h = this.mBottom - this.mTop; if (this.mForegroundInPadding) { selfBounds.set(0, 0, w, h); } else { selfBounds.set(this.mPaddingLeft, this.mPaddingTop, w - this.mPaddingRight, h - this.mPaddingBottom); } //const layoutDirection = this.getLayoutDirection(); Gravity.apply(this.mForegroundGravity, foreground.getIntrinsicWidth(), foreground.getIntrinsicHeight(), selfBounds, overlayBounds); foreground.setBounds(overlayBounds); } foreground.draw(canvas); } } /** * Sets whether to consider all children, or just those in * the VISIBLE or INVISIBLE state, when measuring. Defaults to false. * * @param measureAll true to consider children marked GONE, false otherwise. * Default value is false. * * @attr ref android.R.styleable#FrameLayout_measureAllChildren */ setMeasureAllChildren( measureAll:boolean) { this.mMeasureAllChildren = measureAll; } /** * Determines whether all children, or just those in the VISIBLE or * INVISIBLE state, are considered when measuring. * * @return Whether all children are considered when measuring. */ getMeasureAllChildren() { return this.mMeasureAllChildren; } public generateLayoutParamsFromAttr(attrs: HTMLElement): android.view.ViewGroup.LayoutParams { return new FrameLayout.LayoutParams(this.getContext(), attrs); } shouldDelayChildPressedState():boolean { return false; } protected checkLayoutParams(p:ViewGroup.LayoutParams){ return p instanceof FrameLayout.LayoutParams; } protected generateLayoutParams(p:ViewGroup.LayoutParams){ return new FrameLayout.LayoutParams(p); } } export module FrameLayout { /** * Per-child layout information for layouts that support margins. * See {@link android.R.styleable#FrameLayout_Layout FrameLayout Layout Attributes} * for a list of all child view attributes that this class supports. * * @attr ref android.R.styleable#FrameLayout_Layout_layout_gravity */ export class LayoutParams extends ViewGroup.MarginLayoutParams { /** * The gravity to apply with the View to which these layout parameters * are associated. * * @see android.view.Gravity * * @attr ref android.R.styleable#FrameLayout_Layout_layout_gravity */ gravity = -1; constructor(context:Context, attrs:HTMLElement); constructor(); /** * Copy constructor. Clones the width, height, margin values, and * gravity of the source. * * @param source The layout params to copy from. */ constructor(source:ViewGroup.LayoutParams); /** * Creates a new set of layout parameters with the specified width, height * and weight. * * @param width the width, either {@link #MATCH_PARENT}, * {@link #WRAP_CONTENT} or a fixed size in pixels * @param height the height, either {@link #MATCH_PARENT}, * {@link #WRAP_CONTENT} or a fixed size in pixels * @param gravity the gravity * * @see android.view.Gravity */ constructor(width:number, height:number, gravity?:number); constructor(...args) { super(...(() => { if (args[0] instanceof android.content.Context && args[1] instanceof HTMLElement) return [args[0], args[1]]; else if (typeof args[0] === 'number' && typeof args[1] === 'number' && typeof args[2] === 'number') return [args[0], args[1]]; else if (typeof args[0] === 'number' && typeof args[1] === 'number') return [args[0], args[1]]; else if (args[0] instanceof ViewGroup.LayoutParams) return [args[0]]; })()); if (args[0] instanceof Context && args[1] instanceof HTMLElement) { const c = <Context>args[0]; const attrs = <HTMLElement>args[1]; const a = c.obtainStyledAttributes(attrs); this.gravity = Gravity.parseGravity(a.getAttrValue('layout_gravity'), -1); a.recycle(); } else if (typeof args[0] === 'number' && typeof args[1] === 'number' && typeof args[2] === 'number') { this.gravity = args[2]; } else if (typeof args[0] === 'number' && typeof args[1] === 'number') { } else if (args[0] instanceof FrameLayout.LayoutParams) { const source = <FrameLayout.LayoutParams>args[0]; this.gravity = source.gravity; } else if (args[0] instanceof ViewGroup.MarginLayoutParams) { } else if (args[0] instanceof ViewGroup.LayoutParams) { } } protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap { return super.createClassAttrBinder().set('layout_gravity', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { param.gravity = attrBinder.parseGravity(value, param.gravity); }, getter(param:LayoutParams) { return param.gravity; } }); } } } }
the_stack
import {ActionGroup, Item} from '@react-spectrum/actiongroup'; import {Cell, Column, Row, TableBody, TableHeader, TableView} from '@react-spectrum/table'; import {Checkbox} from '@react-spectrum/checkbox'; import {classNames, useStyleProps} from '@react-spectrum/utils'; import {Flex} from '@react-spectrum/layout'; import {Link} from '@react-spectrum/link'; import {Meta, Story} from '@storybook/react'; import React, {useRef} from 'react'; import {SearchField} from '@react-spectrum/searchfield'; import styles from './index.css'; import {TextField} from '@react-spectrum/textfield'; import {useLandmark} from '../'; interface StoryProps {} const meta: Meta<StoryProps> = { title: 'Landmark', parameters: {providerSwitcher: {mainElement: false}} }; export default meta; const Template = (): Story<StoryProps> => (props) => <Example {...props} />; const NestedTemplate = (): Story<StoryProps> => (props) => <NestedExample {...props} />; const TableTemplate = (): Story<StoryProps> => (props) => <TableExample {...props} />; const ApplicationTemplate = (): Story<StoryProps> => (props) => <ApplicationExample {...props} />; const DuplicateRolesWithLabelsTemplate = (): Story<StoryProps> => (props) => <DuplicateRolesWithLabelsExample {...props} />; const DuplicateRolesWithNoLabelsTemplate = (): Story<StoryProps> => (props) => <DuplicateRolesNoLabelExample {...props} />; const DuplicateRolesWithSameLabelsTemplate = (): Story<StoryProps> => (props) => <DuplicateRolesWithSameLabelsExample {...props} />; const OneWithNoFocusableChildrenExampleTemplate = (): Story<StoryProps> => (props) => <OneWithNoFocusableChildrenExample {...props} />; const AllWithNoFocusableChildrenExampleTemplate = (): Story<StoryProps> => (props) => <AllWithNoFocusableChildrenExample {...props} />; function Main(props) { let ref = useRef(); let {styleProps} = useStyleProps(props); let {landmarkProps} = useLandmark({...props, role: 'main'}, ref); return <main aria-label="Danni's unicorn corral" ref={ref} {...props} {...landmarkProps} {...styleProps}>{props.children}</main>; } function Navigation(props) { let ref = useRef(); let {styleProps} = useStyleProps(props); let {landmarkProps} = useLandmark({...props, role: 'navigation'}, ref); return <nav aria-label="Rainbow lookout" ref={ref} {...props} {...landmarkProps} {...styleProps}>{props.children}</nav>; } function Region(props) { let ref = useRef(); let {styleProps} = useStyleProps(props); let {landmarkProps} = useLandmark({...props, role: 'region'}, ref); return <article aria-label="The greens" ref={ref} {...props} {...landmarkProps} {...styleProps}>{props.children}</article>; } function Search(props) { let ref = useRef(); let {styleProps} = useStyleProps(props); let {landmarkProps} = useLandmark({...props, role: 'search'}, ref); return ( <form aria-label="Magic seeing eye" ref={ref} {...props} {...landmarkProps} {...styleProps}> <SearchField label="Search" /> </form> ); } function Example() { return ( <div> <Navigation> <div>Navigation Landmark</div> <ul> <li><a href="/home">Home</a></li> <li><a href="/about">About</a></li> <li><a href="/contact">Contact</a></li> </ul> </Navigation> <Main> <div>Main Landmark</div> <TextField label="First Name" /> </Main> </div> ); } function DuplicateRolesWithLabelsExample() { return ( <div> <Navigation aria-label="First Nav"> <div>Navigation Landmark with 'First Nav' label</div> <ul> <li><a href="/home">Home</a></li> <li><a href="/about">About</a></li> <li><a href="/contact">Contact</a></li> </ul> </Navigation> <Navigation aria-label="Second Nav"> <div>Navigation Landmark with 'Second Nav' label</div> <ul> <li><a href="/home">Home</a></li> <li><a href="/about">About</a></li> <li><a href="/contact">Contact</a></li> </ul> </Navigation> <Main> <div>Main Landmark</div> <TextField label="First Name" /> </Main> </div> ); } function DuplicateRolesWithSameLabelsExample() { return ( <div> <Navigation aria-label="First Nav"> <div>Navigation Landmark with 'First Nav' label</div> <ul> <li><a href="/home">Home</a></li> <li><a href="/about">About</a></li> <li><a href="/contact">Contact</a></li> </ul> </Navigation> <Navigation aria-label="First Nav"> <div>Navigation Landmark with 'First Nav' label</div> <ul> <li><a href="/home">Home</a></li> <li><a href="/about">About</a></li> <li><a href="/contact">Contact</a></li> </ul> </Navigation> <Main> <div>Main Landmark</div> <TextField label="First Name" /> </Main> </div> ); } function DuplicateRolesNoLabelExample() { return ( <div> <Navigation aria-label={undefined}> <div>Navigation Landmark with no label</div> <ul> <li><a href="/home">Home</a></li> <li><a href="/about">About</a></li> <li><a href="/contact">Contact</a></li> </ul> </Navigation> <Navigation aria-label={undefined}> <div>Navigation Landmark with no label</div> <ul> <li><a href="/home">Home</a></li> <li><a href="/about">About</a></li> <li><a href="/contact">Contact</a></li> </ul> </Navigation> <Main aria-label={undefined}> <div>Main Landmark</div> <TextField label="First Name" /> </Main> </div> ); } function OneWithNoFocusableChildrenExample() { return ( <div> <TextField label="First Name" /> <Main> <div>Main Landmark</div> <div>No focusable children</div> </Main> <TextField label="First Name" /> </div> ); } function AllWithNoFocusableChildrenExample() { return ( <div> <Region> <div>Region Landmark</div> <div>No focusable children</div> </Region> <TextField label="First Name" /> <Main> <div>Main Landmark</div> <div>No focusable children</div> </Main> </div> ); } function NestedExample() { return ( <div> <Main> <div>Main Landmark</div> <TextField label="First Name" /> <Region> <div>Region Landmark inside Main</div> <Checkbox>Checkbox label</Checkbox> </Region> </Main> </div> ); } function TableExample() { return ( <div> <Navigation> <ActionGroup> <Item>One</Item> <Item>Two</Item> <Item>Three</Item> </ActionGroup> </Navigation> <Main> <TableView aria-label="Table"> <TableHeader> <Column key="foo" allowsSorting>Foo</Column> <Column key="bar" allowsSorting>Bar</Column> <Column key="baz">Baz</Column> </TableHeader> <TableBody> <Row> <Cell>Foo 1</Cell> <Cell>Bar 1</Cell> <Cell>Baz 1</Cell> </Row> <Row> <Cell>Foo 2</Cell> <Cell>Bar 2</Cell> <Cell>Baz 2</Cell> </Row> <Row> <Cell>Foo 3</Cell> <Cell>Bar 3</Cell> <Cell>Baz 3</Cell> </Row> </TableBody> </TableView> </Main> </div> ); } // ['main', 'region', 'search', 'navigation', 'form', 'banner', 'contentinfo', 'complementary'] function ApplicationExample() { return ( <div className={classNames(styles, 'application')}> <Region UNSAFE_className={classNames(styles, 'globalnav')}> <Flex justifyContent="space-between"> <Link><a href="//react-spectrum.com">React Spectrum</a></Link> <Search /> </Flex> </Region> <Navigation UNSAFE_className={classNames(styles, 'navigation')} aria-label="Site Nav"> <ActionGroup orientation="vertical"> <Item>One</Item> <Item>Two</Item> <Item>Three</Item> </ActionGroup> </Navigation> <Main UNSAFE_className={classNames(styles, 'main')}> <TableView aria-label="Table" justifySelf="stretch"> <TableHeader> <Column key="foo" allowsSorting>Foo</Column> <Column key="bar" allowsSorting>Bar</Column> <Column key="baz">Baz</Column> </TableHeader> <TableBody> <Row> <Cell>Foo 1</Cell> <Cell>Bar 1</Cell> <Cell>Baz 1</Cell> </Row> <Row> <Cell>Foo 2</Cell> <Cell>Bar 2</Cell> <Cell>Baz 2</Cell> </Row> <Row> <Cell>Foo 3</Cell> <Cell>Bar 3</Cell> <Cell>Baz 3</Cell> </Row> </TableBody> </TableView> </Main> <Navigation UNSAFE_className={classNames(styles, 'navigation-content')} aria-label="Content Nav"> <ActionGroup orientation="vertical"> <Item>One</Item> <Item>Two</Item> <Item>Three</Item> </ActionGroup> </Navigation> </div> ); } export const FlatLandmarks = Template().bind({}); FlatLandmarks.args = {}; export const NestedLandmarks = NestedTemplate().bind({}); NestedLandmarks.args = {}; export const TableLandmark = TableTemplate().bind({}); TableLandmark.args = {}; export const ApplicationWithLandmarks = ApplicationTemplate().bind({}); ApplicationWithLandmarks.args = {}; export const DuplicateRolesWithLabels = DuplicateRolesWithLabelsTemplate().bind({}); DuplicateRolesWithLabels.args = {}; export const DuplicateRolesWithNoLabels = DuplicateRolesWithNoLabelsTemplate().bind({}); DuplicateRolesWithNoLabels.args = {}; export const DuplicateRolesWithSameLabels = DuplicateRolesWithSameLabelsTemplate().bind({}); DuplicateRolesWithSameLabels.args = {}; export const OneWithNoFocusableChildren = OneWithNoFocusableChildrenExampleTemplate().bind({}); OneWithNoFocusableChildren.args = {}; export const AllWithNoFocusableChildren = AllWithNoFocusableChildrenExampleTemplate().bind({}); AllWithNoFocusableChildren.args = {};
the_stack
import { select } from 'd3-selection'; const emptyDescriptions = { 'vcl-access-title': 'This chart has no title provided.', 'vcl-access-subtitle': 'This chart has no subtitle provided.', 'vcl-access-long-description': '', // 'This chart has no long description provided.', 'vcl-access-context': '', 'vcl-access-executive-summary': '', // 'This chart has no executive summary provided.', 'vcl-access-purpose': '', // 'This chart has no information regarding its purpose provided.', 'vcl-access-statistics': '', // 'This chart has no statistical explanation provided.', 'vcl-access-layout': '', // 'This chart has no layout description provided.', 'vcl-access-xAxis': '', // 'This chart has no x axis.', 'vcl-access-yAxis': '', // 'this chart has no y axis.', 'vcl-access-notes': '', // 'No notes provided regarding the structure of the chart.', 'vcl-access-annotation': '', // 'This chart has no annotations.', 'vcl-access-annotation-title': '', // 'This chart displays an annotation with no title.', 'vcl-access-annotation-description': '', // 'This annotation has no description provided.' headings: '' }; export const initializeDescriptionRoot = ({ rootEle, title, chartTag, uniqueID, highestHeadingLevel, redraw, disableKeyNav }: { rootEle: any; title: string; chartTag: string; uniqueID: string; highestHeadingLevel?: any; redraw?: boolean; disableKeyNav?: boolean; }) => { let level1 = findTagLevel(highestHeadingLevel, 0); level1 = level1 === 'h1' ? 'h2' : level1; const level2 = findTagLevel(level1, 1); const level3 = findTagLevel(level1, 2); const level4 = findTagLevel(level1, 3); let instructionsWrapper = select(rootEle).select('.vcl-accessibility-instructions'); if (!instructionsWrapper.size() || redraw) { select(rootEle) .select('.vcl-main-title') .attr('aria-hidden', 'true'); select(rootEle) .select('.vcl-sub-title') .attr('aria-hidden', 'true'); if (!instructionsWrapper.size()) { instructionsWrapper = select(rootEle) .select('.o-layout') .insert('div', ':first-child') .attr('class', 'vcl-accessibility-instructions') .style('position', 'absolute') .style('width', '200px'); } else { instructionsWrapper.selectAll('*').remove(); } instructionsWrapper.append(level4).attr('class', 'screen-reader-info vcl-region-label'); // .on('focus', focusInstructions) // .on('blur', blurInstructions) // .attr('tabindex', 0); instructionsWrapper .append(level1) .attr('class', 'screen-reader-info vcl-access-title') .text(emptyDescriptions['vcl-access-title']); instructionsWrapper .append(level2) .attr('class', 'screen-reader-info vcl-access-subtitle') .text(emptyDescriptions['vcl-access-subtitle']); instructionsWrapper .append(level2) .attr('class', 'screen-reader-info vcl-access-executive-summary-heading') .text(emptyDescriptions['headings']); instructionsWrapper .append(level4) .attr('class', 'screen-reader-info vcl-access-executive-summary') .attr('data-level', level2) .text(emptyDescriptions['vcl-access-executive-summary']); instructionsWrapper .append(level2) .attr('class', 'screen-reader-info vcl-access-purpose-heading') .text(emptyDescriptions['headings']); instructionsWrapper .append(level4) .attr('class', 'screen-reader-info vcl-access-purpose') .attr('data-level', level2) .text(emptyDescriptions['vcl-access-purpose']); instructionsWrapper .append(level2) .attr('class', 'screen-reader-info vcl-access-long-description-heading') .text(emptyDescriptions['headings']); instructionsWrapper .append(level4) .attr('class', 'screen-reader-info vcl-access-long-description') .attr('data-level', level2) .text(emptyDescriptions['vcl-access-long-description']); instructionsWrapper .append(level4) .attr('data-level', level2) .attr('class', 'screen-reader-info vcl-access-context') .text(emptyDescriptions['vcl-access-context']); instructionsWrapper .append(level2) .attr('class', 'screen-reader-info vcl-access-structure-heading') .text('Structure'); instructionsWrapper .append(level3) .attr('class', 'screen-reader-info vcl-access-statistics-heading') .text(emptyDescriptions['headings']); instructionsWrapper .append(level4) .attr('class', 'screen-reader-info vcl-access-statistics') .attr('data-level', level3) .text(emptyDescriptions['vcl-access-statistics']); instructionsWrapper .append(level3) .attr('class', 'screen-reader-info vcl-access-chart-layout-heading') .text('Chart Layout Description'); instructionsWrapper .append(level4) .attr('class', 'screen-reader-info vcl-access-layout') .text(emptyDescriptions['vcl-access-layout']); instructionsWrapper .append(level4) .attr('class', 'screen-reader-info vcl-access-xAxis') .text(emptyDescriptions['vcl-access-xAxis']); instructionsWrapper .append(level4) .attr('class', 'screen-reader-info vcl-access-yAxis') .text(emptyDescriptions['vcl-access-yAxis']); instructionsWrapper .append(level3) .attr('class', 'screen-reader-info vcl-access-notes-heading') .text(emptyDescriptions['headings']); instructionsWrapper .append(level4) .attr('class', 'screen-reader-info vcl-access-notes') .attr('data-level', level3) .attr('data-annotationlevel', level2) .text(emptyDescriptions['vcl-access-notes']); instructionsWrapper .append(level2) .attr('class', 'screen-reader-info vcl-access-annotations-heading') .text(emptyDescriptions['headings']); } instructionsWrapper.attr('id', 'chart-instructions-' + uniqueID); const chartTitle = title ? ', Titled: ' + title : ', with no title provided.'; const fullDescription = `Keyboard interactive ${chartTag}${chartTitle}. This section contains additional information about this chart. Pressing TAB will focus the keyboard instructions menu. Tabbing again takes you to the chart area.`; // Chart Unique ID: ${uniqueID}. const nonInteractive = `Static ${chartTag} image${chartTitle}. This section contains additional information about this chart. Pressing TAB will focus the data table button.`; instructionsWrapper.select('.vcl-region-label').text(!disableKeyNav ? fullDescription : nonInteractive); }; export const setAccessTitle = (rootEle: any, title: string) => { select(rootEle) .select('.vcl-access-title') .text(title ? 'Chart title: ' + title : emptyDescriptions['vcl-access-title']); }; export const setAccessSubtitle = (rootEle: any, subtitle: string) => { select(rootEle) .select('.vcl-access-subtitle') .text(subtitle ? 'Chart subtitle: ' + subtitle : emptyDescriptions['vcl-access-subtitle']); }; export const setAccessLongDescription = (rootEle: any, description: string) => { setDescriptionNode( select(rootEle).select('.vcl-accessibility-instructions'), description, 'Long Description', 'vcl-access-long-description', description || select(rootEle) .select('.vcl-access-context') .text() ); }; export const setAccessContext = (rootEle: any, context: string) => { setDescriptionNode( select(rootEle).select('.vcl-accessibility-instructions'), context, 'Long Description', 'vcl-access-context', context || select(rootEle) .select('.vcl-access-long-description') .text(), 'vcl-access-long-description' ); }; export const setAccessExecutiveSummary = (rootEle: any, summary: string) => { setDescriptionNode( select(rootEle).select('.vcl-accessibility-instructions'), summary, 'Executive Summary', 'vcl-access-executive-summary', !!summary ); }; export const setAccessPurpose = (rootEle: any, purpose: string) => { setDescriptionNode( select(rootEle).select('.vcl-accessibility-instructions'), purpose, 'Purpose', 'vcl-access-purpose', !!purpose ); }; export const setAccessStatistics = (rootEle: any, statistics: string) => { setDescriptionNode( select(rootEle).select('.vcl-accessibility-instructions'), statistics, 'Statistical Information', 'vcl-access-statistics', !!statistics ); }; export const setAccessChartCounts = ({ rootEle, parentGNode, chartTag, geomType, groupName, recursive }: { rootEle: any; parentGNode: any; chartTag: string; geomType: string; groupName?: string; recursive?: boolean; }) => { const primaryG = select(parentGNode); const plural = primaryG .selectAll('g') .selectAll('*:not(title)') .size() > 1 || (primaryG .selectAll('g') .selectAll('*:not(title)') .size() === 0 && primaryG.selectAll('*:not(title)').size()) > 1 ? 's' : ''; const groupNameString = groupName || geomType + ' group'; const groupPlural = primaryG.selectAll('g').size() > 1 ? 's' : ''; const count = !recursive ? primaryG.selectAll('g').size() ? primaryG.selectAll('g').size() + ' ' + groupNameString + groupPlural + ' containing a total ' + (primaryG .selectAll('g') .selectAll('*:not(title)') .size() - primaryG .selectAll('g') .selectAll('.vcl-accessibility-focus-highlight') .size()) + ' ' + geomType + plural : primaryG.selectAll('*:not(title)').size() - primaryG.selectAll('.vcl-accessibility-focus-highlight').size() + ' ' + geomType + plural : primaryG.selectAll('g').size() + ' ' + geomType + plural + ' (more ' + geomType + 's may be revealed upon interaction)'; select(rootEle) .select('.vcl-access-layout') .text(`This is a ${chartTag} with ${count}.`); }; export const setAccessXAxis = ({ rootEle, hasXAxis, xAxis, xAxisLabel }: { rootEle: any; hasXAxis: boolean; xAxis?: any; xAxisLabel?: string; }) => { let label = emptyDescriptions['vcl-access-xAxis']; if (hasXAxis) { const xDomain = xAxis && xAxis.formattedTicks && xAxis.formattedTicks[0] ? xAxis.formattedTicks : []; const xAxisTitle = xAxisLabel ? `, titled ${xAxisLabel}` : ''; const xAxisRange = xDomain.length ? ` with a range that starts with ${xDomain[0]} and ends with ${xDomain[xDomain.length - 1]}` : ''; label = `The chart has a horizontal X Axis${xAxisTitle}${xAxisRange}.`; } select(rootEle) .select('.vcl-access-xAxis') .text(label); }; export const setAccessYAxis = ({ rootEle, hasYAxis, yAxis, secondaryYAxis, yAxisLabel, secondaryYAxisLabel, xAxisLabel }: { rootEle: any; hasYAxis: boolean; yAxis?: any; secondaryYAxis?: any; yAxisLabel?: string; secondaryYAxisLabel?: string; xAxisLabel?: string; }) => { let label = emptyDescriptions['vcl-access-yAxis']; // y axis range from min to max // secondary y axis range from min to max e.g for pareto-chart. let yAxisTicks; if (yAxis && yAxis.formattedTicks) { yAxisTicks = yAxis.formattedTicks; } let secondaryYAxisTicks; if (secondaryYAxis && secondaryYAxis.formattedTicks) { secondaryYAxisTicks = secondaryYAxis.formattedTicks; } if (hasYAxis) { if (secondaryYAxisTicks) { // secondary y axis present const yAxis1Title = yAxisLabel ? `, titled ${yAxisLabel}` : ''; const yAxis1Ticks = yAxisTicks ? ` with a range that starts with ${yAxisTicks[0]} and ends with ${yAxisTicks[yAxisTicks.length - 1]}` : ''; const yAxis2Title = secondaryYAxisLabel ? `, titled ${secondaryYAxisLabel}` : ''; const yAxis2Ticks = secondaryYAxisTicks ? ` with a range that starts with ${secondaryYAxisTicks[0]} and ends with ${ secondaryYAxisTicks[secondaryYAxisTicks.length - 1] }` : ''; label = `The chart has a primary vertical Y Axis${yAxis1Title}${yAxis1Ticks}. `; label += `The chart has a secondary vertical Y Axis${yAxis2Title}${yAxis2Ticks}.`; } else if (!(typeof yAxis === 'function')) { // y axis is an object that may contain multiple axes // parallel plot uses this const yLabels = Object.keys(yAxis); const firstYDomain = yAxis[yLabels[0]].y && yAxis[yLabels[0]].y.formattedTicks && yAxis[yLabels[0]].y.formattedTicks[0] ? yAxis[yLabels[0]].y.formattedTicks : []; const y1Range = firstYDomain.length ? `, with a range that starts with ${firstYDomain[0]} and ends with ${firstYDomain[firstYDomain.length - 1]}` : ''; label = yLabels.length > 1 ? `The chart has ${yLabels.length} vertical Y Axis sections, all using different scales${ xAxisLabel ? '. This series is titled ' + xAxisLabel : '' }.` : `The chart has a vertical Y Axis, titled ${yLabels[0]}${y1Range}.`; if (yLabels.length > 1) { // the yAxis objected *does* contain multiple objects! let i = 0; for (i = 0; i < yLabels.length; i++) { const labelScale = yAxis[yLabels[i]].y; const iYDomain = labelScale && labelScale.formattedTicks && labelScale.formattedTicks[0] ? labelScale.formattedTicks : []; const iYRange = iYDomain.length ? `, with a range that starts with ${iYDomain[0]} and ends with ${iYDomain[iYDomain.length - 1]}` : ''; label += ` Y Axis ${i + 1} of ${yLabels.length}, titled ${yLabels[i]}${iYRange}.`; } } } else { // only one axis present const yDomain = yAxis && yAxis.formattedTicks && yAxis.formattedTicks[0] ? yAxis.formattedTicks : []; const yAxisTitle = yAxisLabel ? `, titled ${yAxisLabel}` : ''; const yAxisRange = yDomain.length ? ` with a range that starts with ${yDomain[0]} and ends with ${yDomain[yDomain.length - 1]}` : ''; label = `The chart has a vertical Y axis${yAxisTitle}${yAxisRange}.`; } } select(rootEle) .select('.vcl-access-yAxis') .text(label); }; export const setAccessStructure = (rootEle: any, structure: string) => { setDescriptionNode( select(rootEle).select('.vcl-accessibility-instructions'), structure, 'Notes about the chart structure', 'vcl-access-notes', !!structure ); }; export const setAccessAnnotation = (rootEle: any, annotations: any) => { const parent = select(rootEle).select('.vcl-accessibility-instructions'); const notesNode = parent.select('.vcl-access-notes').node(); let header = parent.select('.vcl-access-annotations-heading'); const instructionsHeading = '.vcl-interaction-instructions'; const headerLevel = notesNode.dataset.annotationlevel; const level1 = findTagLevel(headerLevel, 1); const level2 = findTagLevel(headerLevel, 2); parent.selectAll('.vcl-access-annotation').remove(); let i = 1; if (annotations && annotations.length) { if (!header.size()) { header = parent .insert(headerLevel, instructionsHeading) .attr('class', 'screen-reader-info vcl-access-annotations-heading'); } annotations.forEach(annotation => { let count = false; if (annotation.note) { if (annotation.note.title) { count = true; parent .insert(level1, instructionsHeading) .attr('class', 'screen-reader-info vcl-access-annotation') .text(annotation.note.title || 'Annotation ' + i); } if (annotation.note.label) { count = true; parent .insert(level2, instructionsHeading) .attr('class', 'screen-reader-info vcl-access-annotation') .text(annotation.note.label); } } if (annotation.accessibilityDescription) { count = true; parent .insert(level2, instructionsHeading) .attr('class', 'screen-reader-info vcl-access-annotation') .text(annotation.accessibilityDescription); } if (count) { i++; } }); } if (i - 1) { const plural = i - 2 > 0 ? 's' : ''; const headingText = i - 1 + ' annotation' + plural + ' on the chart'; header.text(headingText); } else { header.remove(); } }; export const setAccessibilityDescriptionWidth = (uniqueID, width) => { select('#chart-instructions-' + uniqueID).style('width', () => { return Math.max(width, 200) + 'px'; }); }; export const findTagLevel = (startLevel: any, depthFromStart?: number) => { if (startLevel === 'p' || startLevel === 'P' || !startLevel) { return 'p'; } else if (startLevel === 'span' || startLevel === 'SPAN') { return 'span'; } else if (startLevel === 'div' || startLevel === 'DIV') { return 'div'; } const depth = depthFromStart || 0; const start = typeof startLevel !== 'string' || startLevel.length <= 1 ? startLevel : startLevel[1]; if (+start + depth < 7 && depth < 3) { return 'h' + (+start + depth); } return 'p'; }; const focusInstructions = (_, i, n) => { select(n[i]) .style('width', 'auto') .style('height', 'auto') .style('left', 'auto') .style('top', '15px') .style('background', 'white') .style('z-index', 9999); }; const blurInstructions = (_, i, n) => { select(n[i]) .style('width', null) .style('height', null) .style('left', null) .style('top', null) .style('background', null) .style('z-index', null); }; const setDescriptionNode = ( root: any, description: string, headingText: string, tag: string, contentExists: boolean, headingTag?: string ) => { const contentNode = root.select('.' + tag).text(description || emptyDescriptions[tag]); let headingNode = root.select('.' + (headingTag || tag) + '-heading'); if (contentExists) { if (!headingNode.size()) { headingNode = root .insert(contentNode.node().dataset.level, '.' + (headingTag || tag)) .attr('class', 'screen-reader-info ' + (headingTag || tag) + '-heading'); } headingNode.text(headingText); } else { headingNode.remove(); } };
the_stack
import {CamerasController} from './utils/CamerasController'; import {Cooker} from './utils/Cooker'; import {CookController} from './utils/CookController'; import {CoreGraph} from '../../core/graph/CoreGraph'; import {CorePerformance} from '../../core/performance/CorePerformance'; import {DispatchController} from './utils/DispatchController'; import {ExpressionsController} from './utils/ExpressionsController'; import {LifeCycleController} from './utils/LifeCycleController'; import {LoadingController} from './utils/LoadingController'; import {MissingReferencesController} from './utils/MissingReferencesController'; import {NodesController} from './utils/NodesController'; import {PolySceneSerializer} from './utils/Serializer'; import {SceneEventsDispatcher} from './utils/events/EventsDispatcher'; import {ObjectsController} from './utils/ObjectsController'; import {ReferencesController} from './utils/ReferencesController'; import {onTimeTickHook, TimeController} from './utils/TimeController'; import {UniformsController} from './utils/UniformsController'; import {ViewersRegister} from './utils/ViewersRegister'; import {WebGLController} from './utils/WebGLController'; import {WindowController} from './utils/WindowController'; import {SceneAssetsController} from './utils/AssetsController'; import {BaseNodeType} from '../nodes/_Base'; import {ObjNodeChildrenMap} from '../poly/registers/nodes/Obj'; import {ParamsInitData} from '../nodes/utils/io/IOController'; import {Constructor, valueof} from '../../types/GlobalTypes'; import {Scene} from 'three/src/scenes/Scene'; import {CoreString} from '../../core/String'; import {Object3D} from 'three/src/core/Object3D'; /** * PolyScene contains all nodes within a scene. * */ export class PolyScene { /** * Returns the THREE.Scene. * * @remarks * * Read more about how to use a THREE.Scene on [THREE's documentation](https://threejs.org/docs/?q=scene#api/en/scenes/Scene) * */ threejsScene(): Scene { return this.root().object; } private _uuid!: string; setUuid(uuid: string) { return (this._uuid = uuid); } get uuid() { return this._uuid; } private _name: string | undefined; setName(newName: string) { newName = CoreString.sanitizeName(newName); return (this._name = newName); } name() { return this._name; } protected _cameras_controller = new CamerasController(this); get camerasController() { return this._cameras_controller; } /** * Returns the cameraNode that has been set as main * */ mainCameraNode() { return this.camerasController.mainCameraNode(); } private _cooker = new Cooker(this); get cooker() { return this._cooker; } // private _cube_cameras_controller: CubeCamerasController; // get cube_cameras_controller() { // return (this._cube_cameras_controller = this._cube_cameras_controller || new CubeCamerasController(this)); // } private _assets_controller: SceneAssetsController | undefined; get assets() { return (this._assets_controller = this._assets_controller || new SceneAssetsController()); } public readonly cookController = new CookController(); /** * Returns a promise to wait for all nodes to have cooked when loading a scene. * */ async waitForCooksCompleted(): Promise<void> { return this.cookController.waitForCooksCompleted(); } private _dispatch_controller: DispatchController | undefined; get dispatchController() { return (this._dispatch_controller = this._dispatch_controller || new DispatchController(this)); } private _events_dispatcher: SceneEventsDispatcher | undefined; get eventsDispatcher() { return (this._events_dispatcher = this._events_dispatcher || new SceneEventsDispatcher(this)); } private _graph = new CoreGraph(); get graph() { return this._graph; } private _lifecycle_controller: LifeCycleController | undefined; get lifecycleController() { return (this._lifecycle_controller = this._lifecycle_controller || new LifeCycleController(this)); } private _loading_controller: LoadingController | undefined; get loadingController() { return (this._loading_controller = this._loading_controller || new LoadingController(this)); } private _missing_expression_references_controller: MissingReferencesController = new MissingReferencesController( this ); get missingExpressionReferencesController() { return this._missing_expression_references_controller; } private _expressions_controller: ExpressionsController = new ExpressionsController(); get expressionsController() { return this._expressions_controller; } protected _nodes_controller = new NodesController(this); get nodesController() { return this._nodes_controller; } /** * Creates a new node. * * nodeClass can be either a string or a node class. Both examples below work: * * - polyScene.createNode('box'): returns a BoxSopNode * - polyScene.createNode(boxSopNode): returns a BoxSopNode * */ createNode<S extends keyof ObjNodeChildrenMap>( nodeClass: S, params_init_value_overrides?: ParamsInitData ): ObjNodeChildrenMap[S]; createNode<K extends valueof<ObjNodeChildrenMap>>( nodeClass: Constructor<K>, params_init_value_overrides?: ParamsInitData ): K; createNode<K extends valueof<ObjNodeChildrenMap>>( nodeClass: Constructor<K>, params_init_value_overrides?: ParamsInitData ): K { return this.root().createNode(nodeClass, params_init_value_overrides) as K; } /** * returns all nodes with a given type * * - polyScene.nodesByType('box'): returns all BoxSopNodes */ nodesByType(type: string): BaseNodeType[] { return this.nodesController.nodesByType(type); } protected _objects_controller = new ObjectsController(this); get objectsController() { return this._objects_controller; } /** * returns a THREE.Object3D whose name matches the mask * */ findObjectByMask(mask: string): Object3D | undefined { return this._objects_controller.findObjectByMask(mask); } /** * returns a list THREE.Object3Ds whose names matche the mask * */ objectsByMask(mask: string): Object3D[] { return this._objects_controller.objectsByMask(mask); } protected _references_controller = new ReferencesController(this); get referencesController() { return this._references_controller; } protected _performance: CorePerformance | undefined; get performance() { return (this._performance = this._performance || new CorePerformance()); } protected _viewers_register: ViewersRegister | undefined; get viewersRegister() { return (this._viewers_register = this._viewers_register || new ViewersRegister(this)); } // // // time // // protected _time_controller = new TimeController(this); get timeController() { return this._time_controller; } /** * sets the current frame * */ setFrame(frame: number) { this.timeController.setFrame(frame); } setFrameToStart() { this.timeController.setFrameToStart(); } /** * returns the current frame * */ frame(): number { return this.timeController.frame(); } /** * returns the current time * */ time(): number { return this.timeController.time(); } maxFrame() { return this.timeController.maxFrame(); } /** * starts playing the scene * */ play() { this.timeController.play(); } /** * pauses the scene * */ pause() { this.timeController.pause(); } // // // serializer // // private _serializer: PolySceneSerializer | undefined; private get serializer() { return (this._serializer = this._serializer || new PolySceneSerializer(this)); } toJSON() { return this.serializer.toJSON(); } private _read_only = false; private _read_only_requester: BaseNodeType | undefined; markAsReadOnly(requester: BaseNodeType) { if (this._read_only) { return; } this._read_only_requester = requester; this._read_only = true; } readOnly() { return this._read_only; } readOnlyRequester() { return this._read_only_requester; } // // // uniforms // // private _uniformsController: UniformsController | undefined; get uniformsController() { return (this._uniformsController = this._uniformsController || new UniformsController(this)); } // // // webgl // // private _webgl_controller: WebGLController | undefined; get webgl_controller() { return (this._webgl_controller = this._webgl_controller || new WebGLController()); } // // // window // // private _windowController: WindowController | undefined; get windowController() { return (this._windowController = this._windowController || new WindowController(this)); } // // // constructor // // constructor() { // this.mark_as_loaded() this._graph.setScene(this); // this.time_controller.init(); this.nodesController.init(); } dispose() { this._windowController?.dispose(); } // // // cooker // // /** * batchUpdates can be useful to set multiple parameter values without triggering a recook for each update. * */ batchUpdates(callback: () => void) { this._cooker.block(); callback(); this._cooker.unblock(); } // // // nodes // // /** * returns a node based on its path * * - polyScene.node('/geo1') * */ node(path: string) { return this.nodesController.node(path); } /** * returns the root node * */ root() { return this.nodesController.root(); } // // // CALLBACKS // // /** * registers a BeforeTick callback. BeforeTick callbacks are run before updating the frame (and therefore before any time dependent node has changed) * */ registerOnBeforeTick(callbackName: string, callback: onTimeTickHook): void { this.timeController.registerOnBeforeTick(callbackName, callback); } /** * unregisters BeforeTick callback * */ unRegisterOnBeforeTick(callbackName: string): void { this.timeController.unRegisterOnBeforeTick(callbackName); } /** * Returns the list registered BeforeTick callback names * */ registeredBeforeTickCallbackNames(): string[] | undefined { return this.timeController.registeredBeforeTickCallbackNames(); } /** * registers AfterTick callback. AfterTick callbacks are run after updating the frame (and therefore after any time dependent node has changed) * */ registerOnAfterTick(callbackName: string, callback: onTimeTickHook): void { this.timeController.registerOnAfterTick(callbackName, callback); } /** * unregisters AfterTick callback * */ unRegisterOnAfterTick(callbackName: string): void { this.timeController.unRegisterOnAfterTick(callbackName); } /** * Returns the list registered AfterTick callback names * */ registeredAfterTickCallbackNames(): string[] | undefined { return this.timeController.registeredAfterTickCallbackNames(); } }
the_stack
/** * @license Copyright © 2013 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview Code that manages multiple full-width pages, of which only one is shown at a time. Intended for use on * the mobile site but could be used on desktop sites too. */ namespace VRS { /** * The settings to pass when creating a new Page object. */ export interface Page_Settings { /** * The unique name of the page. */ name: string; /** * The top-level element of the page. */ element: JQuery; /** * A method that is called whenever the page is hidden or made visible. Passed true if the page is about to be made visible and false if it has just been hidden. */ visibleCallback?: (willBecomeVisible: boolean) => void; /** * A method that is called after the page has been made visible. */ afterVisibleCallback?: () => void; } /** * Describes a page for the page manager. */ export class Page { // Kept as public fields for backwards compatibility name: string; element: JQuery; visibleCallback: (willBecomeVisible: boolean) => void; afterVisibleCallback: () => void; container: JQuery = null; isVisible = true; originalParent: JQuery = null; originalCss: Object = null; constructor(settings: Page_Settings) { if(!settings) throw 'You must supply a settings object'; if(!settings.name) throw 'You must supply a unique name'; if(!settings.element) throw 'You must supply the top-level element'; this.name = settings.name; this.element = settings.element; this.visibleCallback = settings.visibleCallback || function() { }; this.afterVisibleCallback = settings.afterVisibleCallback || function() { }; } /** * Releases any resources held by the page. Moves the page back to its original parent. */ dispose() { if(this.originalCss) this.element.css(this.originalCss); if(this.originalParent) this.originalParent.append(this.element); else this.element.remove(); if(this.container) this.container.remove(); this.container = null; this.originalCss = null; this.originalParent = null; } } /** * The object that manages pages for the mobile versions of the site. */ export class PageManager { private _Dispatcher = new VRS.EventHandler({ name: 'VRS.PageManager' }); private _Events = { hidingPage: 'hidingPage', hiddenPage: 'hiddenPage', showingPage: 'showingPage', shownPage: 'shownPage' }; private _Element: JQuery = null; // The element that the page manager attaches all pages to. private _ElementOriginalCss: Object = null; // The CSS that needs to be applied to the element to return it to the pre-initialised state. private _Pages: Page[] = []; // The collection of pages that have been added to the manager. private _VisiblePage: Page = null; // The page that is currently visible. /** * Releases all of the resources held by the object. */ dispose() { var length = this._Pages.length; for(var i = length - 1;i >= 0;--i) { var page = this._Pages[i]; page.dispose(); } this._Pages = []; if(this._Element && this._ElementOriginalCss) { this._Element.css(this._ElementOriginalCss); } this._Element = null; this._ElementOriginalCss = null; $(window).off('resize.vrspagemanager', this.windowResized); } /** * Called before a page is hidden. */ hookHidingPage(callback: (page: Page) => void, forceThis?: Object) : IEventHandle { return this._Dispatcher.hook(this._Events.hidingPage, callback, forceThis); } /** * Called after a page has been hidden. */ hookHiddenPage(callback: (page: Page) => void, forceThis?: Object) : IEventHandle { return this._Dispatcher.hook(this._Events.hiddenPage, callback, forceThis); } /** * Called before a page is shown. */ hookShowingPage(callback: (page: Page) => void, forceThis?: Object) : IEventHandle { return this._Dispatcher.hook(this._Events.showingPage, callback, forceThis); } /** * Called after a page has been shown. */ hookShownPage(callback: (page: Page) => void, forceThis?: Object) : IEventHandle { return this._Dispatcher.hook(this._Events.shownPage, callback, forceThis); } /** * Raises an event. */ private raiseEvent(event: string, page: Page) { this._Dispatcher.raise(event, [ page ]); } /** * Unhooks a hooked event. */ unhook(hookResult: IEventHandle) { this._Dispatcher.unhook(hookResult); } /** * Initialises the page manager. * @param {jQuery} element The element to which all pages will be attached. The CSS for this element gets modified. */ initialise(element: JQuery) { if(this._Element) throw 'The page manager cannot be initialised more than once'; if(!element) throw 'You must supply an element for the page manager to use'; this._Element = element; this._ElementOriginalCss = this._Element.css([ 'width', 'height', 'position' ]); this._Element.css({ width: '100%', height: '100%', position: 'relative' }); $(window).on('resize.vrspagemanager', $.proxy(this.windowResized, this)); } /** * Creates a page from a jQuery element. If this is the first page that's been added then it remains on screen, * otherwise it is hidden. */ addPage(page: Page) { if(!this._Element) throw 'You must initialise the page manager before calling addPage'; if(!page) throw 'You must supply a page'; if(this.findPage(page.name)) throw 'A page already exists with the name ' + page.name; this._Pages.push(page); page.originalParent = page.element.parent(); page.originalCss = page.element.css([ 'width', 'height' ]); page.container = $('<div/>') .css({ width: '100%', height: '100%' }) .appendTo(this._Element) .append(page.element); page.element.css({ width: '100%', height: '100%' }); if(VRS.refreshManager) { VRS.refreshManager.registerOwner(page.container); VRS.refreshManager.rebuildRelationships(); } if(this._Pages.length === 1) this.showPage(page); else this.hidePage(page); } /** * Removes a page from the manager. The page is either returned to its original parent or, if it had no parent, * it is just removed from the window. */ removePage(pageOrName: string | Page) { var index = this.findPageIndex(pageOrName); var page = index === -1 ? null : this._Pages[index]; if(page) { if(VRS.refreshManager) { VRS.refreshManager.unregisterOwner(page.container); } if(page === this._VisiblePage) { if(index + 1 < this._Pages.length) this.show(this._Pages[index + 1]); else if(index > 0) this.show(this._Pages[index - 1]); else this._VisiblePage = null; } this._Pages.splice(index, 1); page.dispose(); if(VRS.refreshManager) { VRS.refreshManager.rebuildRelationships(); } } } /** * Hides or shows a page. */ show(pageOrName: string | Page) { var page = this.findPage(pageOrName); if(!page.isVisible) { if(this._VisiblePage) this.hidePage(this._VisiblePage); this.showPage(page); } } /** * Hides a page from view. */ private hidePage(page: Page) { if(page.isVisible) { page.isVisible = false; this.raiseEvent(this._Events.hidingPage, page); page.container.hide(); this.raiseEvent(this._Events.hiddenPage, page); page.visibleCallback(false); } if(page === this._VisiblePage) { this._VisiblePage = null; } } /** * Brings a page into view. */ private showPage(page: Page) { if(!page.isVisible) { page.isVisible = true; page.visibleCallback(true); this.raiseEvent(this._Events.showingPage, page); page.container.show(); this.raiseEvent(this._Events.shownPage, page); page.afterVisibleCallback(); if(VRS.refreshManager) { VRS.refreshManager.refreshTargets(page.container); } } this._VisiblePage = page; } /** * If passes the name of a page then this returns the registered VRS.Page with that name, otherwise if passed a * page then it simply gets returned. Returns null if no page exists for the name passed across. */ private findPage(nameOrPage: string | Page) : Page { var result: Page = <Page>nameOrPage; if(!(result instanceof VRS.Page)) { result = null; var length = this._Pages.length; for(var i = 0;i < length;++i) { var page = this._Pages[i]; if(page.name === nameOrPage) { result = page; break; } } } return result; } /** * Given a page or the name of a page this returns the index of the associated page within _Pages. Returns -1 * if no page could be found. */ private findPageIndex(nameOrPage: string | Page) : number { var result = -1; var length = this._Pages.length; for(var i = 0;i < length;++i) { var page = this._Pages[i]; if(nameOrPage === page || nameOrPage === page.name) { result = i; break; } } return result; } /** * Called when the window is resized. */ private windowResized() { if(this._VisiblePage && VRS.refreshManager) { VRS.refreshManager.refreshTargets(this._VisiblePage.container); } } } /* * Pre-builts */ export var pageManager = new VRS.PageManager(); }
the_stack
import { BrowserView, app, ipcMain } from 'electron'; import { parse as parseUrl } from 'url'; import { getViewMenu } from './menus/view'; import { AppWindow } from './windows'; import { IHistoryItem, IBookmark } from '~/interfaces'; import { ERROR_PROTOCOL, NETWORK_ERROR_HOST, WEBUI_BASE_URL, } from '~/constants/files'; import { NEWTAB_URL } from '~/constants/tabs'; import { ZOOM_FACTOR_MIN, ZOOM_FACTOR_MAX, ZOOM_FACTOR_INCREMENT, } from '~/constants/web-contents'; import { TabEvent } from '~/interfaces/tabs'; import { Queue } from '~/utils/queue'; import { Application } from './application'; import { getUserAgentForURL } from './user-agent'; interface IAuthInfo { url: string; } export class View { public browserView: BrowserView; public isNewTab = false; public homeUrl: string; public favicon = ''; public incognito = false; public errorURL = ''; private hasError = false; private window: AppWindow; public bounds: any; public lastHistoryId: string; public bookmark: IBookmark; public findInfo = { occurrences: '0/0', text: '', }; public requestedAuth: IAuthInfo; public requestedPermission: any; private historyQueue = new Queue(); private lastUrl = ''; public constructor(window: AppWindow, url: string, incognito: boolean) { this.browserView = new BrowserView({ webPreferences: { preload: `${app.getAppPath()}/build/view-preload.bundle.js`, nodeIntegration: false, contextIsolation: true, sandbox: true, enableRemoteModule: false, partition: incognito ? 'view_incognito' : 'persist:view', plugins: true, nativeWindowOpen: true, webSecurity: true, javascript: true, worldSafeExecuteJavaScript: false, }, }); this.incognito = incognito; this.webContents.userAgent = getUserAgentForURL( this.webContents.userAgent, '', ); (this.webContents as any).windowId = window.win.id; this.window = window; this.homeUrl = url; this.webContents.session.webRequest.onBeforeSendHeaders( (details, callback) => { const { object: settings } = Application.instance.settings; if (settings.doNotTrack) details.requestHeaders['DNT'] = '1'; callback({ requestHeaders: details.requestHeaders }); }, ); ipcMain.handle(`get-error-url-${this.id}`, async (e) => { return this.errorURL; }); this.webContents.on('context-menu', (e, params) => { const menu = getViewMenu(this.window, params, this.webContents); menu.popup(); }); this.webContents.addListener('found-in-page', (e, result) => { Application.instance.dialogs .getDynamic('find') .browserView.webContents.send('found-in-page', result); }); this.webContents.addListener('page-title-updated', (e, title) => { this.window.updateTitle(); this.updateData(); this.emitEvent('title-updated', title); this.updateURL(this.webContents.getURL()); }); this.webContents.addListener('did-navigate', async (e, url) => { this.emitEvent('did-navigate', url); await this.addHistoryItem(url); this.updateURL(url); }); this.webContents.addListener( 'did-navigate-in-page', async (e, url, isMainFrame) => { if (isMainFrame) { this.emitEvent('did-navigate', url); await this.addHistoryItem(url, true); this.updateURL(url); } }, ); this.webContents.addListener('did-stop-loading', () => { this.updateNavigationState(); this.emitEvent('loading', false); this.updateURL(this.webContents.getURL()); }); this.webContents.addListener('did-start-loading', () => { this.hasError = false; this.updateNavigationState(); this.emitEvent('loading', true); this.updateURL(this.webContents.getURL()); }); this.webContents.addListener('did-start-navigation', async (e, ...args) => { this.updateNavigationState(); this.favicon = ''; this.emitEvent('load-commit', ...args); this.updateURL(this.webContents.getURL()); }); this.webContents.on( 'did-start-navigation', (e, url, isInPlace, isMainFrame) => { if (!isMainFrame) return; const newUA = getUserAgentForURL(this.webContents.userAgent, url); if (this.webContents.userAgent !== newUA) { this.webContents.userAgent = newUA; } }, ); this.webContents.addListener( 'new-window', (e, url, frameName, disposition) => { if (disposition === 'new-window') { if (frameName === '_self') { e.preventDefault(); this.window.viewManager.selected.webContents.loadURL(url); } else if (frameName === '_blank') { e.preventDefault(); this.window.viewManager.create( { url, active: true, }, true, ); } } else if (disposition === 'foreground-tab') { e.preventDefault(); this.window.viewManager.create({ url, active: true }, true); } else if (disposition === 'background-tab') { e.preventDefault(); this.window.viewManager.create({ url, active: false }, true); } }, ); this.webContents.addListener( 'did-fail-load', (e, errorCode, errorDescription, validatedURL, isMainFrame) => { // ignore -3 (ABORTED) - An operation was aborted (due to user action). if (isMainFrame && errorCode !== -3) { this.errorURL = validatedURL; this.hasError = true; this.webContents.loadURL( `${ERROR_PROTOCOL}://${NETWORK_ERROR_HOST}/${errorCode}`, ); } }, ); this.webContents.addListener( 'page-favicon-updated', async (e, favicons) => { this.favicon = favicons[0]; this.updateData(); try { let fav = this.favicon; if (fav.startsWith('http')) { fav = await Application.instance.storage.addFavicon(fav); } this.emitEvent('favicon-updated', fav); } catch (e) { this.favicon = ''; // console.error(e); } }, ); this.webContents.addListener('zoom-changed', (e, zoomDirection) => { const newZoomFactor = this.webContents.zoomFactor + (zoomDirection === 'in' ? ZOOM_FACTOR_INCREMENT : -ZOOM_FACTOR_INCREMENT); if ( newZoomFactor <= ZOOM_FACTOR_MAX && newZoomFactor >= ZOOM_FACTOR_MIN ) { this.webContents.zoomFactor = newZoomFactor; this.emitEvent('zoom-updated', this.webContents.zoomFactor); window.viewManager.emitZoomUpdate(); } else { e.preventDefault(); } }); this.webContents.addListener( 'certificate-error', ( event: Electron.Event, url: string, error: string, certificate: Electron.Certificate, callback: Function, ) => { console.log(certificate, error, url); // TODO: properly handle insecure websites. event.preventDefault(); callback(true); }, ); this.webContents.addListener('media-started-playing', () => { this.emitEvent('media-playing', true); }); this.webContents.addListener('media-paused', () => { this.emitEvent('media-paused', true); }); if (url.startsWith(NEWTAB_URL)) this.isNewTab = true; this.webContents.loadURL(url); this.browserView.setAutoResize({ width: true, height: true, horizontal: false, vertical: false, }); } public get webContents() { return this.browserView.webContents; } public get url() { return this.webContents.getURL(); } public get title() { return this.webContents.getTitle(); } public get id() { return this.webContents.id; } public get isSelected() { return this.id === this.window.viewManager.selectedId; } public updateNavigationState() { if (this.browserView.webContents.isDestroyed()) return; if (this.window.viewManager.selectedId === this.id) { this.window.send('update-navigation-state', { canGoBack: this.webContents.canGoBack(), canGoForward: this.webContents.canGoForward(), }); } } public destroy() { (this.browserView.webContents as any).destroy(); this.browserView = null; } public async updateCredentials() { if ( !process.env.ENABLE_AUTOFILL || this.browserView.webContents.isDestroyed() ) return; const item = await Application.instance.storage.findOne<any>({ scope: 'formfill', query: { url: this.hostname, }, }); this.emitEvent('credentials', item != null); } public async addHistoryItem(url: string, inPage = false) { if ( url !== this.lastUrl && !url.startsWith(WEBUI_BASE_URL) && !url.startsWith(`${ERROR_PROTOCOL}://`) && !this.incognito ) { const historyItem: IHistoryItem = { title: this.title, url, favicon: this.favicon, date: new Date().getTime(), }; await this.historyQueue.enqueue(async () => { this.lastHistoryId = ( await Application.instance.storage.insert<IHistoryItem>({ scope: 'history', item: historyItem, }) )._id; historyItem._id = this.lastHistoryId; Application.instance.storage.history.push(historyItem); }); } else if (!inPage) { await this.historyQueue.enqueue(async () => { this.lastHistoryId = ''; }); } } public updateURL = (url: string) => { if (this.lastUrl === url) return; this.emitEvent('url-updated', this.hasError ? this.errorURL : url); this.lastUrl = url; this.isNewTab = url.startsWith(NEWTAB_URL); this.updateData(); if (process.env.ENABLE_AUTOFILL) this.updateCredentials(); this.updateBookmark(); }; public updateBookmark() { this.bookmark = Application.instance.storage.bookmarks.find( (x) => x.url === this.url, ); if (!this.isSelected) return; this.window.send('is-bookmarked', !!this.bookmark); } public async updateData() { if (!this.incognito) { const id = this.lastHistoryId; if (id) { const { title, url, favicon } = this; this.historyQueue.enqueue(async () => { await Application.instance.storage.update({ scope: 'history', query: { _id: id, }, value: { title, url, favicon, }, multi: false, }); const item = Application.instance.storage.history.find( (x) => x._id === id, ); if (item) { item.title = title; item.url = url; item.favicon = favicon; } }); } } } public send(channel: string, ...args: any[]) { this.webContents.send(channel, ...args); } public get hostname() { return parseUrl(this.url).hostname; } public emitEvent(event: TabEvent, ...args: any[]) { this.window.send('tab-event', event, this.id, args); } }
the_stack
import { TestBed } from '@angular/core/testing'; import { HttpClientTestingModule, HttpTestingController, } from '@angular/common/http/testing'; import { ODataClient } from './client'; import { ODataMetadataResource, ODataEntitySetResource, ODataFunctionResource, ODataActionResource, ODataSingletonResource, ODataEntityResource, ODataBatchResource, ODataResource, } from './resources'; import { ODataModule } from './module'; import { ODataStructuredTypeParser } from './parsers'; import { HttpHeaders } from '@angular/common/http'; import { TripPinConfig, Person, NAMESPACE, SERVICE_ROOT, PlanItem, Trip, } from './trippin.spec'; import { ODataStructuredType } from './schema'; import { Http } from './utils'; describe('ODataClient', () => { let client: ODataClient; let httpMock: HttpTestingController; beforeEach(() => { TestBed.configureTestingModule({ imports: [ODataModule.forRoot(TripPinConfig), HttpClientTestingModule], }); client = TestBed.inject<ODataClient>(ODataClient); httpMock = TestBed.inject(HttpTestingController); }); afterEach(() => { httpMock.verify(); }); it('should return undefined parser for resource', () => { const set: ODataResource<Person> = client.entitySet<Person>('People'); const api = client.apiFor(set); const parser = api.parserForType<Person>( 'Foo' ) as ODataStructuredTypeParser<Person>; expect(parser).toBeUndefined(); }); it('should return person parser for resource', () => { const set: ODataResource<Person> = client.entitySet<Person>( 'People', `${NAMESPACE}.Person` ); const api = client.apiFor(set); const parser = api.parserForType<Person>( set.type() as string ) as ODataStructuredTypeParser<Person>; expect(parser instanceof ODataStructuredTypeParser).toBeTruthy(); }); it('should throw error parser for type', () => { expect(function () { client.parserForType<Person>(`${NAMESPACE}.Foo`); }).toThrow(new Error('No Parser for type TripPin.Foo was found')); }); it('should throw error entity config', () => { expect(function () { client.enumTypeForType<Person>(`${NAMESPACE}.Foo`); }).toThrow(new Error('No Enum for type TripPin.Foo was found')); }); it('should throw error entity config', () => { expect(function () { client.structuredTypeForType<Person>(`${NAMESPACE}.Foo`); }).toThrow(new Error('No Structured for type TripPin.Foo was found')); }); it('should return person parser for type', () => { const parser = client.parserForType<Person>(`${NAMESPACE}.Person`); expect(parser instanceof ODataStructuredTypeParser).toBeTruthy(); }); it('should return person entity config', () => { const config = client.structuredTypeForType<Person>(`${NAMESPACE}.Person`); expect(config instanceof ODataStructuredType).toBeTruthy(); }); it('should create metadata resource', () => { const metadata: ODataMetadataResource = client.metadata(); expect(metadata.endpointUrl()).toEqual(SERVICE_ROOT + '$metadata'); }); it('should create batch resource', () => { const batch: ODataBatchResource = client.batch(); expect(batch.endpointUrl()).toEqual(SERVICE_ROOT + '$batch'); }); it('should create singleton resource', () => { const singleton: ODataSingletonResource<Person> = client.singleton<Person>('Me'); expect(singleton.endpointUrl()).toEqual(SERVICE_ROOT + 'Me'); }); it('should create entitySet resource', () => { const set: ODataEntitySetResource<Person> = client.entitySet<Person>('People'); expect(set.endpointUrl()).toEqual(SERVICE_ROOT + 'People'); }); it('should create unbound function resource', () => { const fun: ODataFunctionResource<any, any> = client.function<any, any>( 'NS.MyFunction' ); expect(fun.endpointUrl()).toEqual(SERVICE_ROOT + 'NS.MyFunction'); }); it('should create unbound action resource', () => { const act: ODataActionResource<any, any> = client.action<any, any>( 'NS.MyAction' ); expect(act.endpointUrl()).toEqual(SERVICE_ROOT + 'NS.MyAction'); }); it('should return parser for resource', () => { const set: ODataResource<Person> = client.entitySet<Person>( 'People', `${NAMESPACE}.Person` ); const api = client.apiFor(set); const parser = api.parserForType<Person>( set.type() as string ) as ODataStructuredTypeParser<Person>; expect(parser instanceof ODataStructuredTypeParser).toBeTruthy(); expect(parser.fields.length).toEqual(9); }); it('should convert resource to json', () => { const set: ODataEntitySetResource<Person> = client.entitySet<Person>( 'People', `${NAMESPACE}.Person` ); const func = set.function<any, any>('NS.MyFunction'); const json = func.toJSON(); expect(json).toEqual({ segments: [ { name: 'entitySet', path: 'People', type: 'TripPin.Person' }, { name: 'function', path: 'NS.MyFunction' }, ], options: {}, }); }); it('should fetch people', () => { const dummyPeople = [ { '@odata.id': "http://services.odata.org/V4/TripPinServiceRW/People('russellwhyte')", '@odata.etag': 'W/"08D814450D6BDB6F"', UserName: 'russellwhyte', FirstName: 'Russell', LastName: 'Whyte', Emails: ['Russell@example.com', 'Russell@contoso.com'], }, { '@odata.id': "http://services.odata.org/V4/TripPinServiceRW/People('scottketchum')", '@odata.etag': 'W/"08D814450D6BDB6F"', UserName: 'scottketchum', FirstName: 'Scott', LastName: 'Ketchum', Emails: ['Scott@example.com'], }, ]; const data = { '@odata.context': 'http://services.odata.org/V4/TripPinServiceRW/$metadata#People', value: dummyPeople, }; client .entitySet<Person>('People', `${NAMESPACE}.Person`) .top(2) .fetch() .subscribe(({ entities, annots }) => { expect(entities !== null).toBeTrue(); expect((entities as any[]).length).toBe(2); expect(annots.entitySet).toEqual('People'); expect(entities).toEqual(dummyPeople); }); const req = httpMock.expectOne(`${SERVICE_ROOT}People?$top=2`); expect(req.request.method).toBe('GET'); req.flush(data); }); it('should fetch person', () => { const person = { UserName: 'russellwhyte', FirstName: 'Russell', LastName: 'Whyte', Emails: ['Russell@example.com', 'Russell@contoso.com'], }; const entityMetadata = { '@odata.context': 'http://services.odata.org/V4/TripPinServiceRW/$metadata#People/$entity', '@odata.id': "http://services.odata.org/V4/TripPinServiceRW/People('russellwhyte')", '@odata.etag': 'W/"08D814450D6BDB6F"', }; const entityFunctions = { '#Microsoft.OData.SampleService.Models.TripPin.GetFriendsTrips': { title: 'Microsoft.OData.SampleService.Models.TripPin.GetFriendsTrips', target: "http://services.odata.org/V4/(S(4m0tuxtnhcfctl4gzem3gr10))/TripPinServiceRW/People('diegomvh')/Microsoft.OData.SampleService.Models.TripPin.GetFriendsTrips", }, }; const entity: ODataEntityResource<Person> = client .entitySet<Person>('People', `${NAMESPACE}.Person`) .entity('russellwhyte'); entity.fetch().subscribe(({ entity, annots }) => { expect(annots.entitySet).toEqual('People'); expect(annots.etag).toEqual('W/"08D814450D6BDB6F"'); expect(entity).toEqual(person); }); const req = httpMock.expectOne(`${SERVICE_ROOT}People('russellwhyte')`); expect(req.request.method).toBe('GET'); const data = Object.assign({}, person, entityMetadata, entityFunctions); req.flush(data); }); it('should create trip', () => { const trip: Trip = { TripId: 3, ShareId: '00000000-0000-0000-0000-000000000000', Description: 'Create Containment', Name: 'Test Trip', Budget: 1000, StartsAt: new Date(Date.parse('2014-01-01T00:00:00+08:00')), EndsAt: new Date(Date.parse('2014-02-01T00:00:00+08:00')), Tags: ['Test Tag 1', 'Test Tag 2'], }; const data = { '@odata.context': "serviceRoot/$metadata#People('russellwhyte')/Trips/$entity", ...trip, }; client .entitySet<Person>('People', `${NAMESPACE}.Person`) .entity('russellwhyte') .navigationProperty<Trip>('Trips') .create({ //'@odata.type': 'Microsoft.OData.SampleService.Models.TripPin.Trip', TripId: 3, ShareId: '00000000-0000-0000-0000-000000000000', Description: 'Create Containment', Name: 'Test Trip', StartsAt: new Date(Date.parse('2014-01-01T00:00:00+08:00')), EndsAt: new Date(Date.parse('2014-02-01T00:00:00+08:00')), Budget: 1000, Tags: ['Test Tag 1', 'Test Tag 2'], }) .subscribe(({ entity, annots: meta }) => { expect(entity !== null).toBeTrue(); expect(meta.entitySet).toEqual('People'); expect(entity).toEqual(trip); }); const req = httpMock.expectOne( `${SERVICE_ROOT}People('russellwhyte')/Trips` ); expect(req.request.method).toBe('POST'); req.flush(data); }); it('should create planItem', () => { const item: PlanItem = { //"@odata.type": "#Microsoft.OData.SampleService.Models.TripPin.Event", ConfirmationCode: '4372899DD', Description: 'Client Meeting', Duration: 'PT3H', EndsAt: new Date('2014-06-01T23:11:17.5479185-07:00'), OccursAt: { '@odata.type': '#Microsoft.OData.SampleService.Models.TripPin.EventLocation', Address: '100 Church Street, 8th Floor, Manhattan, 10007', BuildingInfo: 'Regus Business Center', City: { '@odata.type': '#Microsoft.OData.SampleService.Models.TripPin.City', CountryRegion: 'United States', Name: 'New York City', Region: 'New York', }, }, PlanItemId: 33, StartsAt: new Date('2014-05-25T23:11:17.5459178-07:00'), }; const data = { '@odata.context': "serviceRoot/$metadata#People('russellwhyte')/Trips(1003)/PlanItems/$entity", ...item, }; client .entitySet<Person>('People', `${NAMESPACE}.Person`) .entity('russellwhyte') .navigationProperty<Trip>('Trips') .key(1003) .navigationProperty<PlanItem>('PlanItems') .create(item) .subscribe(({ entity, annots: meta }) => { expect(entity !== null).toBeTrue(); expect(meta.entitySet).toEqual('People'); expect(entity).toEqual(item); }); const req = httpMock.expectOne( `${SERVICE_ROOT}People('russellwhyte')/Trips(1003)/PlanItems` ); expect(req.request.method).toBe('POST'); req.flush(data); }); it('should delete trip', () => { client .entitySet<Person>('People', `${NAMESPACE}.Person`) .entity('russellwhyte') .navigationProperty<Trip>('Trips') .key(1001) .destroy() .subscribe(({ entity, annots: meta }) => { expect(entity).toBeNull(); }); const req = httpMock.expectOne( `${SERVICE_ROOT}People('russellwhyte')/Trips(1001)` ); expect(req.request.method).toBe('DELETE'); req.flush(''); }); it('should execute batch', () => { const payload = { '@odata.context': 'http://services.odata.org/V4/TripPinServiceRW/$metadata#People/$entity', '@odata.id': "http://services.odata.org/V4/TripPinServiceRW/People('russellwhyte')", '@odata.etag': 'W/"08D814450D6BDB6F"', UserName: 'russellwhyte', FirstName: 'Russell', LastName: 'Whyte', Emails: ['Russell@example.com', 'Russell@contoso.com'], }; const data = `--batchresponse_6520643b-3c13-4889-aa60-b4422cf2b82b Content-Type: application/http Content-Transfer-Encoding: binary HTTP/1.1 200 OK Content-Type: application/json; odata.metadata=minimal OData-Version: 4.0 ${JSON.stringify(payload)} --batchresponse_6520643b-3c13-4889-aa60-b4422cf2b82b--`; const entity: ODataEntityResource<Person> = client .entitySet<Person>('People', `${NAMESPACE}.Person`) .entity('russellwhyte'); client .batch() .exec((batch) => { expect(batch.endpointUrl()).toEqual(SERVICE_ROOT + '$batch'); return entity.fetch(); }) .subscribe(({ annots: meta }) => { expect(meta.entitySet).toEqual('People'); expect(meta.etag).toEqual('W/"08D814450D6BDB6F"'); }); const headers = new HttpHeaders({ 'Content-Length': data.length.toString(), 'Content-Type': 'multipart/mixed; boundary=batchresponse_6520643b-3c13-4889-aa60-b4422cf2b82b', }); const req = httpMock.expectOne(`${SERVICE_ROOT}$batch`); expect(req.request.method).toBe('POST'); req.flush(data, { headers }); }); });
the_stack
import threshold_bls from 'blind-threshold-bls' import { BLSCryptographyClient, ServicePartialSignature, } from '../../src/bls/bls-cryptography-client' import config from '../../src/config' const PUBLIC_KEY = '8VZ0ZBPBjeRaH2nE+itNKiL/wKl38foK74MniCCIxvpA/9AfE1Uy7qbGGRyiKj8AAeiFpSaMzi7Flfe/Tj/qCWM8LMgQGR+eTvt7yiYsyKIVpGMJYVyzchEtPwFZyRyA' const PUBLIC_POLYNOMIAL = '0300000000000000f156746413c18de45a1f69c4fa2b4d2a22ffc0a977f1fa0aef8327882088c6fa40ffd01f135532eea6c6191ca22a3f0001e885a5268cce2ec595f7bf4e3fea09633c2cc810191f9e4efb7bca262cc8a215a46309615cb372112d3f0159c91c80ececfb0ecd57116e44c7580b57fe7c3f0f566d65f789f041b9febd83d3497e4c430af250cf8ac135f4782d283f3dd5009cf6e8de23a35be1cc21a8504ee2e3757a36f6c9813137d0f6b8aa75febc5ee77435cfd4280de80647670a60683e9481f091088a9940142b31d42ed3981dd548910fa41364f589c93c87bf62725468779a1442785600c08efbeff391f84e3200560dcd95d055998f4ef803a820356ef5b756cc75a98286bd21b5675cfe2db9bac0bcee64dc94c435d92aa5fbfa118680' const SIGNATURES = [ 'MAAAAAAAAADkHsKIX91BuKRjNgsJR81otwGGln4HuguYe4QkZoInFwNIiU9QglFZeLpJmNEysIAAAAAA', 'MAAAAAAAAABqscf+GUMQD5I8SJW+zzZKuo83gyRZs/RUR7zePSDx4ZtewOGEc/VThpUpqgM5mAEBAAAA', 'MAAAAAAAAABH006sJMay5D4OtOHDdQh3W8gX7yafeyMSGJzba7RhBAWatCEztthuQ6gSEOYTYQECAAAA', 'MAAAAAAAAAAhzTl/S+mldhE+5F5rt+2XKJQsNtELZeo+aoHjhsVVdw8Ofk1ZRr9EUZbvVKetNYADAAAA', ] const COMBINED_SIGNATURE = '16RcENpbLgq5pIkcPWdgnMofeLqSyuUVin9h4jof9/I8GRsmt5iRxjWAkpftKPWA' const INVALID_SIGNATURE = 'MAAAAAAAAACanrA73tApLu+j569ICcXrEBRLi4czWJtInJPSUpoZUOVDc1667hvMq1ESncFzlgEHAAAA' config.thresholdSignature = { threshold: 3, polynomial: PUBLIC_POLYNOMIAL, pubKey: PUBLIC_KEY, } describe(`BLS service computes signature`, () => { it('provides blinded signature', async () => { const signatures: ServicePartialSignature[] = [ { url: 'url1', signature: SIGNATURES[0], }, { url: 'url2', signature: SIGNATURES[1], }, { url: 'url3', signature: SIGNATURES[2], }, { url: 'url4', signature: SIGNATURES[3], }, ] const message = Buffer.from('hello world') const userSeed = new Uint8Array(32) for (let i = 0; i < userSeed.length - 1; i++) { userSeed[i] = i } const blindedMsgResult = threshold_bls.blind(message, userSeed) const blindedMsg = Buffer.from(blindedMsgResult.message).toString('base64') const blsCryptoClient = new BLSCryptographyClient() for (let i = 0; i < signatures.length; i++) { await blsCryptoClient.addSignature(signatures[i]) if (i >= 2) { expect(blsCryptoClient.hasSufficientSignatures()).toBeTruthy() } else { expect(blsCryptoClient.hasSufficientSignatures()).toBeFalsy() } } const actual = await blsCryptoClient.combinePartialBlindedSignatures(blindedMsg) expect(actual).toEqual(COMBINED_SIGNATURE) const unblindedSignedMessage = threshold_bls.unblind( Buffer.from(actual, 'base64'), blindedMsgResult.blindingFactor ) const publicKey = Buffer.from(PUBLIC_KEY, 'base64') expect(threshold_bls.verify(publicKey, message, unblindedSignedMessage)) }) it('provides blinded signature given one failure if still above threshold', async () => { const signatures: ServicePartialSignature[] = [ { url: 'url1', signature: SIGNATURES[0], }, { url: 'url2', signature: 'X', // This input causes signature combination to fail }, { url: 'url3', signature: SIGNATURES[2], }, { url: 'url4', signature: SIGNATURES[3], }, ] const message = Buffer.from('hello world') const userSeed = new Uint8Array(32) for (let i = 0; i < userSeed.length - 1; i++) { userSeed[i] = i } const blindedMsgResult = threshold_bls.blind(message, userSeed) const blindedMsg = Buffer.from(blindedMsgResult.message).toString('base64') const blsCryptoClient = new BLSCryptographyClient() await signatures.forEach(async (signature) => { await blsCryptoClient.addSignature(signature) }) const actual = await blsCryptoClient.combinePartialBlindedSignatures(blindedMsg) expect(actual).toEqual(COMBINED_SIGNATURE) const unblindedSignedMessage = threshold_bls.unblind( Buffer.from(actual, 'base64'), blindedMsgResult.blindingFactor ) const publicKey = Buffer.from(PUBLIC_KEY, 'base64') expect(threshold_bls.verify(publicKey, message, unblindedSignedMessage)) }) it('throws error if does not meet threshold signatures', async () => { const signatures: ServicePartialSignature[] = [ { url: 'url1', signature: SIGNATURES[0], }, { url: 'url2', signature: 'X', }, { url: 'url3', signature: 'X', }, { url: 'url4', signature: SIGNATURES[3], }, ] const message = Buffer.from('hello world') const userSeed = new Uint8Array(32) for (let i = 0; i < userSeed.length - 1; i++) { userSeed[i] = i } const blindedMsgResult = threshold_bls.blind(message, userSeed) const blindedMsg = Buffer.from(blindedMsgResult.message).toString('base64') const blsCryptoClient = new BLSCryptographyClient() await signatures.forEach(async (signature) => { await blsCryptoClient.addSignature(signature) }) try { await blsCryptoClient.combinePartialBlindedSignatures(blindedMsg) throw new Error('Expected failure with missing signatures') } catch (e: any) { expect(e.message.includes('Not enough partial signatures')).toBeTruthy() } }) it('throws error if signature cannot be combined, but can recover from failure with sufficient signatures', async () => { const signatures: ServicePartialSignature[] = [ { url: 'url1', signature: SIGNATURES[0], }, { url: 'url2', signature: 'X', // This input causes signature combination to fail }, { url: 'url3', signature: SIGNATURES[2], }, { url: 'url4', signature: SIGNATURES[3], }, ] const message = Buffer.from('hello world') const userSeed = new Uint8Array(32) for (let i = 0; i < userSeed.length - 1; i++) { userSeed[i] = i } const blindedMsgResult = threshold_bls.blind(message, userSeed) const blindedMsg = Buffer.from(blindedMsgResult.message).toString('base64') const blsCryptoClient = new BLSCryptographyClient() // Add sigs one-by-one and verify intermediary states await blsCryptoClient.addSignature(signatures[0]) expect(blsCryptoClient.hasSufficientSignatures()).toBeFalsy() await blsCryptoClient.addSignature(signatures[1]) expect(blsCryptoClient.hasSufficientSignatures()).toBeFalsy() await blsCryptoClient.addSignature(signatures[2]) expect(blsCryptoClient.hasSufficientSignatures()).toBeTruthy() // Should fail since 1/3 sigs are invalid try { await blsCryptoClient.combinePartialBlindedSignatures(blindedMsg) } catch (e: any) { expect(e.message.includes('Not enough partial signatures')).toBeTruthy() } // Should be false, now that the invalid signature has been removed expect(blsCryptoClient.hasSufficientSignatures()).toBeFalsy() await blsCryptoClient.addSignature(signatures[3]) expect(blsCryptoClient.hasSufficientSignatures()).toBeTruthy() const actual = await blsCryptoClient.combinePartialBlindedSignatures(blindedMsg) expect(actual).toEqual(COMBINED_SIGNATURE) const unblindedSignedMessage = threshold_bls.unblind( Buffer.from(actual, 'base64'), blindedMsgResult.blindingFactor ) const publicKey = Buffer.from(PUBLIC_KEY, 'base64') expect(threshold_bls.verify(publicKey, message, unblindedSignedMessage)) }) it('throws error if combined signature is invalid, and can recover from failure with sufficient valid partial signatures', async () => { const signatures: ServicePartialSignature[] = [ { url: 'url1', signature: SIGNATURES[0], }, { url: 'url2', signature: SIGNATURES[1], }, { url: 'url3', signature: INVALID_SIGNATURE, // Combination will succeed but verification will fail. }, { url: 'url4', signature: SIGNATURES[3], }, ] const message = Buffer.from('hello world') const userSeed = new Uint8Array(32) for (let i = 0; i < userSeed.length - 1; i++) { userSeed[i] = i } const blindedMsgResult = threshold_bls.blind(message, userSeed) const blindedMsg = Buffer.from(blindedMsgResult.message).toString('base64') const blsCryptoClient = new BLSCryptographyClient() // Add sigs one-by-one and verify intermediary states await blsCryptoClient.addSignature(signatures[0]) expect(blsCryptoClient.hasSufficientSignatures()).toBeFalsy() await blsCryptoClient.addSignature(signatures[1]) expect(blsCryptoClient.hasSufficientSignatures()).toBeFalsy() await blsCryptoClient.addSignature(signatures[2]) expect(blsCryptoClient.hasSufficientSignatures()).toBeTruthy() // Should fail since signature from url3 was generated with the wrong key version try { await blsCryptoClient.combinePartialBlindedSignatures(blindedMsg) } catch (e: any) { expect(e.message.includes('Not enough partial signatures')).toBeTruthy() } // Should be false, now that the invalid partial signature has been removed expect(blsCryptoClient.hasSufficientSignatures()).toBeFalsy() await blsCryptoClient.addSignature(signatures[3]) expect(blsCryptoClient.hasSufficientSignatures()).toBeTruthy() const actual = await blsCryptoClient.combinePartialBlindedSignatures(blindedMsg) expect(actual).toEqual(COMBINED_SIGNATURE) const unblindedSignedMessage = threshold_bls.unblind( Buffer.from(actual, 'base64'), blindedMsgResult.blindingFactor ) const publicKey = Buffer.from(PUBLIC_KEY, 'base64') expect(threshold_bls.verify(publicKey, message, unblindedSignedMessage)) }) })
the_stack
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import 'chrome://resources/cr_elements/cr_expand_button/cr_expand_button.m.js'; import 'chrome://resources/cr_elements/policy/cr_policy_pref_indicator.m.js'; import 'chrome://resources/cr_elements/shared_style_css.m.js'; import 'chrome://resources/cr_elements/shared_vars_css.m.js'; import 'chrome://resources/polymer/v3_0/iron-collapse/iron-collapse.js'; import 'chrome://resources/polymer/v3_0/iron-flex-layout/iron-flex-layout-classes.js'; import 'chrome://resources/polymer/v3_0/paper-spinner/paper-spinner-lite.js'; import 'chrome://resources/polymer/v3_0/paper-styles/color.js'; import '../controls/controlled_button.js'; import '../controls/settings_checkbox.js'; import '../prefs/prefs.js'; import '../settings_shared_css.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js'; import {WebUIListenerMixin} from 'chrome://resources/js/web_ui_listener_mixin.js'; import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {SettingsCheckboxElement} from '../controls/settings_checkbox.js'; import {ChromeCleanupProxy, ChromeCleanupProxyImpl} from './chrome_cleanup_proxy.js'; import {ChromeCleanupRemovalListItem} from './items_to_remove_list.js'; /** * The reason why the controller is in state kIdle. * Must be kept in sync with ChromeCleanerController::IdleReason. */ export enum ChromeCleanupIdleReason { INITIAL = 'initial', REPORTER_FOUND_NOTHING = 'reporter_found_nothing', REPORTER_FAILED = 'reporter_failed', SCANNING_FOUND_NOTHING = 'scanning_found_nothing', SCANNING_FAILED = 'scanning_failed', CONNECTION_LOST = 'connection_lost', USER_DECLINED_CLEANUP = 'user_declined_cleanup', CLEANING_FAILED = 'cleaning_failed', CLEANING_SUCCEEDED = 'cleaning_succeeded', CLEANER_DOWNLOAD_FAILED = 'cleaner_download_failed', } /** * The possible states for the cleanup card. */ enum ChromeCleanerCardState { SCANNING_OFFERED = 'scanning_offered', SCANNING = 'scanning', CLEANUP_OFFERED = 'cleanup_offered', CLEANING = 'cleaning', REBOOT_REQUIRED = 'reboot_required', SCANNING_FOUND_NOTHING = 'scanning_found_nothing', SCANNING_FAILED = 'scanning_failed', CLEANUP_SUCCEEDED = 'cleanup_succeeded', CLEANING_FAILED = 'cleanup_failed', CLEANER_DOWNLOAD_FAILED = 'cleaner_download_failed', } /** * Boolean properties for a cleanup card state. */ enum ChromeCleanupCardFlags { NONE = 0, SHOW_LOGS_PERMISSIONS = 1 << 0, WAITING_FOR_RESULT = 1 << 1, SHOW_ITEMS_TO_REMOVE = 1 << 2, } /** * Identifies an ongoing scanning/cleanup action. */ enum ChromeCleanupOngoingAction { NONE = 0, SCANNING = 1, CLEANING = 2, } type ChromeCleanupCardActionButton = { label: string, doAction: () => void, }; type ChromeCleanupCardComponents = { title: string|null, explanation: string|null, actionButton: ChromeCleanupCardActionButton|null, flags: number, }; /** * Represents the file path structure of a base::FilePath. * dirname ends with a separator. */ type ChromeCleanupFilePath = { dirname: string, basename: string, }; type ChromeCleanerScannerResults = { files: Array<ChromeCleanupFilePath>, registryKeys: Array<string>, }; /** * @fileoverview * 'settings-chrome-cleanup-page' is the settings page containing Chrome * Cleanup settings. * * Example: * * <iron-animated-pages> * <settings-chrome-cleanup-page></settings-chrome-cleanup-page> * ... other pages ... * </iron-animated-pages> */ interface SettingsChromeCleanupPageElement { $: { chromeCleanupLogsUploadControl: SettingsCheckboxElement, chromeCleanupShowNotificationControl: SettingsCheckboxElement, }; } const SettingsChromeCleanupPageElementBase = WebUIListenerMixin(I18nMixin(PolymerElement)); class SettingsChromeCleanupPageElement extends SettingsChromeCleanupPageElementBase { static get is() { return 'settings-chrome-cleanup-page'; } static get template() { return html`{__html_template__}`; } static get properties() { return { /** * Preferences state. */ prefs: { type: Object, notify: true, }, title_: { type: String, value: '', }, explanation_: { type: String, value: '', }, isWaitingForResult_: { type: Boolean, value: '', }, showActionButton_: { type: Boolean, value: false, }, cleanupEnabled_: { type: Boolean, value: true, }, actionButtonLabel_: { type: String, value: '', }, showExplanation_: { type: Boolean, computed: 'computeShowExplanation_(explanation_)', }, showLogsPermission_: { type: Boolean, value: false, }, showItemsToRemove_: { type: Boolean, value: false, }, itemsToRemoveSectionExpanded_: { type: Boolean, value: false, observer: 'itemsToRemoveSectionExpandedChanged_', }, showItemsLinkLabel_: { type: String, value: '', }, showingAllFiles_: { type: Boolean, value: false, }, scannerResults_: { type: Object, value() { return {'files': [], 'registryKeys': []}; }, }, hasFilesToShow_: { type: Boolean, computed: 'computeHasFilesToShow_(scannerResults_)', }, hasRegistryKeysToShow_: { type: Boolean, computed: 'computeHasRegistryKeysToShow_(scannerResults_)', }, logsUploadPref_: { type: Object, value() { return {}; }, }, isPoweredByPartner_: { type: Boolean, value: false, }, /** * Virtual pref that's attached to the notification checkbox. */ notificationEnabledPref_: { type: Object, value() { return { type: chrome.settingsPrivate.PrefType.BOOLEAN, value: false, }; }, }, }; } private title_: string; private explanation_: string; private isWaitingForResult_: boolean; private showActionButton_: boolean; private cleanupEnabled_: boolean; private actionButtonLabel_: string; private showExplanation_: boolean; private showLogsPermission_: boolean; private showNotificationPermission_: boolean; private showItemsToRemove_: boolean; private itemsToRemoveSectionExpanded_: boolean; private showItemsLinkLabel_: string; private showingAllFiles_: boolean; private scannerResults_: ChromeCleanerScannerResults; private hasFilesToShow_: boolean; private hasRegistryKeysToShow_: boolean; private logsUploadPref_: chrome.settingsPrivate.PrefObject; private isPoweredByPartner_: boolean; private notificationEnabledPref_: chrome.settingsPrivate.PrefObject; private emptyChromeCleanerScannerResults_: ChromeCleanerScannerResults = {files: [], registryKeys: []}; private browserProxy_: ChromeCleanupProxy = ChromeCleanupProxyImpl.getInstance(); private doAction_: (() => void)|null = null; private cardStateToComponentsMap_: Map<ChromeCleanerCardState, ChromeCleanupCardComponents>|null = null; private ongoingAction_: ChromeCleanupOngoingAction = ChromeCleanupOngoingAction.NONE; private renderScanOfferedByDefault_: boolean; constructor() { super(); /** * If true; the scan offered view is rendered on state idle, regardless of * the idle reason received from the cleaner controller. The goal is to * ignore previous interactions (such as completed cleanups) performed on * other tabs or if this tab is reloaded. * Set to false whenever there is a transition to a non-idle state while the * current tab is open. */ this.renderScanOfferedByDefault_ = true; } connectedCallback() { super.connectedCallback(); this.cardStateToComponentsMap_ = this.buildCardStateToComponentsMap_(); this.addWebUIListener( 'chrome-cleanup-on-idle', (idleReason: string) => this.onIdle_(idleReason)); this.addWebUIListener( 'chrome-cleanup-on-scanning', () => this.onScanning_()); // Note: both reporter running and scanning share the same UI. this.addWebUIListener( 'chrome-cleanup-on-reporter-running', () => this.onScanning_()); this.addWebUIListener( 'chrome-cleanup-on-infected', (isPoweredByPartner: boolean, scannerResults: ChromeCleanerScannerResults) => this.onInfected_(isPoweredByPartner, scannerResults)); this.addWebUIListener( 'chrome-cleanup-on-cleaning', (isPoweredByPartner: boolean, scannerResults: ChromeCleanerScannerResults) => this.onCleaning_(isPoweredByPartner, scannerResults)); this.addWebUIListener( 'chrome-cleanup-on-reboot-required', () => this.onRebootRequired_()); this.addWebUIListener( 'chrome-cleanup-enabled-change', (enabled: boolean) => this.onCleanupEnabledChange_(enabled)); this.browserProxy_.registerChromeCleanerObserver(); } /** * Implements the action for the only visible button in the UI, which can be * either to start an action such as a cleanup or to restart the computer. */ private proceed_() { this.doAction_!(); } /** * Notifies Chrome that the details section was opened or closed. */ private itemsToRemoveSectionExpandedChanged_( newVal: boolean, oldVal: boolean) { if (!oldVal && newVal) { this.browserProxy_.notifyShowDetails(this.itemsToRemoveSectionExpanded_); } } private computeShowExplanation_(explanation: string): boolean { return explanation !== ''; } /** * @param scannerResults The cleanup items to be presented to the user. * @return Whether there are files to show to the user. */ private computeHasFilesToShow_(scannerResults: ChromeCleanerScannerResults): boolean { return scannerResults.files.length > 0; } /** * @param scannerResults The cleanup items to be presented to the user. * @return Whether user-initiated cleanups are enabled and there are registry * keys to show to the user. */ private computeHasRegistryKeysToShow_( scannerResults: ChromeCleanerScannerResults): boolean { return scannerResults.registryKeys.length > 0; } /** * Listener of event 'chrome-cleanup-on-idle'. */ private onIdle_(idleReason: string) { const lastAction = this.ongoingAction_; this.ongoingAction_ = ChromeCleanupOngoingAction.NONE; this.scannerResults_ = this.emptyChromeCleanerScannerResults_; // Ignore the idle reason and render the scan offered view if no // interaction happened on this tab. if (this.renderScanOfferedByDefault_) { idleReason = ChromeCleanupIdleReason.INITIAL; } switch (idleReason) { case ChromeCleanupIdleReason.INITIAL: this.renderCleanupCard_(ChromeCleanerCardState.SCANNING_OFFERED); break; case ChromeCleanupIdleReason.SCANNING_FOUND_NOTHING: case ChromeCleanupIdleReason.REPORTER_FOUND_NOTHING: this.renderCleanupCard_(ChromeCleanerCardState.SCANNING_FOUND_NOTHING); break; case ChromeCleanupIdleReason.SCANNING_FAILED: case ChromeCleanupIdleReason.REPORTER_FAILED: this.renderCleanupCard_(ChromeCleanerCardState.SCANNING_FAILED); break; case ChromeCleanupIdleReason.CONNECTION_LOST: if (lastAction === ChromeCleanupOngoingAction.SCANNING) { this.renderCleanupCard_(ChromeCleanerCardState.SCANNING_FAILED); } else { assert(lastAction === ChromeCleanupOngoingAction.CLEANING); this.renderCleanupCard_(ChromeCleanerCardState.CLEANING_FAILED); } break; case ChromeCleanupIdleReason.CLEANING_FAILED: case ChromeCleanupIdleReason.USER_DECLINED_CLEANUP: this.renderCleanupCard_(ChromeCleanerCardState.CLEANING_FAILED); break; case ChromeCleanupIdleReason.CLEANING_SUCCEEDED: this.renderCleanupCard_(ChromeCleanerCardState.CLEANUP_SUCCEEDED); break; case ChromeCleanupIdleReason.CLEANER_DOWNLOAD_FAILED: this.renderCleanupCard_(ChromeCleanerCardState.CLEANER_DOWNLOAD_FAILED); break; default: assert(false, `Unknown idle reason: ${idleReason}`); } } /** * Listener of event 'chrome-cleanup-on-scanning'. * No UI will be shown in the Settings page on that state, simply hide the * card and cleanup this element's fields. */ private onScanning_() { this.ongoingAction_ = ChromeCleanupOngoingAction.SCANNING; this.scannerResults_ = this.emptyChromeCleanerScannerResults_; this.renderScanOfferedByDefault_ = false; this.renderCleanupCard_(ChromeCleanerCardState.SCANNING); } /** * Listener of event 'chrome-cleanup-on-infected'. * Offers a cleanup to the user and enables presenting files to be removed. * @param isPoweredByPartner If scanning results are provided by a partner's * engine. * @param scannerResults The cleanup items to be presented to the user. */ private onInfected_( isPoweredByPartner: boolean, scannerResults: ChromeCleanerScannerResults) { this.isPoweredByPartner_ = isPoweredByPartner; this.ongoingAction_ = ChromeCleanupOngoingAction.NONE; this.renderScanOfferedByDefault_ = false; this.scannerResults_ = scannerResults; this.updateShowItemsLinklabel_(); this.renderCleanupCard_(ChromeCleanerCardState.CLEANUP_OFFERED); } /** * Listener of event 'chrome-cleanup-on-cleaning'. * Shows a spinner indicating that an on-going action and enables presenting * files to be removed. * @param isPoweredByPartner If scanning results are provided by a partner's * engine. * @param scannerResults The cleanup items to be presented to the user. */ private onCleaning_( isPoweredByPartner: boolean, scannerResults: ChromeCleanerScannerResults) { this.isPoweredByPartner_ = isPoweredByPartner; this.ongoingAction_ = ChromeCleanupOngoingAction.CLEANING; this.renderScanOfferedByDefault_ = false; this.scannerResults_ = scannerResults; this.updateShowItemsLinklabel_(); this.renderCleanupCard_(ChromeCleanerCardState.CLEANING); } /** * Listener of event 'chrome-cleanup-on-reboot-required'. * No UI will be shown in the Settings page on that state, so we simply hide * the card and cleanup this element's fields. */ private onRebootRequired_() { this.ongoingAction_ = ChromeCleanupOngoingAction.NONE; this.scannerResults_ = this.emptyChromeCleanerScannerResults_; this.renderScanOfferedByDefault_ = false; this.renderCleanupCard_(ChromeCleanerCardState.REBOOT_REQUIRED); } /** * Renders the cleanup card given the state and list of files. * @param state The card state to be rendered. */ private renderCleanupCard_(state: ChromeCleanerCardState) { const components = this.cardStateToComponentsMap_!.get(state); assert(components); this.title_ = components!.title || ''; this.explanation_ = components!.explanation || ''; this.updateActionButton_(components!.actionButton); this.updateCardFlags_(components!.flags); } /** * Updates the action button on the cleanup card as the action expected for * the current state. * @param actionButton The button to render, or null if no button should be * shown. */ private updateActionButton_(actionButton: ChromeCleanupCardActionButton| null) { if (!actionButton) { this.showActionButton_ = false; this.actionButtonLabel_ = ''; this.doAction_ = null; } else { this.showActionButton_ = true; this.actionButtonLabel_ = actionButton.label; this.doAction_ = actionButton.doAction; } } /** * Updates boolean flags corresponding to optional components to be rendered * on the card. * @param flags Flags indicating optional components to be rendered. */ private updateCardFlags_(flags: number) { this.showLogsPermission_ = (flags & ChromeCleanupCardFlags.SHOW_LOGS_PERMISSIONS) !== 0; this.isWaitingForResult_ = (flags & ChromeCleanupCardFlags.WAITING_FOR_RESULT) !== 0; this.showItemsToRemove_ = (flags & ChromeCleanupCardFlags.SHOW_ITEMS_TO_REMOVE) !== 0; // Files to remove list should only be expandable if details are being // shown, otherwise it will add extra padding at the bottom of the card. if (!this.showExplanation_ || !this.showItemsToRemove_) { this.itemsToRemoveSectionExpanded_ = false; } } /** * @param enabled Whether cleanup is enabled. */ private onCleanupEnabledChange_(enabled: boolean) { this.cleanupEnabled_ = enabled; } /** * Sends an action to the browser proxy to start scanning. */ private startScanning_() { this.browserProxy_.startScanning( this.$.chromeCleanupLogsUploadControl.checked); } /** * Sends an action to the browser proxy to start the cleanup. */ private startCleanup_() { this.browserProxy_.startCleanup( this.$.chromeCleanupLogsUploadControl.checked); } /** * Sends an action to the browser proxy to restart the machine. */ private restartComputer_() { this.browserProxy_.restartComputer(); } /** * Updates the label for the collapsed detailed view. If user-initiated * cleanups are enabled, the string is obtained from the browser proxy, * since it may require a plural version. Otherwise, use the default value * for |chromeCleanupLinkShowItems|. */ private updateShowItemsLinklabel_() { const setShowItemsLabel = (text: string) => this.showItemsLinkLabel_ = text; this.browserProxy_ .getItemsToRemovePluralString( this.scannerResults_.files.length + this.scannerResults_.registryKeys.length) .then(setShowItemsLabel); } /** * @return The map of card states to components to be rendered. */ private buildCardStateToComponentsMap_(): Map<ChromeCleanerCardState, ChromeCleanupCardComponents> { /** * The action buttons to show on the card. * @enum {ChromeCleanupCardActionButton} */ const actionButtons = { FIND: { label: this.i18n('chromeCleanupFindButtonLabel'), doAction: () => this.startScanning_(), }, REMOVE: { label: this.i18n('chromeCleanupRemoveButtonLabel'), doAction: () => this.startCleanup_(), }, RESTART_COMPUTER: { label: this.i18n('chromeCleanupRestartButtonLabel'), doAction: () => this.restartComputer_(), }, TRY_SCAN_AGAIN: { label: this.i18n('chromeCleanupTitleTryAgainButtonLabel'), // TODO(crbug.com/776538): do not run the reporter component again. // Try downloading the cleaner and scan with it instead. doAction: () => this.startScanning_(), }, }; return new Map([ [ ChromeCleanerCardState.CLEANUP_OFFERED, { title: this.i18n('chromeCleanupTitleRemove'), explanation: this.i18n('chromeCleanupExplanationRemove'), actionButton: actionButtons.REMOVE, flags: ChromeCleanupCardFlags.SHOW_LOGS_PERMISSIONS | ChromeCleanupCardFlags.SHOW_ITEMS_TO_REMOVE, } ], [ ChromeCleanerCardState.CLEANING, { title: this.i18n('chromeCleanupTitleRemoving'), explanation: this.i18n('chromeCleanupExplanationRemoving'), actionButton: null, flags: ChromeCleanupCardFlags.WAITING_FOR_RESULT | ChromeCleanupCardFlags.SHOW_ITEMS_TO_REMOVE, } ], [ ChromeCleanerCardState.REBOOT_REQUIRED, { title: this.i18n('chromeCleanupTitleRestart'), explanation: null, actionButton: actionButtons.RESTART_COMPUTER, flags: ChromeCleanupCardFlags.NONE, } ], [ ChromeCleanerCardState.CLEANUP_SUCCEEDED, { title: this.i18nAdvanced('chromeCleanupTitleRemoved', {tags: ['a']}), explanation: null, actionButton: null, flags: ChromeCleanupCardFlags.NONE, } ], [ ChromeCleanerCardState.CLEANING_FAILED, { title: this.i18n('chromeCleanupTitleErrorCantRemove'), explanation: this.i18n('chromeCleanupExplanationCleanupError'), actionButton: null, flags: ChromeCleanupCardFlags.NONE, } ], [ ChromeCleanerCardState.SCANNING_OFFERED, { title: this.i18n('chromeCleanupTitleFindAndRemove'), explanation: this.i18n('chromeCleanupExplanationFindAndRemove'), actionButton: actionButtons.FIND, flags: ChromeCleanupCardFlags.SHOW_LOGS_PERMISSIONS, } ], [ ChromeCleanerCardState.SCANNING, { title: this.i18n('chromeCleanupTitleScanning'), explanation: null, actionButton: null, flags: ChromeCleanupCardFlags.WAITING_FOR_RESULT, } ], [ // TODO(crbug.com/776538): Could we offer to reset settings here? ChromeCleanerCardState.SCANNING_FOUND_NOTHING, { title: this.i18n('chromeCleanupTitleNothingFound'), explanation: null, actionButton: null, flags: ChromeCleanupCardFlags.NONE, } ], [ ChromeCleanerCardState.SCANNING_FAILED, { title: this.i18n('chromeCleanupTitleScanningFailed'), explanation: this.i18n('chromeCleanupExplanationScanError'), actionButton: null, flags: ChromeCleanupCardFlags.NONE, } ], [ ChromeCleanerCardState.CLEANER_DOWNLOAD_FAILED, { // TODO(crbug.com/776538): distinguish between missing network // connectivity and cleanups being disabled by the server. title: this.i18n('chromeCleanupTitleCleanupUnavailable'), explanation: this.i18n('chromeCleanupExplanationCleanupUnavailable'), actionButton: actionButtons.TRY_SCAN_AGAIN, flags: ChromeCleanupCardFlags.NONE, }, ], ]); } private getListEntriesFromStrings_(list: Array<string>): Array<ChromeCleanupRemovalListItem> { return list.map(entry => ({text: entry, highlightSuffix: null})); } private getListEntriesFromFilePaths_(paths: Array<ChromeCleanupFilePath>): Array<ChromeCleanupRemovalListItem> { return paths.map( path => ({text: path.dirname, highlightSuffix: path.basename})); } } customElements.define( SettingsChromeCleanupPageElement.is, SettingsChromeCleanupPageElement);
the_stack
import { Map } from 'immutable'; import { PortRecord } from '../../constants/flowdesigner.model'; import * as Port from './port'; import * as Position from '../position/position'; describe('isPortElseThrow', () => { it('return true if given parameter is a PortRecord', () => { // given const testPort = new PortRecord(); // when const test = Port.isPortElseThrow(testPort); // expect expect(test).toEqual(true); }); it('throw if given parameter is not a PortRecord', () => { // given const testPort = Map(); // when // expect expect(() => Port.isPortElseThrow(testPort)).toThrow(); }); }); describe('isTopologyElseThrow', () => { it('return true if given parameter is a valid Topology', () => { expect(Port.isTopologyElseThrow('INCOMING')).toBe(true); }); it('throw if given parameter is not a valid Topology and doThrow is true', () => { const invalidtopology = 'LOOKUP'; expect(() => Port.isTopologyElseThrow('LOOKUP')).toThrow( `Should be a topology 'OUTGOING' or 'INCOMING', was given ${invalidtopology}`, ); }); }); describe('port api', () => { const id = 'ID'; const nodeId = 'NODE_ID'; const position = Position.create(10, 10); const index = 1; const topology = 'OUTGOING'; const portType = 'PortType'; const testPort = Port.create(id, nodeId, index, topology, portType); const key = 'KEY'; const value = { whatever: 'whatever' }; const improperId = 34; const improperNodeId = 42; const improperIndex = '10'; const impropertopology = {}; const improperPosition = Map({ x: 10, y: 10 }); const improperPortType = {}; const improperPort = Map(); describe('create', () => { it('given proper id, nodeId, index, topology and componentType return a Node', () => { // given // when const test = Port.create(id, nodeId, index, topology, portType); // expect expect(Port.isPort(test)).toEqual(true); }); it('throw if given an improper id', () => { // given // when // expect expect(() => Port.create(improperId as any, nodeId, index, topology, portType), ).toThrow(); }); it('throw if given an improper NodeId', () => { // given // when // expect expect(() => Port.create(id, improperNodeId as any, index, topology, portType), ).toThrow(); }); it('throw if given an improper index', () => { // given // when // expect expect(() => Port.create(id, nodeId, improperIndex as any, topology, portType), ).toThrow(); }); it('throw if given an improper topology', () => { // given // when // expect expect(() => Port.create(id, nodeId, index, impropertopology as any, portType), ).toThrow(); }); it('throw if given an improper componentType', () => { // given // when // expect expect(() => Port.create(id, nodeId, index, topology, improperPortType as any), ).toThrow(); }); }); describe('isPort', () => { it('return true if given parameter is a PortRecord', () => { // given // when const test = Port.isPort(testPort); // expect expect(test).toBe(true); }); it('return false if given parameter is not a PortRecord', () => { // given // when const test = Port.isPort(improperPort); // expect expect(test).toEqual(false); }); }); describe('getId', () => { it('given a proper Node return an Id', () => { // given // when const test = Port.getId(testPort); // expect expect(test).toEqual(id); }); it('throw given an improper Port', () => { expect(() => Port.getId(improperPort)).toThrow(); }); }); describe('getNodeId', () => { it('given a proper Port return a NodeId', () => { // given // when const test = Port.getNodeId(testPort); // expect expect(test).toEqual(nodeId); }); it('throw given an improper Port', () => { expect(() => Port.getId(improperPort)).toThrow(); }); }); describe('setNodeId', () => { it('given a proper Port and NodeId return a Port with updated NodeId', () => { // given const newNodeId = 'NEW_NODE_ID'; // when const test = Port.setNodeId(newNodeId, testPort); // expect expect(Port.getNodeId(test)).toEqual(newNodeId); }); it('throw given an improper NodeId', () => { // given // when // expect expect(() => Port.setNodeId(improperNodeId as any, testPort)).toThrow(); }); it('throw given an improper Port', () => { // given // when // expect expect(() => Port.setNodeId(nodeId, improperPort)).toThrow(); }); }); describe('getComponentType', () => { it('given a proper Port return a ComponentType', () => { // given // when const test = Port.getComponentType(testPort); // expect expect(test).toEqual(portType); }); it('throw given an improper Port', () => { expect(() => Port.getComponentType(improperPort)).toThrow(); }); }); describe('setComponentType', () => { it('given a proper Port and ComponentType return a Port with updated ComponentType', () => { // given const newComponentType = 'NEW_COMPONENT_TYPE'; // when const test = Port.setComponentType(newComponentType, testPort); // expect expect(Port.getComponentType(test)).toEqual(newComponentType); }); it('throw given an improper ComponentType', () => { // given // when // expect expect(() => Port.setComponentType(improperNodeId as any, testPort)).toThrow(); }); it('throw given an improper Port', () => { // given // when // expect expect(() => Port.setComponentType(portType, improperPort)).toThrow(); }); }); describe('getPosition', () => { it('given a proper Port return a Position', () => { // given // when const test = Port.getPosition(Port.setPosition(position, testPort)); // expect expect(test).toEqual(position); }); it('throw given an improper Port', () => { expect(() => Port.getPosition(improperPortType)).toThrow(); }); }); describe('setPosition', () => { it('given a proper Port and Position return a Port with updated Position', () => { // given const newPosition = Position.create(42, 24); // when const test = Port.setPosition(newPosition, testPort); // expect expect(Port.getPosition(test)).toEqual(newPosition); }); it('throw given an improper position', () => { // given // when // expect expect(() => Port.setPosition(improperPosition as any, testPort)).toThrow(); }); it('throw given an improper Port', () => { // given // when // expect expect(() => Port.setPosition(position, improperPort)).toThrow(); }); }); describe('getTopology', () => { it('given a proper Port return a topology', () => { // given // when const test = Port.getTopology(testPort); // expect expect(test).toEqual(topology); }); it('throw given an improper Port', () => { expect(() => Port.getTopology(improperPort)).toThrow(); }); }); describe('setTopology', () => { it('given a proper Port and topology return a Port with updated topology', () => { // given const newTopology = 'INCOMING'; // when const test = Port.setTopology(newTopology, testPort); // expect expect(Port.getTopology(test)).toEqual(newTopology); }); it('throw given an improper topology', () => { // given // when // expect expect(() => Port.setTopology(impropertopology as any, testPort)).toThrow(); }); it('throw given an improper Port', () => { // given // when // expect expect(() => Port.setTopology(topology, improperPort)).toThrow(); }); }); describe('getIndex', () => { it('given a proper Port return an index', () => { // given // when const test = Port.getIndex(testPort); // expect expect(test).toEqual(index); }); it('throw given an improper Port', () => { expect(() => Port.getIndex(improperPort)).toThrow(); }); }); describe('setIndex', () => { it('given a proper Port and Index return a Port with updated Index', () => { // given const newIndex = 64; // when const test = Port.setIndex(newIndex, testPort); // expect expect(Port.getIndex(test)).toEqual(newIndex); }); it('throw given an improper index', () => { // given // when // expect expect(() => Port.setTopology(improperIndex, testPort)).toThrow(); }); it('throw given an improper Port', () => { // given // when // expect expect(() => Port.setTopology(topology, improperPort)).toThrow(); }); }); describe('setData', () => { it('given a proper key, value and port return said port with the new key/value', () => { // given const newKey = 'newKey'; const newValue = 'newValue'; // when const test = Port.setData(newKey, newValue, testPort); // expect expect(Port.getData(newKey, test)).toEqual(newValue); }); it('throw given an improper key', () => { // given const improperKey = 12; // when // expect expect(() => Port.setData(improperKey as any, value, testPort)).toThrow(); }); it('throw given an improper port', () => { // given // when // expect expect(() => Port.setData(key, value, improperPort)).toThrow(); }); }); describe('getData', () => { it('given a proper key and port return value associated with the key', () => { // given const newKey = 'newKey'; const newValue = 'newValue'; const preparedPort = Port.setData(newKey, newValue, testPort); // when const test = Port.getData(newKey, preparedPort); // expect expect(test).toEqual(newValue); }); it('throw given an improper key', () => { // given const improperKey = 12; // when // expect expect(() => Port.getData(improperKey as any, testPort)).toThrow(); }); it('throw given an improper port', () => { // given // when // expect expect(() => Port.getData(key, improperPort)).toThrow(); }); }); describe('hasData', () => { it('given a proper key and port return true if key exist', () => { // given const newKey = 'newKey'; const newValue = 'newValue'; const preparedPort = Port.setData(newKey, newValue, testPort); // when const test = Port.hasData(newKey, preparedPort); // expect expect(test).toEqual(true); }); it('throw given an improper key', () => { // given const improperKey = 12; // when // expect expect(() => Port.hasData(improperKey as any, testPort)).toThrow(); }); it('throw given an improper port', () => { // given // when // expect expect(() => Port.hasData(key, improperPort)).toThrow(); }); }); describe('deleteData', () => { it('given a proper key and port return port without the key in data property if key exist', () => { // given const newKey = 'newKey'; const newValue = 'newValue'; const preparedPort = Port.setData(newKey, newValue, testPort); // when const test = Port.deleteData(newKey, preparedPort); // expect expect(Port.hasData(newKey, test)).toEqual(false); }); it('throw given an improper key', () => { // given const improperKey = 12; // when // expect expect(() => Port.deleteData(improperKey as any, testPort)).toThrow(); }); it('throw given an improper port', () => { // given // when // expect expect(() => Port.deleteData(key, improperPort)).toThrow(); }); }); describe('setGraphicalAttribute', () => { it('given a proper key, value and port return said port with the new key/value', () => { // given const newKey = 'newKey'; const newValue = 'newValue'; // when const test = Port.setGraphicalAttribute(newKey, newValue, testPort); // expect expect(Port.getGraphicalAttribute(newKey, test)).toEqual(newValue); }); it('throw given a key being part of FORBIDEN_GRAPHICAL_ATTRIBUTES', () => { // given const improperNewKey = 'portType'; const newValue = 'newValue'; // when // expect expect(() => Port.setGraphicalAttribute(improperNewKey, newValue, testPort)).toThrow(); }); it('throw given an improper key', () => { // given const improperKey = 12; // when // expect expect(() => Port.setGraphicalAttribute(improperKey as any, value, testPort)).toThrow(); }); it('throw given an improper port', () => { // given // when // expect expect(() => Port.setGraphicalAttribute(key, value, improperPort)).toThrow(); }); }); describe('getGraphicalAttribute', () => { it('given a proper key and port return value associated with the key', () => { // given const newKey = 'newKey'; const newValue = 'newValue'; const preparedPort = Port.setGraphicalAttribute(newKey, newValue, testPort); // when const test = Port.getGraphicalAttribute(newKey, preparedPort); // expect expect(test).toEqual(newValue); }); it('throw given a key being part of FORBIDEN_GRAPHICAL_ATTRIBUTES', () => { // given const improperNewKey = 'portType'; // when // expect expect(() => Port.getGraphicalAttribute(improperNewKey, testPort)).toThrow(); }); it('throw given an improper key', () => { // given const improperKey = 12; // when // expect expect(() => Port.getGraphicalAttribute(improperKey as any, testPort)).toThrow(); }); it('throw given an improper port', () => { // given // when // expect expect(() => Port.getGraphicalAttribute(key, improperPort)).toThrow(); }); }); describe('hasGraphicalAttribute', () => { it('given a proper key and port return true if key exist', () => { // given const newKey = 'newKey'; const newValue = 'newValue'; const preparedPort = Port.setGraphicalAttribute(newKey, newValue, testPort); // when const test = Port.hasGraphicalAttribute(newKey, preparedPort); // expect expect(test).toEqual(true); }); it('throw given a key being part of FORBIDEN_GRAPHICAL_ATTRIBUTES', () => { // given const improperKey = 'portType'; // when // expect expect(() => Port.hasGraphicalAttribute(improperKey, testPort)).toThrow(); }); it('throw given an improper key', () => { // given const improperKey = 12; // when // expect expect(() => Port.hasGraphicalAttribute(improperKey as any, testPort)).toThrow(); }); it('throw given an improper port', () => { // given // when // expect expect(() => Port.hasGraphicalAttribute(key, improperPort)).toThrow(); }); }); describe('deleteGraphicalAttribute', () => { it('given a proper key and port return port without the key in data property if key exist', () => { // given const newKey = 'newKey'; const newValue = 'newValue'; const preparedPort = Port.setGraphicalAttribute(newKey, newValue, testPort); // when const test = Port.deleteGraphicalAttribute(newKey, preparedPort); // expect expect(Port.hasGraphicalAttribute(newKey, test)).toEqual(false); }); it('throw given a key being part of FORBIDEN_GRAPHICAL_ATTRIBUTES', () => { // given const improperKey = 'portType'; // when // expect expect(() => Port.deleteGraphicalAttribute(improperKey, testPort)).toThrow(); }); it('throw given an improper key', () => { // given const improperKey = 12; // when // expect expect(() => Port.deleteGraphicalAttribute(improperKey as any, testPort)).toThrow(); }); it('throw given an improper port', () => { // given // when // expect expect(() => Port.deleteGraphicalAttribute(key, improperPort)).toThrow(); }); }); });
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/sourceControlSyncJobOperationsMappers"; import * as Parameters from "../models/parameters"; import { AutomationClientContext } from "../automationClientContext"; /** Class representing a SourceControlSyncJobOperations. */ export class SourceControlSyncJobOperations { private readonly client: AutomationClientContext; /** * Create a SourceControlSyncJobOperations. * @param {AutomationClientContext} client Reference to the service client. */ constructor(client: AutomationClientContext) { this.client = client; } /** * Creates the sync job for a source control. * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param sourceControlName The source control name. * @param sourceControlSyncJobId The source control sync job id. * @param parameters The parameters supplied to the create source control sync job operation. * @param [options] The optional parameters * @returns Promise<Models.SourceControlSyncJobCreateResponse> */ create(resourceGroupName: string, automationAccountName: string, sourceControlName: string, sourceControlSyncJobId: string, parameters: Models.SourceControlSyncJobCreateParameters, options?: msRest.RequestOptionsBase): Promise<Models.SourceControlSyncJobCreateResponse>; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param sourceControlName The source control name. * @param sourceControlSyncJobId The source control sync job id. * @param parameters The parameters supplied to the create source control sync job operation. * @param callback The callback */ create(resourceGroupName: string, automationAccountName: string, sourceControlName: string, sourceControlSyncJobId: string, parameters: Models.SourceControlSyncJobCreateParameters, callback: msRest.ServiceCallback<Models.SourceControlSyncJob>): void; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param sourceControlName The source control name. * @param sourceControlSyncJobId The source control sync job id. * @param parameters The parameters supplied to the create source control sync job operation. * @param options The optional parameters * @param callback The callback */ create(resourceGroupName: string, automationAccountName: string, sourceControlName: string, sourceControlSyncJobId: string, parameters: Models.SourceControlSyncJobCreateParameters, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SourceControlSyncJob>): void; create(resourceGroupName: string, automationAccountName: string, sourceControlName: string, sourceControlSyncJobId: string, parameters: Models.SourceControlSyncJobCreateParameters, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SourceControlSyncJob>, callback?: msRest.ServiceCallback<Models.SourceControlSyncJob>): Promise<Models.SourceControlSyncJobCreateResponse> { return this.client.sendOperationRequest( { resourceGroupName, automationAccountName, sourceControlName, sourceControlSyncJobId, parameters, options }, createOperationSpec, callback) as Promise<Models.SourceControlSyncJobCreateResponse>; } /** * Retrieve the source control sync job identified by job id. * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param sourceControlName The source control name. * @param sourceControlSyncJobId The source control sync job id. * @param [options] The optional parameters * @returns Promise<Models.SourceControlSyncJobGetResponse> */ get(resourceGroupName: string, automationAccountName: string, sourceControlName: string, sourceControlSyncJobId: string, options?: msRest.RequestOptionsBase): Promise<Models.SourceControlSyncJobGetResponse>; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param sourceControlName The source control name. * @param sourceControlSyncJobId The source control sync job id. * @param callback The callback */ get(resourceGroupName: string, automationAccountName: string, sourceControlName: string, sourceControlSyncJobId: string, callback: msRest.ServiceCallback<Models.SourceControlSyncJobById>): void; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param sourceControlName The source control name. * @param sourceControlSyncJobId The source control sync job id. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, automationAccountName: string, sourceControlName: string, sourceControlSyncJobId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SourceControlSyncJobById>): void; get(resourceGroupName: string, automationAccountName: string, sourceControlName: string, sourceControlSyncJobId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SourceControlSyncJobById>, callback?: msRest.ServiceCallback<Models.SourceControlSyncJobById>): Promise<Models.SourceControlSyncJobGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, automationAccountName, sourceControlName, sourceControlSyncJobId, options }, getOperationSpec, callback) as Promise<Models.SourceControlSyncJobGetResponse>; } /** * Retrieve a list of source control sync jobs. * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param sourceControlName The source control name. * @param [options] The optional parameters * @returns Promise<Models.SourceControlSyncJobListByAutomationAccountResponse> */ listByAutomationAccount(resourceGroupName: string, automationAccountName: string, sourceControlName: string, options?: Models.SourceControlSyncJobListByAutomationAccountOptionalParams): Promise<Models.SourceControlSyncJobListByAutomationAccountResponse>; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param sourceControlName The source control name. * @param callback The callback */ listByAutomationAccount(resourceGroupName: string, automationAccountName: string, sourceControlName: string, callback: msRest.ServiceCallback<Models.SourceControlSyncJobListResult>): void; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param sourceControlName The source control name. * @param options The optional parameters * @param callback The callback */ listByAutomationAccount(resourceGroupName: string, automationAccountName: string, sourceControlName: string, options: Models.SourceControlSyncJobListByAutomationAccountOptionalParams, callback: msRest.ServiceCallback<Models.SourceControlSyncJobListResult>): void; listByAutomationAccount(resourceGroupName: string, automationAccountName: string, sourceControlName: string, options?: Models.SourceControlSyncJobListByAutomationAccountOptionalParams | msRest.ServiceCallback<Models.SourceControlSyncJobListResult>, callback?: msRest.ServiceCallback<Models.SourceControlSyncJobListResult>): Promise<Models.SourceControlSyncJobListByAutomationAccountResponse> { return this.client.sendOperationRequest( { resourceGroupName, automationAccountName, sourceControlName, options }, listByAutomationAccountOperationSpec, callback) as Promise<Models.SourceControlSyncJobListByAutomationAccountResponse>; } /** * Retrieve a list of source control sync jobs. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.SourceControlSyncJobListByAutomationAccountNextResponse> */ listByAutomationAccountNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.SourceControlSyncJobListByAutomationAccountNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByAutomationAccountNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.SourceControlSyncJobListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByAutomationAccountNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SourceControlSyncJobListResult>): void; listByAutomationAccountNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SourceControlSyncJobListResult>, callback?: msRest.ServiceCallback<Models.SourceControlSyncJobListResult>): Promise<Models.SourceControlSyncJobListByAutomationAccountNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByAutomationAccountNextOperationSpec, callback) as Promise<Models.SourceControlSyncJobListByAutomationAccountNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const createOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/sourceControls/{sourceControlName}/sourceControlSyncJobs/{sourceControlSyncJobId}", urlParameters: [ Parameters.resourceGroupName, Parameters.automationAccountName, Parameters.sourceControlName, Parameters.sourceControlSyncJobId, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion1 ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.SourceControlSyncJobCreateParameters, required: true } }, responses: { 201: { bodyMapper: Mappers.SourceControlSyncJob }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/sourceControls/{sourceControlName}/sourceControlSyncJobs/{sourceControlSyncJobId}", urlParameters: [ Parameters.resourceGroupName, Parameters.automationAccountName, Parameters.sourceControlName, Parameters.sourceControlSyncJobId, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion1 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SourceControlSyncJobById }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByAutomationAccountOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/sourceControls/{sourceControlName}/sourceControlSyncJobs", urlParameters: [ Parameters.resourceGroupName, Parameters.automationAccountName, Parameters.sourceControlName, Parameters.subscriptionId ], queryParameters: [ Parameters.filter, Parameters.apiVersion1 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SourceControlSyncJobListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByAutomationAccountNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SourceControlSyncJobListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer };
the_stack
import { isArray, isBlank, isBoolean, isDate, isEmpty, isFunction, isNumber, isObject, isPresent, isPromise, isString, } from '../../guards' import { Empty } from '../../guards/types' // tslint:disable:no-magic-numbers // tslint:disable-next-line:no-empty const noop = () => {} const emptyArr = [] as any[] const emptyObj = {} describe(`type guards`, () => { describe(`isArray`, () => { it(`should return true if value is an Array`, () => { expect(isArray(123)).toBe(false) expect(isArray(emptyObj)).toBe(false) expect(isArray({ one: 1 })).toBe(false) expect(isArray(emptyArr)).toBe(true) expect(isArray([1, 2, 3])).toBe(true) const arrWithTypes = [1, 2, 3] as number[] | string const arrWithComplexTypes = [{ who: 'Me' }] as | Array<{ who: string }> | string if (isArray(arrWithTypes)) { // $ExpectType number[] expect(arrWithTypes[0].toString()).toBe('1') } else { // $ExpectType string expect(typeof arrWithTypes).toBe('string') } if (isArray(arrWithComplexTypes)) { // $ExpectType Array<{ who: string }> expect(arrWithComplexTypes[0].who).toBe('Me') } else { // $ExpectType string // @ts-ignore expect(arrWithComplexTypes[0].who).toThrow() } }) }) describe(`isObject`, () => { type MyMap = { who: string; age: number } const possibleValidObj = { who: 'John', age: 32, } as MyMap | string | boolean it(`should return false if value is not an object map`, () => { expect(isObject(123)).toBe(false) expect(isObject('hello')).toBe(false) expect(isObject(null)).toBe(false) expect(isObject(undefined)).toBe(false) expect(isObject(true)).toBe(false) expect(isObject(noop)).toBe(false) expect(isObject(emptyArr)).toBe(false) expect(isObject(emptyObj)).toBe(true) }) it(`should properly type constraint object via inference`, () => { if (isObject(possibleValidObj)) { // $ExpectType MyMap expect(possibleValidObj).toHaveProperty('age') const { age } = possibleValidObj expect(age).toBe(32) } else { // $ExpectType string | boolean expect(possibleValidObj).toThrow() // @ts-ignore const { one } = possibleValidObj expect(one).toThrow() } }) it(`should properly type constraint object with array exclusion via inference`, () => { const arr = [1, 2, 3] as number[] | { one: 1 } if (isObject(arr)) { // $ExpectType { one: 1 } expect(arr).toThrow() // @ts-ignore const [first] = arr expect(first).toThrow() } else { // $ExpectType number[] expect(arr).toHaveProperty('length') const [first] = arr expect(first).toBe(1) } }) }) describe(`isFunction`, () => { it(`should return true if value is function`, () => { expect(isFunction(emptyArr)).toBe(false) expect(isFunction(emptyObj)).toBe(false) expect(isFunction(noop)).toBe(true) type FnDefinition = (count: number, who: string) => string const fnImplementation: FnDefinition | any[] = ( count: number, who: string ) => { if (!isNumber(count) || !isString(who)) { throw new Error(`arguments doesn't match allowed types`) } return `${who}: ${count} times` } if (isFunction(fnImplementation)) { // $ExpectType (count: number, who: string) => `${who}: ${count} times` expect(typeof fnImplementation).toBe('function') expect(fnImplementation(3, 'Me')).toBe('Me: 3 times') // @ts-ignore expect(() => fnImplementation(true, 123)).toThrowError( `arguments doesn't match allowed types` ) } else { // @ts-ignore expect(() => fnImplementation(3, 'Me')).toThrow() } }) }) describe(`isNumber`, () => { it(`should return true if value is number, NaN, Infinity`, () => { expect(isNumber(123)).toBe(true) expect(isNumber(NaN)).toBe(true) expect(isNumber(Infinity)).toBe(true) expect(isNumber(-1)).toBe(true) expect(isNumber('123')).toBe(false) // tslint:disable-next-line:prefer-const let narrowValue = 123 as number | { foo: () => {} } if (isNumber(narrowValue)) { // $ExpectType number expect(typeof narrowValue.toFixed).toBe('function') } else { // $ExpectType { foo: ()=>{} } // @ts-ignore expect(() => narrowValue.foo()).toThrow() } }) }) describe(`isBoolean`, () => { it(`should return true if value is boolean`, () => { expect(isBoolean(false)).toBe(true) expect(isBoolean(true)).toBe(true) expect(isBoolean('hello')).toBe(false) expect(isBoolean(-1)).toBe(false) expect(isBoolean(123)).toBe(false) }) }) describe(`isString`, () => { it(`should return true if value is string`, () => { expect(isString(false)).toBe(false) expect(isString(true)).toBe(false) expect(isString(-1)).toBe(false) expect(isString(123)).toBe(false) expect(isString('hello')).toBe(true) expect(isString('')).toBe(true) }) it(`should keep string literals if value is particular string literal`, () => { // tslint:disable-next-line:prefer-const const maybeString = 'hello' as 'hello' | boolean | number function testTypes() { if (isString(maybeString)) { // $ExpectType 'hello' expect(maybeString).toBe('hello') } else { throw new Error('string literals not handled properly') } } expect(testTypes).not.toThrow() }) }) describe(`isPresent`, () => { it(`should return true if value is present (non nullable, non undefined)`, () => { expect(isPresent(false)).toBe(true) expect(isPresent(true)).toBe(true) expect(isPresent(-1)).toBe(true) expect(isPresent(123)).toBe(true) expect(isPresent('hello')).toBe(true) expect(isPresent('')).toBe(true) expect(isPresent(emptyArr)).toBe(true) expect(isPresent(emptyObj)).toBe(true) expect(isPresent(null)).toBe(false) expect(isPresent(undefined)).toBe(false) const value = 'wat' as undefined | null | string if (isPresent(value)) { expect(typeof value).toBe('string') } else { // $ExpectType null | undefined // @ts-ignore expect(() => value.toString()).toThrow() } }) describe(`isBlank`, () => { it(`should return true if value is blank (non null or undefined)`, () => { expect(isBlank(false)).toBe(false) expect(isBlank(true)).toBe(false) expect(isBlank(-1)).toBe(false) expect(isBlank(123)).toBe(false) expect(isBlank('hello')).toBe(false) expect(isBlank('')).toBe(false) expect(isBlank(emptyArr)).toBe(false) expect(isBlank(emptyObj)).toBe(false) expect(isBlank(null)).toBe(true) expect(isBlank(undefined)).toBe(true) const value = null as undefined | null | string if (isBlank(value)) { // $ExpectType null | undefined // @ts-ignore expect(() => value.toString()).toThrow() } else { // $ExpectType string expect(typeof value).toBe('string') expect(() => value.toString()).toThrow() } }) }) describe(`isDate`, () => { it(`should return true if value is Date`, () => { expect(isDate('2018-09-02')).toBe(false) expect(isDate(Date.now())).toBe(false) expect(isDate(Date.parse('2018-09-02'))).toBe(false) expect(isDate(new Date())).toBe(true) }) }) describe(`isPromise`, () => { it(`should return true if value is Promise`, (done) => { const promiseViaCtor = new Promise((resolve) => resolve()) const promiseResolved = Promise.resolve() const promiseRejected = () => Promise.reject().catch(() => { done() }) const observableLike = { subscribe: noop, } expect(isPromise(promiseViaCtor)).toBe(true) expect(isPromise(promiseResolved)).toBe(true) expect(isPromise(promiseRejected())).toBe(true) expect(isPromise(emptyObj)).toBe(false) expect(isPromise(emptyArr)).toBe(false) expect(isPromise(noop)).toBe(false) expect(isPromise(observableLike)).toBe(false) }) }) }) describe(`isEmpty`, () => { it(`should return true for empty strings`, () => { const str = 'hello' expect(isEmpty('')).toBe(true) expect(isEmpty(str)).toBe(false) if (isEmpty(str)) { // $ExpectType '' expect(str[1].toUpperCase()).toThrow() } else { // $ExpectType 'hello' expect(str).toHaveLength(5) } }) it(`should return true for empty arrays`, () => { const arr = ['hello', 'world'] expect(isEmpty(emptyArr)).toBe(true) if (isEmpty(arr)) { // $ExpectType never[] expect(arr[1]).toThrow() } else { // $ExpectType string[] expect(arr).toHaveLength(2) const [first, second] = arr expect(first).toBe('hello') expect(second).toBe('world') } }) it(`should return true for empty objects`, () => { const obj = { one: 1, two: 2 } as | { one: number; two: number } | Empty.Object expect(isEmpty(emptyObj)).toBe(true) expect(isEmpty(obj)).toBe(false) if (isEmpty(obj)) { // $ExpectType Record<string,never> // @ts-ignore expect(obj.one.toString()).toThrow() } else { const { one, two } = obj expect({ one, two }).toEqual(obj) // $ExpectType { one: number; two: number } expect(obj).toHaveProperty('one') expect(obj).toHaveProperty('two') } }) it(`should throw error when non supported values are checked for emptiness`, () => { // @ts-ignore expect(() => isEmpty(undefined)).toThrowError( 'checked value must be type of string | array | object. You provided undefined' ) // @ts-ignore expect(() => isEmpty(null)).toThrowError( 'checked value must be type of string | array | object. You provided null' ) // @ts-ignore expect(() => isEmpty(true)).toThrowError( 'checked value must be type of string | array | object. You provided boolean' ) // @ts-ignore expect(() => isEmpty(123)).toThrowError( 'checked value must be type of string | array | object. You provided number' ) // on `object` types we cannot constraint with proper type error, we would get runtime error though expect(() => isEmpty(noop)).toThrow( 'checked value must be type of string | array | object. You provided function' ) }) }) })
the_stack
declare module 'sumi-worker' { /** * Options to configure the behaviour of a file open dialog. * * * Note 1: A dialog can select files, folders, or both. This is not true for Windows * which enforces to open either files or folder, but *not both*. * * Note 2: Explicitly setting `canSelectFiles` and `canSelectFolders` to `false` is futile * and the editor then silently adjusts the options to select files. */ export interface OpenDialogOptions { /** * The resource the dialog shows when opened. */ defaultUri?: Uri; /** * A human-readable string for the open button. */ openLabel?: string; /** * Allow to select files, defaults to `true`. */ canSelectFiles?: boolean; /** * Allow to select folders, defaults to `false`. */ canSelectFolders?: boolean; /** * Allow to select many files or folders. */ canSelectMany?: boolean; /** * A set of file filters that are used by the dialog. Each entry is a human readable label, * like "TypeScript", and an array of extensions, e.g. * ```ts * { * 'Images': ['png', 'jpg'] * 'TypeScript': ['ts', 'tsx'] * } * ``` */ filters?: { [name: string]: string[] }; } /** * Options to configure the behaviour of a file save dialog. */ export interface SaveDialogOptions { /** * The resource the dialog shows when opened. */ defaultUri?: Uri; /** * A human-readable string for the save button. */ saveLabel?: string; /** * A set of file filters that are used by the dialog. Each entry is a human readable label, * like "TypeScript", and an array of extensions, e.g. * ```ts * { * 'Images': ['png', 'jpg'] * 'TypeScript': ['ts', 'tsx'] * } * ``` */ filters?: { [name: string]: string[] }; } export namespace window { /** * The currently opened terminals or an empty array. */ export const terminals: ReadonlyArray<Terminal>; /** * The currently active terminal or `undefined`. The active terminal is the one that * currently has focus or most recently had focus. */ export const activeTerminal: Terminal | undefined; /** * An [event](#Event) which fires when the [active terminal](#window.activeTerminal) * has changed. *Note* that the event also fires when the active terminal changes * to `undefined`. */ export const onDidChangeActiveTerminal: Event<Terminal | undefined>; /** * An [event](#Event) which fires when a terminal has been created, either through the * [createTerminal](#window.createTerminal) API or commands. */ export const onDidOpenTerminal: Event<Terminal>; /** * An [event](#Event) which fires when a terminal is disposed. */ export const onDidCloseTerminal: Event<Terminal>; /** * Represents the current window's state. */ export const state: WindowState; /** * An [event](#Event) which fires when the focus state of the current window * changes. The value of the event represents whether the window is focused. */ export const onDidChangeWindowState: Event<WindowState>; /** * Creates a [Terminal](#Terminal). The cwd of the terminal will be the workspace directory * if it exists, regardless of whether an explicit customStartPath setting exists. * * @param name Optional human-readable string which will be used to represent the terminal in the UI. * @param shellPath Optional path to a custom shell executable to be used in the terminal. * @param shellArgs Optional args for the custom shell executable. A string can be used on Windows only which * allows specifying shell args in [command-line format](https://msdn.microsoft.com/en-au/08dfcab2-eb6e-49a4-80eb-87d4076c98c6). * @return A new Terminal. */ export function createTerminal(name?: string, shellPath?: string, shellArgs?: string[] | string): Terminal; /** * Create and show a new webview panel. * * @param viewType Identifies the type of the webview panel. * @param title Title of the panel. * @param showOptions Where to show the webview in the editor. If preserveFocus is set, the new webview will not take focus. * @param options Settings for the new panel. * * @return New webview panel. */ export function createWebviewPanel( viewType: string, title: string, showOptions: ViewColumn | { viewColumn: ViewColumn; preserveFocus?: boolean }, options?: WebviewPanelOptions & WebviewOptions, ): WebviewPanel; /** * ~~Show progress in the Source Control viewlet while running the given callback and while * its returned promise isn't resolve or rejected.~~ * * @deprecated Use `withProgress` instead. * * @param task A callback returning a promise. Progress increments can be reported with * the provided [progress](#Progress)-object. * @return The thenable the task did return. */ export function withScmProgress<R>(task: (progress: Progress<number>) => Thenable<R>): Thenable<R>; /** * Show progress in the editor. Progress is shown while running the given callback * and while the promise it returned isn't resolved nor rejected. The location at which * progress should show (and other details) is defined via the passed [`ProgressOptions`](#ProgressOptions). * * @param task A callback returning a promise. Progress state can be reported with * the provided [progress](#Progress)-object. * * To report discrete progress, use `increment` to indicate how much work has been completed. Each call with * a `increment` value will be summed up and reflected as overall progress until 100% is reached (a value of * e.g. `10` accounts for `10%` of work done). * Note that currently only `ProgressLocation.Notification` is capable of showing discrete progress. * * To monitor if the operation has been cancelled by the user, use the provided [`CancellationToken`](#CancellationToken). * Note that currently only `ProgressLocation.Notification` is supporting to show a cancel button to cancel the * long running operation. * * @return The thenable the task-callback returned. */ export function withProgress<R>( options: ProgressOptions, task: (progress: Progress<{ message?: string; increment?: number }>, token: CancellationToken) => Thenable<R>, ): Thenable<R>; /** * Register a [TreeDataProvider](#TreeDataProvider) for the view contributed using the extension point `views`. * This will allow you to contribute data to the [TreeView](#TreeView) and update if the data changes. * * **Note:** To get access to the [TreeView](#TreeView) and perform operations on it, use [createTreeView](#window.createTreeView). * * @param viewId Id of the view contributed using the extension point `views`. * @param treeDataProvider A [TreeDataProvider](#TreeDataProvider) that provides tree data for the view */ export function registerTreeDataProvider<T>(viewId: string, treeDataProvider: TreeDataProvider<T>): Disposable; /** * Create a [TreeView](#TreeView) for the view contributed using the extension point `views`. * @param viewId Id of the view contributed using the extension point `views`. * @param options Options for creating the [TreeView](#TreeView) * @returns a [TreeView](#TreeView). */ export function createTreeView<T>(viewId: string, options: TreeViewOptions<T>): TreeView<T>; /** * Options for creating a [TreeView](#TreeView) */ export interface TreeViewOptions<T> { /** * A data provider that provides tree data. */ treeDataProvider: TreeDataProvider<T>; /** * Whether to show collapse all action or not. */ showCollapseAll?: boolean; } /** * Shows a file open dialog to the user which allows to select a file * for opening-purposes. * * @param options Options that control the dialog. * @returns A promise that resolves to the selected resources or `undefined`. */ export function showOpenDialog(options: OpenDialogOptions): Thenable<Uri[] | undefined>; /** * Shows a file save dialog to the user which allows to select a file * for saving-purposes. * * @param options Options that control the dialog. * @returns A promise that resolves to the selected resource or `undefined`. */ export function showSaveDialog(options: SaveDialogOptions): Thenable<Uri | undefined>; } /** * A panel that contains a webview. */ interface WebviewPanel { /** * Identifies the type of the webview panel, such as `'markdown.preview'`. */ readonly viewType: string; /** * Title of the panel shown in UI. */ title: string; /** * Icon for the panel shown in UI. */ iconPath?: Uri | { light: Uri; dark: Uri }; /** * Webview belonging to the panel. */ readonly webview: Webview; /** * Content settings for the webview panel. */ readonly options: WebviewPanelOptions; /** * Editor position of the panel. This property is only set if the webview is in * one of the editor view columns. */ readonly viewColumn?: ViewColumn; /** * Whether the panel is active (focused by the user). */ readonly active: boolean; /** * Whether the panel is visible. */ readonly visible: boolean; /** * Fired when the panel's view state changes. */ readonly onDidChangeViewState: Event<WebviewPanelOnDidChangeViewStateEvent>; /** * Fired when the panel is disposed. * * This may be because the user closed the panel or because `.dispose()` was * called on it. * * Trying to use the panel after it has been disposed throws an exception. */ readonly onDidDispose: Event<void>; /** * Show the webview panel in a given column. * * A webview panel may only show in a single column at a time. If it is already showing, this * method moves it to a new column. * * @param viewColumn View column to show the panel in. Shows in the current `viewColumn` if undefined. * @param preserveFocus When `true`, the webview will not take focus. */ reveal(viewColumn?: ViewColumn, preserveFocus?: boolean): void; /** * Dispose of the webview panel. * * This closes the panel if it showing and disposes of the resources owned by the webview. * Webview panels are also disposed when the user closes the webview panel. Both cases * fire the `onDispose` event. */ dispose(): any; } /** * Event fired when a webview panel's view state changes. */ export interface WebviewPanelOnDidChangeViewStateEvent { /** * Webview panel whose view state changed. */ readonly webviewPanel: WebviewPanel; } }
the_stack
import React from 'react' import capitalize from 'lodash/capitalize' import { useRouter } from 'next/router' import { Screen } from '../../types' import { Select as NativeSelect, OrganizationWrapper, lightThemes, NewsCard, } from '@island.is/web/components' import { useDateUtils } from '@island.is/web/i18n/useDateUtils' import { Box, Text, Stack, BreadCrumbItem, Divider, Pagination, Hidden, Select, Option, Link, GridColumn, NavigationItem, } from '@island.is/island-ui/core' import { withMainLayout } from '@island.is/web/layouts/main' import { GET_NAMESPACE_QUERY, GET_NEWS_DATES_QUERY, GET_NEWS_QUERY, GET_ORGANIZATION_PAGE_QUERY, } from '../queries' import { GetNewsDatesQuery, QueryGetNewsDatesArgs, GetNewsQuery, QueryGetNewsArgs, ContentLanguage, QueryGetNamespaceArgs, GetNamespaceQuery, Query, QueryGetOrganizationPageArgs, } from '../../graphql/schema' import { useNamespace } from '@island.is/web/hooks' import { useLinkResolver } from '../../hooks/useLinkResolver' const PERPAGE = 10 interface NewsListProps { organizationPage: Query['getOrganizationPage'] newsList: GetNewsQuery['getNews']['items'] total: number datesMap: { [year: string]: number[] } selectedYear: number selectedMonth: number selectedPage: number selectedTag: string namespace: GetNamespaceQuery['getNamespace'] } const NewsList: Screen<NewsListProps> = ({ organizationPage, newsList, total, datesMap, selectedYear, selectedMonth, selectedPage, selectedTag, namespace, }) => { const Router = useRouter() const { linkResolver } = useLinkResolver() const { getMonthByIndex } = useDateUtils() const n = useNamespace(namespace) const currentNavItem = organizationPage.menuLinks.find( ({ primaryLink }) => primaryLink.url === Router.asPath, )?.primaryLink ?? organizationPage.secondaryMenu?.childrenLinks.find( ({ url }) => url === Router.asPath, ) const newsTitle = currentNavItem?.text ?? newsList[0]?.genericTags.find((x) => x.slug === selectedTag).title ?? n('newsTitle', 'Fréttir og tilkynningar') const years = Object.keys(datesMap) const months = datesMap[selectedYear] ?? [] const allYearsString = n('allYears', 'Allar fréttir') const allMonthsString = n('allMonths', 'Allt árið') const yearString = n('year', 'Ár') const monthString = n('month', 'Mánuður') const yearOptions = [ { label: allYearsString, value: allYearsString, }, ...years.map((year) => ({ label: year, value: year, })), ] const monthOptions = [ { label: allMonthsString, value: undefined, }, ...months.map((month) => ({ label: capitalize(getMonthByIndex(month - 1)), // api returns months with index starting from 1 not 0 so we compensate value: month, })), ] const makeHref = (y: number | string, m?: number | string) => { const params = { y, m, tag: selectedTag } const query = Object.entries(params).reduce((queryObject, [key, value]) => { if (value) { queryObject[key] = value } return queryObject }, {}) return { pathname: linkResolver('organizationnewsoverview', [ organizationPage.slug, ]).href, query, } } const breadCrumbs: BreadCrumbItem[] = [ { title: 'Ísland.is', href: linkResolver('homepage').href, typename: 'homepage', }, { title: organizationPage.title, href: linkResolver('organizationpage', [organizationPage.slug]).href, typename: 'organizationpage', }, ] const sidebar = ( <Hidden below="md"> <Box background="purple100" borderRadius="large" padding={4} marginTop={4} > <Stack space={3}> <Text variant="h4" as="h1" color="purple600"> {newsTitle} </Text> <Divider weight="purple200" /> <NativeSelect name="year" value={selectedYear ? selectedYear.toString() : allYearsString} options={yearOptions} onChange={(e) => { const selectedValue = e.target.value !== allYearsString ? e.target.value : null Router.push(makeHref(selectedValue)) }} color="purple400" /> {selectedYear && ( <div> <Link href={makeHref(selectedYear)}> <Text as="span" fontWeight={!selectedMonth ? 'semiBold' : 'regular'} > {allMonthsString} </Text> </Link> </div> )} {months.map((month) => ( <div key={month}> <Link href={makeHref(selectedYear, month)}> <Text as="span" fontWeight={selectedMonth === month ? 'semiBold' : 'regular'} > {capitalize(getMonthByIndex(month - 1))} </Text> </Link> </div> ))} </Stack> </Box> </Hidden> ) const navList: NavigationItem[] = organizationPage.menuLinks.map( ({ primaryLink, childrenLinks }) => ({ title: primaryLink.text, href: primaryLink.url, active: organizationPage.newsTag?.slug === selectedTag && primaryLink.url === Router.asPath, items: childrenLinks.map(({ text, url }) => ({ title: text, href: url, })), }), ) return ( <OrganizationWrapper pageTitle={newsTitle} organizationPage={organizationPage} breadcrumbItems={breadCrumbs} sidebarContent={sidebar} navigationData={{ title: n('navigationTitle', 'Efnisyfirlit'), items: navList, }} > <Stack space={[3, 3, 4]}> <Text variant="h1" as="h1" marginBottom={2}> {newsTitle} </Text> {selectedYear && ( <Hidden below="lg"> <Text variant="h2" as="h2"> {selectedYear} </Text> </Hidden> )} <GridColumn hiddenAbove="sm" paddingTop={4} paddingBottom={1}> <Select label={yearString} placeholder={yearString} isSearchable={false} value={yearOptions.find( (option) => option.value === (selectedYear ? selectedYear.toString() : allYearsString), )} options={yearOptions} onChange={({ value }: Option) => { Router.push(makeHref(value === allYearsString ? null : value)) }} name="year" /> </GridColumn> {selectedYear && ( <GridColumn hiddenAbove="sm"> <Select label={monthString} placeholder={monthString} value={monthOptions.find((o) => o.value === selectedMonth)} options={monthOptions} onChange={({ value }: Option) => Router.push(makeHref(selectedYear, value)) } name="month" /> </GridColumn> )} {!newsList.length && ( <Text variant="h4"> {n('newsListEmptyMonth', 'Engar fréttir fundust í þessum mánuði.')} </Text> )} {newsList.map((newsItem, index) => ( <NewsCard key={index} title={newsItem.title} introduction={newsItem.intro} image={newsItem.image} titleAs="h2" href={ linkResolver('organizationnews', [ organizationPage.slug, newsItem.slug, ]).href } date={newsItem.date} readMoreText={n('readMore', 'Lesa nánar')} /> ))} {newsList.length > 0 && ( <Box paddingTop={[4, 4, 8]}> <Pagination totalPages={Math.ceil(total / PERPAGE)} page={selectedPage} renderLink={(page, className, children) => ( <Link href={{ pathname: linkResolver('organizationnewsoverview', [ organizationPage.slug, ]).href, query: { ...Router.query, page }, }} > <span className={className}>{children}</span> </Link> )} /> </Box> )} </Stack> </OrganizationWrapper> ) } const createDatesMap = (datesList) => { return datesList.reduce((datesMap, date) => { const [year, month] = date.split('-') if (datesMap[year]) { datesMap[year].push(parseInt(month)) // we can assume each month only appears once } else { datesMap[year] = [parseInt(month)] } return datesMap }, {}) } const getIntParam = (s: string | string[]) => { const i = parseInt(Array.isArray(s) ? s[0] : s, 10) if (!isNaN(i)) return i } NewsList.getInitialProps = async ({ apolloClient, locale, query }) => { const year = getIntParam(query.y) const month = year && getIntParam(query.m) const selectedPage = getIntParam(query.page) ?? 1 const organizationPage = ( await Promise.resolve( apolloClient.query<Query, QueryGetOrganizationPageArgs>({ query: GET_ORGANIZATION_PAGE_QUERY, variables: { input: { slug: query.slug as string, lang: locale as ContentLanguage, }, }, }), ) ).data.getOrganizationPage const tag = (query.tag as string) ?? organizationPage.newsTag?.slug ?? '' const [ { data: { getNewsDates: newsDatesList }, }, { data: { getNews: { items: newsList, total }, }, }, namespace, ] = await Promise.all([ apolloClient.query<GetNewsDatesQuery, QueryGetNewsDatesArgs>({ query: GET_NEWS_DATES_QUERY, variables: { input: { lang: locale as ContentLanguage, tag, }, }, }), apolloClient.query<GetNewsQuery, QueryGetNewsArgs>({ query: GET_NEWS_QUERY, variables: { input: { lang: locale as ContentLanguage, size: PERPAGE, page: selectedPage, year, month, tag, }, }, }), apolloClient .query<GetNamespaceQuery, QueryGetNamespaceArgs>({ query: GET_NAMESPACE_QUERY, variables: { input: { lang: locale as ContentLanguage, namespace: 'NewsList', }, }, }) .then((variables) => { // map data here to reduce data processing in component return JSON.parse(variables.data.getNamespace.fields) }), ]) const lightTheme = lightThemes.includes(organizationPage.theme) return { organizationPage: organizationPage, newsList: organizationPage.newsTag ? newsList : [], total, selectedYear: year, selectedMonth: month, selectedTag: tag, datesMap: createDatesMap(newsDatesList), selectedPage, namespace, ...(lightTheme ? {} : { darkTheme: true }), } } export default withMainLayout(NewsList)
the_stack
import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Store } from '@ngrx/store'; import { TranslateService } from '@ngx-translate/core'; import { Observable } from 'rxjs'; import { filter, map, switchMap, take } from 'rxjs/operators'; import { hasValue, isNotEmpty, isNotEmptyOperator } from '../../shared/empty.util'; import { NotificationOptions } from '../../shared/notifications/models/notification-options.model'; import { INotification } from '../../shared/notifications/models/notification.model'; import { NotificationsService } from '../../shared/notifications/notifications.service'; import { FollowLinkConfig } from '../../shared/utils/follow-link-config.model'; import { dataService } from '../cache/builders/build-decorators'; import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; import { RequestParam } from '../cache/models/request-param.model'; import { ObjectCacheService } from '../cache/object-cache.service'; import { CoreState } from '../core.reducers'; import { HttpOptions } from '../dspace-rest/dspace-rest.service'; import { DSpaceSerializer } from '../dspace-rest/dspace.serializer'; import { Collection } from '../shared/collection.model'; import { COLLECTION } from '../shared/collection.resource-type'; import { ContentSource } from '../shared/content-source.model'; import { HALEndpointService } from '../shared/hal-endpoint.service'; import { Item } from '../shared/item.model'; import { getFirstCompletedRemoteData } from '../shared/operators'; import { ComColDataService } from './comcol-data.service'; import { CommunityDataService } from './community-data.service'; import { DSOChangeAnalyzer } from './dso-change-analyzer.service'; import { PaginatedList } from './paginated-list.model'; import { RemoteData } from './remote-data'; import { ContentSourceRequest, FindListOptions, RestRequest, UpdateContentSourceRequest } from './request.models'; import { RequestService } from './request.service'; import { BitstreamDataService } from './bitstream-data.service'; @Injectable() @dataService(COLLECTION) export class CollectionDataService extends ComColDataService<Collection> { protected linkPath = 'collections'; protected errorTitle = 'collection.source.update.notifications.error.title'; protected contentSourceError = 'collection.source.update.notifications.error.content'; constructor( protected requestService: RequestService, protected rdbService: RemoteDataBuildService, protected store: Store<CoreState>, protected cds: CommunityDataService, protected objectCache: ObjectCacheService, protected halService: HALEndpointService, protected notificationsService: NotificationsService, protected http: HttpClient, protected bitstreamDataService: BitstreamDataService, protected comparator: DSOChangeAnalyzer<Collection>, protected translate: TranslateService ) { super(); } /** * Get all collections the user is authorized to submit to * * @param query limit the returned collection to those with metadata values * matching the query terms. * @param options The [[FindListOptions]] object * @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's * no valid cached version. Defaults to true * @param reRequestOnStale Whether or not the request should automatically be re- * requested after the response becomes stale * @param linksToFollow List of {@link FollowLinkConfig} that indicate which * {@link HALLink}s should be automatically resolved * @return Observable<RemoteData<PaginatedList<Collection>>> * collection list */ getAuthorizedCollection(query: string, options: FindListOptions = {}, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<Collection>[]): Observable<RemoteData<PaginatedList<Collection>>> { const searchHref = 'findSubmitAuthorized'; options = Object.assign({}, options, { searchParams: [new RequestParam('query', query)] }); return this.searchBy(searchHref, options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow).pipe( filter((collections: RemoteData<PaginatedList<Collection>>) => !collections.isResponsePending)); } /** * Get all collections the user is authorized to submit to * * @param query limit the returned collection to those with metadata values matching the query terms. * @param entityType The entity type used to limit the returned collection * @param options The [[FindListOptions]] object * @param reRequestOnStale Whether or not the request should automatically be re-requested after * the response becomes stale * @param linksToFollow The array of [[FollowLinkConfig]] * @return Observable<RemoteData<PaginatedList<Collection>>> * collection list */ getAuthorizedCollectionByEntityType( query: string, entityType: string, options: FindListOptions = {}, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<Collection>[]): Observable<RemoteData<PaginatedList<Collection>>> { const searchHref = 'findSubmitAuthorizedByEntityType'; options = Object.assign({}, options, { searchParams: [ new RequestParam('query', query), new RequestParam('entityType', entityType) ] }); return this.searchBy(searchHref, options, true, reRequestOnStale, ...linksToFollow).pipe( filter((collections: RemoteData<PaginatedList<Collection>>) => !collections.isResponsePending)); } /** * Get all collections the user is authorized to submit to, by community * * @param communityId The community id * @param query limit the returned collection to those with metadata values matching the query terms. * @param options The [[FindListOptions]] object * @param reRequestOnStale Whether or not the request should automatically be re- * requested after the response becomes stale * @return Observable<RemoteData<PaginatedList<Collection>>> * collection list */ getAuthorizedCollectionByCommunity(communityId: string, query: string, options: FindListOptions = {}, reRequestOnStale = true,): Observable<RemoteData<PaginatedList<Collection>>> { const searchHref = 'findSubmitAuthorizedByCommunity'; options = Object.assign({}, options, { searchParams: [ new RequestParam('uuid', communityId), new RequestParam('query', query) ] }); return this.searchBy(searchHref, options, reRequestOnStale).pipe( filter((collections: RemoteData<PaginatedList<Collection>>) => !collections.isResponsePending)); } /** * Get all collections the user is authorized to submit to, by community and has the metadata * * @param communityId The community id * @param entityType The entity type used to limit the returned collection * @param options The [[FindListOptions]] object * @param reRequestOnStale Whether or not the request should automatically be re-requested after * the response becomes stale * @param linksToFollow The array of [[FollowLinkConfig]] * @return Observable<RemoteData<PaginatedList<Collection>>> * collection list */ getAuthorizedCollectionByCommunityAndEntityType( communityId: string, entityType: string, options: FindListOptions = {}, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<Collection>[]): Observable<RemoteData<PaginatedList<Collection>>> { const searchHref = 'findSubmitAuthorizedByCommunityAndEntityType'; const searchParams = [ new RequestParam('uuid', communityId), new RequestParam('entityType', entityType) ]; options = Object.assign({}, options, { searchParams: searchParams }); return this.searchBy(searchHref, options, true, reRequestOnStale, ...linksToFollow).pipe( filter((collections: RemoteData<PaginatedList<Collection>>) => !collections.isResponsePending)); } /** * Find whether there is a collection whom user has authorization to submit to * * @return boolean * true if the user has at least one collection to submit to */ hasAuthorizedCollection(): Observable<boolean> { const searchHref = 'findSubmitAuthorized'; const options = new FindListOptions(); options.elementsPerPage = 1; return this.searchBy(searchHref, options).pipe( filter((collections: RemoteData<PaginatedList<Collection>>) => !collections.isResponsePending), take(1), map((collections: RemoteData<PaginatedList<Collection>>) => collections.payload.totalElements > 0) ); } /** * Get the endpoint for the collection's content harvester * @param collectionId */ getHarvesterEndpoint(collectionId: string): Observable<string> { return this.halService.getEndpoint(this.linkPath).pipe( switchMap((href: string) => this.halService.getEndpoint('harvester', `${href}/${collectionId}`)) ); } /** * Get the collection's content harvester * @param collectionId */ getContentSource(collectionId: string, useCachedVersionIfAvailable = true): Observable<RemoteData<ContentSource>> { const href$ = this.getHarvesterEndpoint(collectionId).pipe( isNotEmptyOperator(), take(1) ); href$.subscribe((href: string) => { const request = new ContentSourceRequest(this.requestService.generateRequestId(), href); this.requestService.send(request, useCachedVersionIfAvailable); }); return this.rdbService.buildSingle<ContentSource>(href$); } /** * Update the settings of the collection's content harvester * @param collectionId * @param contentSource */ updateContentSource(collectionId: string, contentSource: ContentSource): Observable<ContentSource | INotification> { const requestId = this.requestService.generateRequestId(); const serializedContentSource = new DSpaceSerializer(ContentSource).serialize(contentSource); const request$ = this.getHarvesterEndpoint(collectionId).pipe( take(1), map((href: string) => { const options: HttpOptions = Object.create({}); let headers = new HttpHeaders(); headers = headers.append('Content-Type', 'application/json'); options.headers = headers; return new UpdateContentSourceRequest(requestId, href, JSON.stringify(serializedContentSource), options); }) ); // Execute the post/put request request$.subscribe((request: RestRequest) => this.requestService.send(request)); // Return updated ContentSource return this.rdbService.buildFromRequestUUID<ContentSource>(requestId).pipe( getFirstCompletedRemoteData(), map((response: RemoteData<ContentSource>) => { if (response.hasFailed) { if (hasValue(response.errorMessage)) { if (response.statusCode === 422) { return this.notificationsService.error(this.translate.instant(this.errorTitle), this.translate.instant(this.contentSourceError), new NotificationOptions(-1)); } else { return this.notificationsService.error(this.translate.instant(this.errorTitle), (response as any).errorMessage, new NotificationOptions(-1)); } } } else { return response; } }), isNotEmptyOperator(), map((response: RemoteData<ContentSource> | INotification) => { if (isNotEmpty((response as any).payload)) { return (response as RemoteData<ContentSource>).payload; } return response as INotification; }) ); } protected getFindByParentHref(parentUUID: string): Observable<string> { return this.halService.getEndpoint('communities').pipe( switchMap((communityEndpointHref: string) => this.halService.getEndpoint('collections', `${communityEndpointHref}/${parentUUID}`)), ); } /** * Returns {@link RemoteData} of {@link Collection} that is the owning collection of the given item * @param item Item we want the owning collection of */ findOwningCollectionFor(item: Item): Observable<RemoteData<Collection>> { return this.findByHref(item._links.owningCollection.href); } /** * Get a list of mapped collections for the given item. * @param item Item for which the mapped collections should be retrieved. * @param findListOptions Pagination and search options. */ findMappedCollectionsFor(item: Item, findListOptions?: FindListOptions): Observable<RemoteData<PaginatedList<Collection>>> { return this.findAllByHref(item._links.mappedCollections.href, findListOptions); } }
the_stack
import { bySport, isSport, PHASE, unwrapGameAttribute } from "../../../common"; import { team } from ".."; import { idb } from "../../db"; import { defaultGameAttributes, g, helpers } from "../../util"; import type { GameResults } from "../../../common/types"; import { getActualAttendance, getAdjustedTicketPrice, getAutoTicketPrice, getBaseAttendance, } from "./attendance"; const writeTeamStats = async (results: GameResults) => { const allStarGame = results.team[0].id === -1 && results.team[1].id === -2; if (allStarGame) { return g.get("defaultStadiumCapacity"); } let baseAttendance = 0; let attendance = 0; let adjustedTicketPrice = 0; for (const t1 of [0, 1]) { const t2 = t1 === 1 ? 0 : 1; const payroll = await team.getPayroll(results.team[t1].id); const [t, teamSeasons] = await Promise.all([ idb.cache.teams.get(results.team[t1].id), idb.cache.teamSeasons.indexGetAll("teamSeasonsByTidSeason", [ [results.team[t1].id, g.get("season") - 2], [results.team[t1].id, g.get("season")], ]), ]); const teamSeason = teamSeasons.at(-1)!; const won = results.team[t1].stat.pts > results.team[t2].stat.pts; const lost = results.team[t1].stat.pts < results.team[t2].stat.pts; const playoffs = g.get("phase") === PHASE.PLAYOFFS; let teamStats = await idb.cache.teamStats.indexGet( "teamStatsByPlayoffsTid", [playoffs, results.team[t1].id], ); if (!teamStats) { teamStats = team.genStatsRow(results.team[t1].id, playoffs); } if (!t) { throw new Error("Invalid tid"); } // Attendance - base calculation now, which is used for other revenue estimates. Base on the home team if (t1 === 0) { const playoffs = g.get("phase") === PHASE.PLAYOFFS; baseAttendance = getBaseAttendance({ hype: teamSeason.hype, pop: teamSeason.pop, playoffs, }); if (t.autoTicketPrice !== false || !g.get("userTids").includes(t.tid)) { const ticketPrice = getAutoTicketPrice({ hype: teamSeason.hype, pop: teamSeason.pop, stadiumCapacity: teamSeason.stadiumCapacity, teamSeasons, }); if (ticketPrice !== t.budget.ticketPrice.amount) { t.budget.ticketPrice.amount = ticketPrice; } } adjustedTicketPrice = getAdjustedTicketPrice( t.budget.ticketPrice.amount, playoffs, ); } // Some things are only paid for regular season games. let salaryPaid = 0; let scoutingPaid = 0; let coachingPaid = 0; let healthPaid = 0; let facilitiesPaid = 0; let merchRevenue = 0; let sponsorRevenue = 0; let nationalTvRevenue = 0; let localTvRevenue = 0; if (g.get("phase") !== PHASE.PLAYOFFS) { // All in [thousands of dollars] salaryPaid = payroll / g.get("numGames"); scoutingPaid = t.budget.scouting.amount / g.get("numGames"); coachingPaid = t.budget.coaching.amount / g.get("numGames"); healthPaid = t.budget.health.amount / g.get("numGames"); facilitiesPaid = t.budget.facilities.amount / g.get("numGames"); const salaryCapFactor = g.get("salaryCap") / defaultGameAttributes.salaryCap; // Only different for hockey let salaryCapFactor2; if (isSport("hockey")) { // Legacy, should probably adjust other params salaryCapFactor2 = g.get("salaryCap") / 90000; } else { salaryCapFactor2 = salaryCapFactor; } if (isSport("basketball") || isSport("hockey")) { merchRevenue = (salaryCapFactor2 * 4.5 * baseAttendance) / 1000; if (merchRevenue > salaryCapFactor * 250) { merchRevenue = salaryCapFactor * 250; } sponsorRevenue = (salaryCapFactor2 * 15 * baseAttendance) / 1000; if (sponsorRevenue > salaryCapFactor * 600) { sponsorRevenue = salaryCapFactor * 600; } nationalTvRevenue = salaryCapFactor2 * 375; localTvRevenue = (salaryCapFactor2 * 15 * baseAttendance) / 1000; if (localTvRevenue > salaryCapFactor * 1200) { localTvRevenue = salaryCapFactor * 1200; } } else { // Football targets: // expenses: $350M // national TV: $170M // local TV: $50M // ticket: $75M // sponsorship: $25M // merchandise: $25M nationalTvRevenue = (salaryCapFactor2 * 175000) / g.get("numGames"); localTvRevenue = (salaryCapFactor2 * ((5000 / g.get("numGames")) * baseAttendance)) / g.get("defaultStadiumCapacity"); sponsorRevenue = (salaryCapFactor2 * ((2500 / g.get("numGames")) * baseAttendance)) / g.get("defaultStadiumCapacity"); merchRevenue = (salaryCapFactor2 * ((2500 / g.get("numGames")) * baseAttendance)) / g.get("defaultStadiumCapacity"); } } // Attendance: base on home team if (t1 === 0) { attendance = getActualAttendance({ baseAttendance, randomize: true, stadiumCapacity: teamSeason.stadiumCapacity, teamSeasons, adjustedTicketPrice, }); } // This doesn't really make sense let ticketRevenue = (adjustedTicketPrice * attendance) / 1000; // [thousands of dollars] // Hype - relative to the expectations of prior seasons if (teamSeason.gp > 5 && g.get("phase") !== PHASE.PLAYOFFS) { let winp = helpers.calcWinp(teamSeason); let winpOld = 0; // Avg winning percentage of last 0-2 seasons (as available) for (let i = 0; i < teamSeasons.length - 1; i++) { winpOld += helpers.calcWinp(teamSeasons[i]); } if (teamSeasons.length > 1) { winpOld /= teamSeasons.length - 1; } else { winpOld = 0.5; // Default for new games } // It should never happen, but winp and winpOld sometimes turn up as NaN due to a duplicate season entry or the user skipping seasons if (Number.isNaN(winp)) { winp = 0; } if (Number.isNaN(winpOld)) { winpOld = 0; } teamSeason.hype = teamSeason.hype + 0.01 * (winp - 0.55) + 0.015 * (winp - winpOld); if (teamSeason.hype > 1) { teamSeason.hype = 1; } else if (teamSeason.hype < 0) { teamSeason.hype = 0; } } // 5% bonus for easy, 5% penalty for hard, 20% penalty for insane const fudgeFactor = g.get("userTids").includes(results.team[t1].id) ? helpers.bound(1 - 0.2 * g.get("difficulty"), 0, Infinity) : 1; // Globally adjust revenue based on the number of games in the season and playoffs let seasonLengthFactor; if (g.get("phase") === PHASE.PLAYOFFS) { let numGamesCurrent = 0; for (const numGames of g.get("numGamesPlayoffSeries")) { numGamesCurrent += Math.ceil((numGames * 3) / 4); } let numGamesDefault = 0; for (const numGames of unwrapGameAttribute( defaultGameAttributes, "numGamesPlayoffSeries", )) { numGamesDefault += Math.ceil((numGames * 3) / 4); } seasonLengthFactor = numGamesDefault / numGamesCurrent; } else { seasonLengthFactor = defaultGameAttributes.numGames / g.get("numGames"); } merchRevenue *= fudgeFactor * seasonLengthFactor; sponsorRevenue *= fudgeFactor * seasonLengthFactor; nationalTvRevenue *= fudgeFactor * seasonLengthFactor; localTvRevenue *= fudgeFactor * seasonLengthFactor; ticketRevenue *= fudgeFactor * seasonLengthFactor; const revenue = merchRevenue + sponsorRevenue + nationalTvRevenue + localTvRevenue + ticketRevenue; const expenses = salaryPaid + scoutingPaid + coachingPaid + healthPaid + facilitiesPaid; teamSeason.cash += revenue - expenses; if (t1 === 0) { // Only home team gets attendance... teamSeason.att += attendance; // This is only used for attendance tracking if (!teamSeason.hasOwnProperty("gpHome")) { teamSeason.gpHome = Math.round(teamSeason.gp / 2); } // See also team.js and teamFinances.js teamSeason.gpHome += 1; } teamSeason.gp += 1; teamSeason.revenues.merch.amount += merchRevenue; teamSeason.revenues.sponsor.amount += sponsorRevenue; teamSeason.revenues.nationalTv.amount += nationalTvRevenue; teamSeason.revenues.localTv.amount += localTvRevenue; teamSeason.revenues.ticket.amount += ticketRevenue; teamSeason.expenses.salary.amount += salaryPaid; teamSeason.expenses.scouting.amount += scoutingPaid; teamSeason.expenses.coaching.amount += coachingPaid; teamSeason.expenses.health.amount += healthPaid; teamSeason.expenses.facilities.amount += facilitiesPaid; // For historical reasons, "ba" is special in basketball (stored in box score, not in team stats) const skip = bySport({ basketball: ["ptsQtrs", "ba"], football: ["ptsQtrs"], hockey: ["ptsQtrs"], }); for (const key of Object.keys(results.team[t1].stat)) { if (skip.includes(key)) { continue; } if (teamStats[key] === undefined) { teamStats[key] = 0; } if (isSport("football") && key.endsWith("Lng")) { if (results.team[t1].stat[key] > teamStats[key]) { teamStats[key] = results.team[t1].stat[key]; } } else { teamStats[key] += results.team[t1].stat[key]; } if (key !== "min") { const oppKey = `opp${helpers.upperCaseFirstLetter(key)}`; // Deal with upgraded leagues, and some stats that don't have opp versions if (teamStats.hasOwnProperty(oppKey)) { teamStats[oppKey] += results.team[t2].stat[key]; } } } // Track this separately, because a team can get a shutout with multiple goalies, and then there is no player shutout if (isSport("hockey")) { if (results.team[t2].stat.pts === 0) { teamStats.so += 1; } if (results.team[t1].stat.pts === 0) { teamStats.oppSo += 1; } } teamStats.gp += 1; if (teamSeason.lastTen.length === 10 && g.get("phase") !== PHASE.PLAYOFFS) { teamSeason.lastTen.pop(); } if (won && g.get("phase") !== PHASE.PLAYOFFS) { teamSeason.won += 1; if (results.team[0].did === results.team[1].did) { teamSeason.wonDiv += 1; } if (results.team[0].cid === results.team[1].cid) { teamSeason.wonConf += 1; } if (t1 === 0) { teamSeason.wonHome += 1; } else { teamSeason.wonAway += 1; } teamSeason.lastTen.unshift(1); if (teamSeason.streak >= 0) { teamSeason.streak += 1; } else { teamSeason.streak = 1; } } else if (lost && g.get("phase") !== PHASE.PLAYOFFS) { const lostOrOtl = results.overtimes > 0 && g.get("otl", "current") ? "otl" : "lost"; teamSeason[lostOrOtl] += 1; if (results.team[0].did === results.team[1].did) { teamSeason[`${lostOrOtl}Div` as const] += 1; } if (results.team[0].cid === results.team[1].cid) { teamSeason[`${lostOrOtl}Conf` as const] += 1; } if (t1 === 0) { teamSeason[`${lostOrOtl}Home` as const] += 1; } else { teamSeason[`${lostOrOtl}Away` as const] += 1; } if (lostOrOtl === "lost") { teamSeason.lastTen.unshift(0); } else { teamSeason.lastTen.unshift("OTL"); } if (teamSeason.streak <= 0) { teamSeason.streak -= 1; } else { teamSeason.streak = -1; } } else if (g.get("ties", "current") && g.get("phase") !== PHASE.PLAYOFFS) { teamSeason.tied += 1; if (results.team[0].did === results.team[1].did) { teamSeason.tiedDiv += 1; } if (results.team[0].cid === results.team[1].cid) { teamSeason.tiedConf += 1; } if (t1 === 0) { teamSeason.tiedHome += 1; } else { teamSeason.tiedAway += 1; } teamSeason.lastTen.unshift(-1); teamSeason.streak = 0; } if (teamSeason.ovrStart === undefined) { const playersRaw = await idb.cache.players.indexGetAll( "playersByTid", teamSeason.tid, ); const players = await idb.getCopies.playersPlus(playersRaw, { attrs: ["value"], fuzz: true, ratings: ["ovr", "pos", "ovrs"], season: g.get("season"), tid: teamSeason.tid, }); teamSeason.ovrStart = team.ovr(players); } await idb.cache.teams.put(t); await idb.cache.teamSeasons.put(teamSeason); await idb.cache.teamStats.put(teamStats); } return attendance; }; export default writeTeamStats;
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { AppServiceEnvironments } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { WebSiteManagementClient } from "../webSiteManagementClient"; import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "../lroImpl"; import { AppServiceEnvironmentResource, AppServiceEnvironmentsListNextOptionalParams, AppServiceEnvironmentsListOptionalParams, AppServiceEnvironmentsListByResourceGroupNextOptionalParams, AppServiceEnvironmentsListByResourceGroupOptionalParams, StampCapacity, AppServiceEnvironmentsListCapacitiesNextOptionalParams, AppServiceEnvironmentsListCapacitiesOptionalParams, Site, VirtualNetworkProfile, AppServiceEnvironmentsChangeVnetNextOptionalParams, AppServiceEnvironmentsChangeVnetOptionalParams, InboundEnvironmentEndpoint, AppServiceEnvironmentsGetInboundNetworkDependenciesEndpointsNextOptionalParams, AppServiceEnvironmentsGetInboundNetworkDependenciesEndpointsOptionalParams, WorkerPoolResource, AppServiceEnvironmentsListMultiRolePoolsNextOptionalParams, AppServiceEnvironmentsListMultiRolePoolsOptionalParams, ResourceMetricDefinition, AppServiceEnvironmentsListMultiRolePoolInstanceMetricDefinitionsNextOptionalParams, AppServiceEnvironmentsListMultiRolePoolInstanceMetricDefinitionsOptionalParams, AppServiceEnvironmentsListMultiRoleMetricDefinitionsNextOptionalParams, AppServiceEnvironmentsListMultiRoleMetricDefinitionsOptionalParams, SkuInfo, AppServiceEnvironmentsListMultiRolePoolSkusNextOptionalParams, AppServiceEnvironmentsListMultiRolePoolSkusOptionalParams, Usage, AppServiceEnvironmentsListMultiRoleUsagesNextOptionalParams, AppServiceEnvironmentsListMultiRoleUsagesOptionalParams, OutboundEnvironmentEndpoint, AppServiceEnvironmentsGetOutboundNetworkDependenciesEndpointsNextOptionalParams, AppServiceEnvironmentsGetOutboundNetworkDependenciesEndpointsOptionalParams, AppServiceEnvironmentsResumeNextOptionalParams, AppServiceEnvironmentsResumeOptionalParams, AppServicePlan, AppServiceEnvironmentsListAppServicePlansNextOptionalParams, AppServiceEnvironmentsListAppServicePlansOptionalParams, AppServiceEnvironmentsListWebAppsNextOptionalParams, AppServiceEnvironmentsListWebAppsOptionalParams, AppServiceEnvironmentsSuspendNextOptionalParams, AppServiceEnvironmentsSuspendOptionalParams, CsmUsageQuota, AppServiceEnvironmentsListUsagesNextOptionalParams, AppServiceEnvironmentsListUsagesOptionalParams, AppServiceEnvironmentsListWorkerPoolsNextOptionalParams, AppServiceEnvironmentsListWorkerPoolsOptionalParams, AppServiceEnvironmentsListWorkerPoolInstanceMetricDefinitionsNextOptionalParams, AppServiceEnvironmentsListWorkerPoolInstanceMetricDefinitionsOptionalParams, AppServiceEnvironmentsListWebWorkerMetricDefinitionsNextOptionalParams, AppServiceEnvironmentsListWebWorkerMetricDefinitionsOptionalParams, AppServiceEnvironmentsListWorkerPoolSkusNextOptionalParams, AppServiceEnvironmentsListWorkerPoolSkusOptionalParams, AppServiceEnvironmentsListWebWorkerUsagesNextOptionalParams, AppServiceEnvironmentsListWebWorkerUsagesOptionalParams, AppServiceEnvironmentsListResponse, AppServiceEnvironmentsListByResourceGroupResponse, AppServiceEnvironmentsGetOptionalParams, AppServiceEnvironmentsGetResponse, AppServiceEnvironmentsCreateOrUpdateOptionalParams, AppServiceEnvironmentsCreateOrUpdateResponse, AppServiceEnvironmentsDeleteOptionalParams, AppServiceEnvironmentPatchResource, AppServiceEnvironmentsUpdateOptionalParams, AppServiceEnvironmentsUpdateResponse, AppServiceEnvironmentsListCapacitiesResponse, AppServiceEnvironmentsGetVipInfoOptionalParams, AppServiceEnvironmentsGetVipInfoResponse, AppServiceEnvironmentsChangeVnetResponse, AppServiceEnvironmentsListDiagnosticsOptionalParams, AppServiceEnvironmentsListDiagnosticsResponse, AppServiceEnvironmentsGetDiagnosticsItemOptionalParams, AppServiceEnvironmentsGetDiagnosticsItemResponse, AppServiceEnvironmentsGetInboundNetworkDependenciesEndpointsResponse, AppServiceEnvironmentsListMultiRolePoolsResponse, AppServiceEnvironmentsGetMultiRolePoolOptionalParams, AppServiceEnvironmentsGetMultiRolePoolResponse, AppServiceEnvironmentsCreateOrUpdateMultiRolePoolOptionalParams, AppServiceEnvironmentsCreateOrUpdateMultiRolePoolResponse, AppServiceEnvironmentsUpdateMultiRolePoolOptionalParams, AppServiceEnvironmentsUpdateMultiRolePoolResponse, AppServiceEnvironmentsListMultiRolePoolInstanceMetricDefinitionsResponse, AppServiceEnvironmentsListMultiRoleMetricDefinitionsResponse, AppServiceEnvironmentsListMultiRolePoolSkusResponse, AppServiceEnvironmentsListMultiRoleUsagesResponse, AppServiceEnvironmentsListOperationsOptionalParams, AppServiceEnvironmentsListOperationsResponse, AppServiceEnvironmentsGetOutboundNetworkDependenciesEndpointsResponse, AppServiceEnvironmentsRebootOptionalParams, AppServiceEnvironmentsResumeResponse, AppServiceEnvironmentsListAppServicePlansResponse, AppServiceEnvironmentsListWebAppsResponse, AppServiceEnvironmentsSuspendResponse, AppServiceEnvironmentsListUsagesResponse, AppServiceEnvironmentsListWorkerPoolsResponse, AppServiceEnvironmentsGetWorkerPoolOptionalParams, AppServiceEnvironmentsGetWorkerPoolResponse, AppServiceEnvironmentsCreateOrUpdateWorkerPoolOptionalParams, AppServiceEnvironmentsCreateOrUpdateWorkerPoolResponse, AppServiceEnvironmentsUpdateWorkerPoolOptionalParams, AppServiceEnvironmentsUpdateWorkerPoolResponse, AppServiceEnvironmentsListWorkerPoolInstanceMetricDefinitionsResponse, AppServiceEnvironmentsListWebWorkerMetricDefinitionsResponse, AppServiceEnvironmentsListWorkerPoolSkusResponse, AppServiceEnvironmentsListWebWorkerUsagesResponse, AppServiceEnvironmentsListNextResponse, AppServiceEnvironmentsListByResourceGroupNextResponse, AppServiceEnvironmentsListCapacitiesNextResponse, AppServiceEnvironmentsChangeVnetNextResponse, AppServiceEnvironmentsGetInboundNetworkDependenciesEndpointsNextResponse, AppServiceEnvironmentsListMultiRolePoolsNextResponse, AppServiceEnvironmentsListMultiRolePoolInstanceMetricDefinitionsNextResponse, AppServiceEnvironmentsListMultiRoleMetricDefinitionsNextResponse, AppServiceEnvironmentsListMultiRolePoolSkusNextResponse, AppServiceEnvironmentsListMultiRoleUsagesNextResponse, AppServiceEnvironmentsGetOutboundNetworkDependenciesEndpointsNextResponse, AppServiceEnvironmentsResumeNextResponse, AppServiceEnvironmentsListAppServicePlansNextResponse, AppServiceEnvironmentsListWebAppsNextResponse, AppServiceEnvironmentsSuspendNextResponse, AppServiceEnvironmentsListUsagesNextResponse, AppServiceEnvironmentsListWorkerPoolsNextResponse, AppServiceEnvironmentsListWorkerPoolInstanceMetricDefinitionsNextResponse, AppServiceEnvironmentsListWebWorkerMetricDefinitionsNextResponse, AppServiceEnvironmentsListWorkerPoolSkusNextResponse, AppServiceEnvironmentsListWebWorkerUsagesNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing AppServiceEnvironments operations. */ export class AppServiceEnvironmentsImpl implements AppServiceEnvironments { private readonly client: WebSiteManagementClient; /** * Initialize a new instance of the class AppServiceEnvironments class. * @param client Reference to the service client */ constructor(client: WebSiteManagementClient) { this.client = client; } /** * Description for Get all App Service Environments for a subscription. * @param options The options parameters. */ public list( options?: AppServiceEnvironmentsListOptionalParams ): PagedAsyncIterableIterator<AppServiceEnvironmentResource> { const iter = this.listPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(options); } }; } private async *listPagingPage( options?: AppServiceEnvironmentsListOptionalParams ): AsyncIterableIterator<AppServiceEnvironmentResource[]> { let result = await this._list(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( options?: AppServiceEnvironmentsListOptionalParams ): AsyncIterableIterator<AppServiceEnvironmentResource> { for await (const page of this.listPagingPage(options)) { yield* page; } } /** * Description for Get all App Service Environments in a resource group. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param options The options parameters. */ public listByResourceGroup( resourceGroupName: string, options?: AppServiceEnvironmentsListByResourceGroupOptionalParams ): PagedAsyncIterableIterator<AppServiceEnvironmentResource> { const iter = this.listByResourceGroupPagingAll(resourceGroupName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByResourceGroupPagingPage(resourceGroupName, options); } }; } private async *listByResourceGroupPagingPage( resourceGroupName: string, options?: AppServiceEnvironmentsListByResourceGroupOptionalParams ): AsyncIterableIterator<AppServiceEnvironmentResource[]> { let result = await this._listByResourceGroup(resourceGroupName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByResourceGroupNext( resourceGroupName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByResourceGroupPagingAll( resourceGroupName: string, options?: AppServiceEnvironmentsListByResourceGroupOptionalParams ): AsyncIterableIterator<AppServiceEnvironmentResource> { for await (const page of this.listByResourceGroupPagingPage( resourceGroupName, options )) { yield* page; } } /** * Description for Get the used, available, and total worker capacity an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ public listCapacities( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListCapacitiesOptionalParams ): PagedAsyncIterableIterator<StampCapacity> { const iter = this.listCapacitiesPagingAll(resourceGroupName, name, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listCapacitiesPagingPage(resourceGroupName, name, options); } }; } private async *listCapacitiesPagingPage( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListCapacitiesOptionalParams ): AsyncIterableIterator<StampCapacity[]> { let result = await this._listCapacities(resourceGroupName, name, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listCapacitiesNext( resourceGroupName, name, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listCapacitiesPagingAll( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListCapacitiesOptionalParams ): AsyncIterableIterator<StampCapacity> { for await (const page of this.listCapacitiesPagingPage( resourceGroupName, name, options )) { yield* page; } } /** * Description for Move an App Service Environment to a different VNET. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param vnetInfo Details for the new virtual network. * @param options The options parameters. */ public beginListChangeVnetAndWait( resourceGroupName: string, name: string, vnetInfo: VirtualNetworkProfile, options?: AppServiceEnvironmentsChangeVnetOptionalParams ): PagedAsyncIterableIterator<Site> { const iter = this.changeVnetPagingAll( resourceGroupName, name, vnetInfo, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.changeVnetPagingPage( resourceGroupName, name, vnetInfo, options ); } }; } private async *changeVnetPagingPage( resourceGroupName: string, name: string, vnetInfo: VirtualNetworkProfile, options?: AppServiceEnvironmentsChangeVnetOptionalParams ): AsyncIterableIterator<Site[]> { const poller = await this._changeVnet( resourceGroupName, name, vnetInfo, options ); let result: any = await poller.pollUntilDone(); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._changeVnetNext( resourceGroupName, name, vnetInfo, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *changeVnetPagingAll( resourceGroupName: string, name: string, vnetInfo: VirtualNetworkProfile, options?: AppServiceEnvironmentsChangeVnetOptionalParams ): AsyncIterableIterator<Site> { for await (const page of this.changeVnetPagingPage( resourceGroupName, name, vnetInfo, options )) { yield* page; } } /** * Description for Get the network endpoints of all inbound dependencies of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ public listInboundNetworkDependenciesEndpoints( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsGetInboundNetworkDependenciesEndpointsOptionalParams ): PagedAsyncIterableIterator<InboundEnvironmentEndpoint> { const iter = this.getInboundNetworkDependenciesEndpointsPagingAll( resourceGroupName, name, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.getInboundNetworkDependenciesEndpointsPagingPage( resourceGroupName, name, options ); } }; } private async *getInboundNetworkDependenciesEndpointsPagingPage( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsGetInboundNetworkDependenciesEndpointsOptionalParams ): AsyncIterableIterator<InboundEnvironmentEndpoint[]> { let result = await this._getInboundNetworkDependenciesEndpoints( resourceGroupName, name, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._getInboundNetworkDependenciesEndpointsNext( resourceGroupName, name, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *getInboundNetworkDependenciesEndpointsPagingAll( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsGetInboundNetworkDependenciesEndpointsOptionalParams ): AsyncIterableIterator<InboundEnvironmentEndpoint> { for await (const page of this.getInboundNetworkDependenciesEndpointsPagingPage( resourceGroupName, name, options )) { yield* page; } } /** * Description for Get all multi-role pools. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ public listMultiRolePools( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListMultiRolePoolsOptionalParams ): PagedAsyncIterableIterator<WorkerPoolResource> { const iter = this.listMultiRolePoolsPagingAll( resourceGroupName, name, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listMultiRolePoolsPagingPage( resourceGroupName, name, options ); } }; } private async *listMultiRolePoolsPagingPage( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListMultiRolePoolsOptionalParams ): AsyncIterableIterator<WorkerPoolResource[]> { let result = await this._listMultiRolePools( resourceGroupName, name, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listMultiRolePoolsNext( resourceGroupName, name, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listMultiRolePoolsPagingAll( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListMultiRolePoolsOptionalParams ): AsyncIterableIterator<WorkerPoolResource> { for await (const page of this.listMultiRolePoolsPagingPage( resourceGroupName, name, options )) { yield* page; } } /** * Description for Get metric definitions for a specific instance of a multi-role pool of an App * Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param instance Name of the instance in the multi-role pool. * @param options The options parameters. */ public listMultiRolePoolInstanceMetricDefinitions( resourceGroupName: string, name: string, instance: string, options?: AppServiceEnvironmentsListMultiRolePoolInstanceMetricDefinitionsOptionalParams ): PagedAsyncIterableIterator<ResourceMetricDefinition> { const iter = this.listMultiRolePoolInstanceMetricDefinitionsPagingAll( resourceGroupName, name, instance, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listMultiRolePoolInstanceMetricDefinitionsPagingPage( resourceGroupName, name, instance, options ); } }; } private async *listMultiRolePoolInstanceMetricDefinitionsPagingPage( resourceGroupName: string, name: string, instance: string, options?: AppServiceEnvironmentsListMultiRolePoolInstanceMetricDefinitionsOptionalParams ): AsyncIterableIterator<ResourceMetricDefinition[]> { let result = await this._listMultiRolePoolInstanceMetricDefinitions( resourceGroupName, name, instance, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listMultiRolePoolInstanceMetricDefinitionsNext( resourceGroupName, name, instance, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listMultiRolePoolInstanceMetricDefinitionsPagingAll( resourceGroupName: string, name: string, instance: string, options?: AppServiceEnvironmentsListMultiRolePoolInstanceMetricDefinitionsOptionalParams ): AsyncIterableIterator<ResourceMetricDefinition> { for await (const page of this.listMultiRolePoolInstanceMetricDefinitionsPagingPage( resourceGroupName, name, instance, options )) { yield* page; } } /** * Description for Get metric definitions for a multi-role pool of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ public listMultiRoleMetricDefinitions( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListMultiRoleMetricDefinitionsOptionalParams ): PagedAsyncIterableIterator<ResourceMetricDefinition> { const iter = this.listMultiRoleMetricDefinitionsPagingAll( resourceGroupName, name, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listMultiRoleMetricDefinitionsPagingPage( resourceGroupName, name, options ); } }; } private async *listMultiRoleMetricDefinitionsPagingPage( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListMultiRoleMetricDefinitionsOptionalParams ): AsyncIterableIterator<ResourceMetricDefinition[]> { let result = await this._listMultiRoleMetricDefinitions( resourceGroupName, name, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listMultiRoleMetricDefinitionsNext( resourceGroupName, name, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listMultiRoleMetricDefinitionsPagingAll( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListMultiRoleMetricDefinitionsOptionalParams ): AsyncIterableIterator<ResourceMetricDefinition> { for await (const page of this.listMultiRoleMetricDefinitionsPagingPage( resourceGroupName, name, options )) { yield* page; } } /** * Description for Get available SKUs for scaling a multi-role pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ public listMultiRolePoolSkus( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListMultiRolePoolSkusOptionalParams ): PagedAsyncIterableIterator<SkuInfo> { const iter = this.listMultiRolePoolSkusPagingAll( resourceGroupName, name, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listMultiRolePoolSkusPagingPage( resourceGroupName, name, options ); } }; } private async *listMultiRolePoolSkusPagingPage( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListMultiRolePoolSkusOptionalParams ): AsyncIterableIterator<SkuInfo[]> { let result = await this._listMultiRolePoolSkus( resourceGroupName, name, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listMultiRolePoolSkusNext( resourceGroupName, name, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listMultiRolePoolSkusPagingAll( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListMultiRolePoolSkusOptionalParams ): AsyncIterableIterator<SkuInfo> { for await (const page of this.listMultiRolePoolSkusPagingPage( resourceGroupName, name, options )) { yield* page; } } /** * Description for Get usage metrics for a multi-role pool of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ public listMultiRoleUsages( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListMultiRoleUsagesOptionalParams ): PagedAsyncIterableIterator<Usage> { const iter = this.listMultiRoleUsagesPagingAll( resourceGroupName, name, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listMultiRoleUsagesPagingPage( resourceGroupName, name, options ); } }; } private async *listMultiRoleUsagesPagingPage( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListMultiRoleUsagesOptionalParams ): AsyncIterableIterator<Usage[]> { let result = await this._listMultiRoleUsages( resourceGroupName, name, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listMultiRoleUsagesNext( resourceGroupName, name, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listMultiRoleUsagesPagingAll( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListMultiRoleUsagesOptionalParams ): AsyncIterableIterator<Usage> { for await (const page of this.listMultiRoleUsagesPagingPage( resourceGroupName, name, options )) { yield* page; } } /** * Description for Get the network endpoints of all outbound dependencies of an App Service * Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ public listOutboundNetworkDependenciesEndpoints( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsGetOutboundNetworkDependenciesEndpointsOptionalParams ): PagedAsyncIterableIterator<OutboundEnvironmentEndpoint> { const iter = this.getOutboundNetworkDependenciesEndpointsPagingAll( resourceGroupName, name, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.getOutboundNetworkDependenciesEndpointsPagingPage( resourceGroupName, name, options ); } }; } private async *getOutboundNetworkDependenciesEndpointsPagingPage( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsGetOutboundNetworkDependenciesEndpointsOptionalParams ): AsyncIterableIterator<OutboundEnvironmentEndpoint[]> { let result = await this._getOutboundNetworkDependenciesEndpoints( resourceGroupName, name, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._getOutboundNetworkDependenciesEndpointsNext( resourceGroupName, name, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *getOutboundNetworkDependenciesEndpointsPagingAll( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsGetOutboundNetworkDependenciesEndpointsOptionalParams ): AsyncIterableIterator<OutboundEnvironmentEndpoint> { for await (const page of this.getOutboundNetworkDependenciesEndpointsPagingPage( resourceGroupName, name, options )) { yield* page; } } /** * Description for Resume an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ public beginListResumeAndWait( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsResumeOptionalParams ): PagedAsyncIterableIterator<Site> { const iter = this.resumePagingAll(resourceGroupName, name, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.resumePagingPage(resourceGroupName, name, options); } }; } private async *resumePagingPage( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsResumeOptionalParams ): AsyncIterableIterator<Site[]> { const poller = await this._resume(resourceGroupName, name, options); let result: any = await poller.pollUntilDone(); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._resumeNext( resourceGroupName, name, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *resumePagingAll( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsResumeOptionalParams ): AsyncIterableIterator<Site> { for await (const page of this.resumePagingPage( resourceGroupName, name, options )) { yield* page; } } /** * Description for Get all App Service plans in an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ public listAppServicePlans( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListAppServicePlansOptionalParams ): PagedAsyncIterableIterator<AppServicePlan> { const iter = this.listAppServicePlansPagingAll( resourceGroupName, name, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listAppServicePlansPagingPage( resourceGroupName, name, options ); } }; } private async *listAppServicePlansPagingPage( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListAppServicePlansOptionalParams ): AsyncIterableIterator<AppServicePlan[]> { let result = await this._listAppServicePlans( resourceGroupName, name, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listAppServicePlansNext( resourceGroupName, name, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listAppServicePlansPagingAll( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListAppServicePlansOptionalParams ): AsyncIterableIterator<AppServicePlan> { for await (const page of this.listAppServicePlansPagingPage( resourceGroupName, name, options )) { yield* page; } } /** * Description for Get all apps in an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ public listWebApps( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListWebAppsOptionalParams ): PagedAsyncIterableIterator<Site> { const iter = this.listWebAppsPagingAll(resourceGroupName, name, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listWebAppsPagingPage(resourceGroupName, name, options); } }; } private async *listWebAppsPagingPage( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListWebAppsOptionalParams ): AsyncIterableIterator<Site[]> { let result = await this._listWebApps(resourceGroupName, name, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listWebAppsNext( resourceGroupName, name, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listWebAppsPagingAll( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListWebAppsOptionalParams ): AsyncIterableIterator<Site> { for await (const page of this.listWebAppsPagingPage( resourceGroupName, name, options )) { yield* page; } } /** * Description for Suspend an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ public beginListSuspendAndWait( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsSuspendOptionalParams ): PagedAsyncIterableIterator<Site> { const iter = this.suspendPagingAll(resourceGroupName, name, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.suspendPagingPage(resourceGroupName, name, options); } }; } private async *suspendPagingPage( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsSuspendOptionalParams ): AsyncIterableIterator<Site[]> { const poller = await this._suspend(resourceGroupName, name, options); let result: any = await poller.pollUntilDone(); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._suspendNext( resourceGroupName, name, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *suspendPagingAll( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsSuspendOptionalParams ): AsyncIterableIterator<Site> { for await (const page of this.suspendPagingPage( resourceGroupName, name, options )) { yield* page; } } /** * Description for Get global usage metrics of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ public listUsages( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListUsagesOptionalParams ): PagedAsyncIterableIterator<CsmUsageQuota> { const iter = this.listUsagesPagingAll(resourceGroupName, name, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listUsagesPagingPage(resourceGroupName, name, options); } }; } private async *listUsagesPagingPage( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListUsagesOptionalParams ): AsyncIterableIterator<CsmUsageQuota[]> { let result = await this._listUsages(resourceGroupName, name, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listUsagesNext( resourceGroupName, name, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listUsagesPagingAll( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListUsagesOptionalParams ): AsyncIterableIterator<CsmUsageQuota> { for await (const page of this.listUsagesPagingPage( resourceGroupName, name, options )) { yield* page; } } /** * Description for Get all worker pools of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ public listWorkerPools( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListWorkerPoolsOptionalParams ): PagedAsyncIterableIterator<WorkerPoolResource> { const iter = this.listWorkerPoolsPagingAll( resourceGroupName, name, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listWorkerPoolsPagingPage(resourceGroupName, name, options); } }; } private async *listWorkerPoolsPagingPage( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListWorkerPoolsOptionalParams ): AsyncIterableIterator<WorkerPoolResource[]> { let result = await this._listWorkerPools(resourceGroupName, name, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listWorkerPoolsNext( resourceGroupName, name, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listWorkerPoolsPagingAll( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListWorkerPoolsOptionalParams ): AsyncIterableIterator<WorkerPoolResource> { for await (const page of this.listWorkerPoolsPagingPage( resourceGroupName, name, options )) { yield* page; } } /** * Description for Get metric definitions for a specific instance of a worker pool of an App Service * Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param instance Name of the instance in the worker pool. * @param options The options parameters. */ public listWorkerPoolInstanceMetricDefinitions( resourceGroupName: string, name: string, workerPoolName: string, instance: string, options?: AppServiceEnvironmentsListWorkerPoolInstanceMetricDefinitionsOptionalParams ): PagedAsyncIterableIterator<ResourceMetricDefinition> { const iter = this.listWorkerPoolInstanceMetricDefinitionsPagingAll( resourceGroupName, name, workerPoolName, instance, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listWorkerPoolInstanceMetricDefinitionsPagingPage( resourceGroupName, name, workerPoolName, instance, options ); } }; } private async *listWorkerPoolInstanceMetricDefinitionsPagingPage( resourceGroupName: string, name: string, workerPoolName: string, instance: string, options?: AppServiceEnvironmentsListWorkerPoolInstanceMetricDefinitionsOptionalParams ): AsyncIterableIterator<ResourceMetricDefinition[]> { let result = await this._listWorkerPoolInstanceMetricDefinitions( resourceGroupName, name, workerPoolName, instance, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listWorkerPoolInstanceMetricDefinitionsNext( resourceGroupName, name, workerPoolName, instance, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listWorkerPoolInstanceMetricDefinitionsPagingAll( resourceGroupName: string, name: string, workerPoolName: string, instance: string, options?: AppServiceEnvironmentsListWorkerPoolInstanceMetricDefinitionsOptionalParams ): AsyncIterableIterator<ResourceMetricDefinition> { for await (const page of this.listWorkerPoolInstanceMetricDefinitionsPagingPage( resourceGroupName, name, workerPoolName, instance, options )) { yield* page; } } /** * Description for Get metric definitions for a worker pool of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param options The options parameters. */ public listWebWorkerMetricDefinitions( resourceGroupName: string, name: string, workerPoolName: string, options?: AppServiceEnvironmentsListWebWorkerMetricDefinitionsOptionalParams ): PagedAsyncIterableIterator<ResourceMetricDefinition> { const iter = this.listWebWorkerMetricDefinitionsPagingAll( resourceGroupName, name, workerPoolName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listWebWorkerMetricDefinitionsPagingPage( resourceGroupName, name, workerPoolName, options ); } }; } private async *listWebWorkerMetricDefinitionsPagingPage( resourceGroupName: string, name: string, workerPoolName: string, options?: AppServiceEnvironmentsListWebWorkerMetricDefinitionsOptionalParams ): AsyncIterableIterator<ResourceMetricDefinition[]> { let result = await this._listWebWorkerMetricDefinitions( resourceGroupName, name, workerPoolName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listWebWorkerMetricDefinitionsNext( resourceGroupName, name, workerPoolName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listWebWorkerMetricDefinitionsPagingAll( resourceGroupName: string, name: string, workerPoolName: string, options?: AppServiceEnvironmentsListWebWorkerMetricDefinitionsOptionalParams ): AsyncIterableIterator<ResourceMetricDefinition> { for await (const page of this.listWebWorkerMetricDefinitionsPagingPage( resourceGroupName, name, workerPoolName, options )) { yield* page; } } /** * Description for Get available SKUs for scaling a worker pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param options The options parameters. */ public listWorkerPoolSkus( resourceGroupName: string, name: string, workerPoolName: string, options?: AppServiceEnvironmentsListWorkerPoolSkusOptionalParams ): PagedAsyncIterableIterator<SkuInfo> { const iter = this.listWorkerPoolSkusPagingAll( resourceGroupName, name, workerPoolName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listWorkerPoolSkusPagingPage( resourceGroupName, name, workerPoolName, options ); } }; } private async *listWorkerPoolSkusPagingPage( resourceGroupName: string, name: string, workerPoolName: string, options?: AppServiceEnvironmentsListWorkerPoolSkusOptionalParams ): AsyncIterableIterator<SkuInfo[]> { let result = await this._listWorkerPoolSkus( resourceGroupName, name, workerPoolName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listWorkerPoolSkusNext( resourceGroupName, name, workerPoolName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listWorkerPoolSkusPagingAll( resourceGroupName: string, name: string, workerPoolName: string, options?: AppServiceEnvironmentsListWorkerPoolSkusOptionalParams ): AsyncIterableIterator<SkuInfo> { for await (const page of this.listWorkerPoolSkusPagingPage( resourceGroupName, name, workerPoolName, options )) { yield* page; } } /** * Description for Get usage metrics for a worker pool of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param options The options parameters. */ public listWebWorkerUsages( resourceGroupName: string, name: string, workerPoolName: string, options?: AppServiceEnvironmentsListWebWorkerUsagesOptionalParams ): PagedAsyncIterableIterator<Usage> { const iter = this.listWebWorkerUsagesPagingAll( resourceGroupName, name, workerPoolName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listWebWorkerUsagesPagingPage( resourceGroupName, name, workerPoolName, options ); } }; } private async *listWebWorkerUsagesPagingPage( resourceGroupName: string, name: string, workerPoolName: string, options?: AppServiceEnvironmentsListWebWorkerUsagesOptionalParams ): AsyncIterableIterator<Usage[]> { let result = await this._listWebWorkerUsages( resourceGroupName, name, workerPoolName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listWebWorkerUsagesNext( resourceGroupName, name, workerPoolName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listWebWorkerUsagesPagingAll( resourceGroupName: string, name: string, workerPoolName: string, options?: AppServiceEnvironmentsListWebWorkerUsagesOptionalParams ): AsyncIterableIterator<Usage> { for await (const page of this.listWebWorkerUsagesPagingPage( resourceGroupName, name, workerPoolName, options )) { yield* page; } } /** * Description for Get all App Service Environments for a subscription. * @param options The options parameters. */ private _list( options?: AppServiceEnvironmentsListOptionalParams ): Promise<AppServiceEnvironmentsListResponse> { return this.client.sendOperationRequest({ options }, listOperationSpec); } /** * Description for Get all App Service Environments in a resource group. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param options The options parameters. */ private _listByResourceGroup( resourceGroupName: string, options?: AppServiceEnvironmentsListByResourceGroupOptionalParams ): Promise<AppServiceEnvironmentsListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec ); } /** * Description for Get the properties of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ get( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsGetOptionalParams ): Promise<AppServiceEnvironmentsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, getOperationSpec ); } /** * Description for Create or update an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param hostingEnvironmentEnvelope Configuration details of the App Service Environment. * @param options The options parameters. */ async beginCreateOrUpdate( resourceGroupName: string, name: string, hostingEnvironmentEnvelope: AppServiceEnvironmentResource, options?: AppServiceEnvironmentsCreateOrUpdateOptionalParams ): Promise< PollerLike< PollOperationState<AppServiceEnvironmentsCreateOrUpdateResponse>, AppServiceEnvironmentsCreateOrUpdateResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<AppServiceEnvironmentsCreateOrUpdateResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, name, hostingEnvironmentEnvelope, options }, createOrUpdateOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Description for Create or update an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param hostingEnvironmentEnvelope Configuration details of the App Service Environment. * @param options The options parameters. */ async beginCreateOrUpdateAndWait( resourceGroupName: string, name: string, hostingEnvironmentEnvelope: AppServiceEnvironmentResource, options?: AppServiceEnvironmentsCreateOrUpdateOptionalParams ): Promise<AppServiceEnvironmentsCreateOrUpdateResponse> { const poller = await this.beginCreateOrUpdate( resourceGroupName, name, hostingEnvironmentEnvelope, options ); return poller.pollUntilDone(); } /** * Description for Delete an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ async beginDelete( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, name, options }, deleteOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Description for Delete an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ async beginDeleteAndWait( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsDeleteOptionalParams ): Promise<void> { const poller = await this.beginDelete(resourceGroupName, name, options); return poller.pollUntilDone(); } /** * Description for Create or update an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param hostingEnvironmentEnvelope Configuration details of the App Service Environment. * @param options The options parameters. */ update( resourceGroupName: string, name: string, hostingEnvironmentEnvelope: AppServiceEnvironmentPatchResource, options?: AppServiceEnvironmentsUpdateOptionalParams ): Promise<AppServiceEnvironmentsUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, hostingEnvironmentEnvelope, options }, updateOperationSpec ); } /** * Description for Get the used, available, and total worker capacity an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ private _listCapacities( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListCapacitiesOptionalParams ): Promise<AppServiceEnvironmentsListCapacitiesResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, listCapacitiesOperationSpec ); } /** * Description for Get IP addresses assigned to an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ getVipInfo( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsGetVipInfoOptionalParams ): Promise<AppServiceEnvironmentsGetVipInfoResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, getVipInfoOperationSpec ); } /** * Description for Move an App Service Environment to a different VNET. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param vnetInfo Details for the new virtual network. * @param options The options parameters. */ private async _changeVnet( resourceGroupName: string, name: string, vnetInfo: VirtualNetworkProfile, options?: AppServiceEnvironmentsChangeVnetOptionalParams ): Promise< PollerLike< PollOperationState<AppServiceEnvironmentsChangeVnetResponse>, AppServiceEnvironmentsChangeVnetResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<AppServiceEnvironmentsChangeVnetResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, name, vnetInfo, options }, changeVnetOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Description for Get diagnostic information for an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ listDiagnostics( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListDiagnosticsOptionalParams ): Promise<AppServiceEnvironmentsListDiagnosticsResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, listDiagnosticsOperationSpec ); } /** * Description for Get a diagnostics item for an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param diagnosticsName Name of the diagnostics item. * @param options The options parameters. */ getDiagnosticsItem( resourceGroupName: string, name: string, diagnosticsName: string, options?: AppServiceEnvironmentsGetDiagnosticsItemOptionalParams ): Promise<AppServiceEnvironmentsGetDiagnosticsItemResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, diagnosticsName, options }, getDiagnosticsItemOperationSpec ); } /** * Description for Get the network endpoints of all inbound dependencies of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ private _getInboundNetworkDependenciesEndpoints( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsGetInboundNetworkDependenciesEndpointsOptionalParams ): Promise< AppServiceEnvironmentsGetInboundNetworkDependenciesEndpointsResponse > { return this.client.sendOperationRequest( { resourceGroupName, name, options }, getInboundNetworkDependenciesEndpointsOperationSpec ); } /** * Description for Get all multi-role pools. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ private _listMultiRolePools( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListMultiRolePoolsOptionalParams ): Promise<AppServiceEnvironmentsListMultiRolePoolsResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, listMultiRolePoolsOperationSpec ); } /** * Description for Get properties of a multi-role pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ getMultiRolePool( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsGetMultiRolePoolOptionalParams ): Promise<AppServiceEnvironmentsGetMultiRolePoolResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, getMultiRolePoolOperationSpec ); } /** * Description for Create or update a multi-role pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param multiRolePoolEnvelope Properties of the multi-role pool. * @param options The options parameters. */ async beginCreateOrUpdateMultiRolePool( resourceGroupName: string, name: string, multiRolePoolEnvelope: WorkerPoolResource, options?: AppServiceEnvironmentsCreateOrUpdateMultiRolePoolOptionalParams ): Promise< PollerLike< PollOperationState< AppServiceEnvironmentsCreateOrUpdateMultiRolePoolResponse >, AppServiceEnvironmentsCreateOrUpdateMultiRolePoolResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<AppServiceEnvironmentsCreateOrUpdateMultiRolePoolResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, name, multiRolePoolEnvelope, options }, createOrUpdateMultiRolePoolOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Description for Create or update a multi-role pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param multiRolePoolEnvelope Properties of the multi-role pool. * @param options The options parameters. */ async beginCreateOrUpdateMultiRolePoolAndWait( resourceGroupName: string, name: string, multiRolePoolEnvelope: WorkerPoolResource, options?: AppServiceEnvironmentsCreateOrUpdateMultiRolePoolOptionalParams ): Promise<AppServiceEnvironmentsCreateOrUpdateMultiRolePoolResponse> { const poller = await this.beginCreateOrUpdateMultiRolePool( resourceGroupName, name, multiRolePoolEnvelope, options ); return poller.pollUntilDone(); } /** * Description for Create or update a multi-role pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param multiRolePoolEnvelope Properties of the multi-role pool. * @param options The options parameters. */ updateMultiRolePool( resourceGroupName: string, name: string, multiRolePoolEnvelope: WorkerPoolResource, options?: AppServiceEnvironmentsUpdateMultiRolePoolOptionalParams ): Promise<AppServiceEnvironmentsUpdateMultiRolePoolResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, multiRolePoolEnvelope, options }, updateMultiRolePoolOperationSpec ); } /** * Description for Get metric definitions for a specific instance of a multi-role pool of an App * Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param instance Name of the instance in the multi-role pool. * @param options The options parameters. */ private _listMultiRolePoolInstanceMetricDefinitions( resourceGroupName: string, name: string, instance: string, options?: AppServiceEnvironmentsListMultiRolePoolInstanceMetricDefinitionsOptionalParams ): Promise< AppServiceEnvironmentsListMultiRolePoolInstanceMetricDefinitionsResponse > { return this.client.sendOperationRequest( { resourceGroupName, name, instance, options }, listMultiRolePoolInstanceMetricDefinitionsOperationSpec ); } /** * Description for Get metric definitions for a multi-role pool of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ private _listMultiRoleMetricDefinitions( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListMultiRoleMetricDefinitionsOptionalParams ): Promise<AppServiceEnvironmentsListMultiRoleMetricDefinitionsResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, listMultiRoleMetricDefinitionsOperationSpec ); } /** * Description for Get available SKUs for scaling a multi-role pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ private _listMultiRolePoolSkus( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListMultiRolePoolSkusOptionalParams ): Promise<AppServiceEnvironmentsListMultiRolePoolSkusResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, listMultiRolePoolSkusOperationSpec ); } /** * Description for Get usage metrics for a multi-role pool of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ private _listMultiRoleUsages( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListMultiRoleUsagesOptionalParams ): Promise<AppServiceEnvironmentsListMultiRoleUsagesResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, listMultiRoleUsagesOperationSpec ); } /** * Description for List all currently running operations on the App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ listOperations( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListOperationsOptionalParams ): Promise<AppServiceEnvironmentsListOperationsResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, listOperationsOperationSpec ); } /** * Description for Get the network endpoints of all outbound dependencies of an App Service * Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ private _getOutboundNetworkDependenciesEndpoints( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsGetOutboundNetworkDependenciesEndpointsOptionalParams ): Promise< AppServiceEnvironmentsGetOutboundNetworkDependenciesEndpointsResponse > { return this.client.sendOperationRequest( { resourceGroupName, name, options }, getOutboundNetworkDependenciesEndpointsOperationSpec ); } /** * Description for Reboot all machines in an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ reboot( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsRebootOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, rebootOperationSpec ); } /** * Description for Resume an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ private async _resume( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsResumeOptionalParams ): Promise< PollerLike< PollOperationState<AppServiceEnvironmentsResumeResponse>, AppServiceEnvironmentsResumeResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<AppServiceEnvironmentsResumeResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, name, options }, resumeOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Description for Get all App Service plans in an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ private _listAppServicePlans( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListAppServicePlansOptionalParams ): Promise<AppServiceEnvironmentsListAppServicePlansResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, listAppServicePlansOperationSpec ); } /** * Description for Get all apps in an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ private _listWebApps( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListWebAppsOptionalParams ): Promise<AppServiceEnvironmentsListWebAppsResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, listWebAppsOperationSpec ); } /** * Description for Suspend an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ private async _suspend( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsSuspendOptionalParams ): Promise< PollerLike< PollOperationState<AppServiceEnvironmentsSuspendResponse>, AppServiceEnvironmentsSuspendResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<AppServiceEnvironmentsSuspendResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, name, options }, suspendOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Description for Get global usage metrics of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ private _listUsages( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListUsagesOptionalParams ): Promise<AppServiceEnvironmentsListUsagesResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, listUsagesOperationSpec ); } /** * Description for Get all worker pools of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ private _listWorkerPools( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListWorkerPoolsOptionalParams ): Promise<AppServiceEnvironmentsListWorkerPoolsResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, listWorkerPoolsOperationSpec ); } /** * Description for Get properties of a worker pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param options The options parameters. */ getWorkerPool( resourceGroupName: string, name: string, workerPoolName: string, options?: AppServiceEnvironmentsGetWorkerPoolOptionalParams ): Promise<AppServiceEnvironmentsGetWorkerPoolResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, workerPoolName, options }, getWorkerPoolOperationSpec ); } /** * Description for Create or update a worker pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param workerPoolEnvelope Properties of the worker pool. * @param options The options parameters. */ async beginCreateOrUpdateWorkerPool( resourceGroupName: string, name: string, workerPoolName: string, workerPoolEnvelope: WorkerPoolResource, options?: AppServiceEnvironmentsCreateOrUpdateWorkerPoolOptionalParams ): Promise< PollerLike< PollOperationState< AppServiceEnvironmentsCreateOrUpdateWorkerPoolResponse >, AppServiceEnvironmentsCreateOrUpdateWorkerPoolResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<AppServiceEnvironmentsCreateOrUpdateWorkerPoolResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, name, workerPoolName, workerPoolEnvelope, options }, createOrUpdateWorkerPoolOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Description for Create or update a worker pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param workerPoolEnvelope Properties of the worker pool. * @param options The options parameters. */ async beginCreateOrUpdateWorkerPoolAndWait( resourceGroupName: string, name: string, workerPoolName: string, workerPoolEnvelope: WorkerPoolResource, options?: AppServiceEnvironmentsCreateOrUpdateWorkerPoolOptionalParams ): Promise<AppServiceEnvironmentsCreateOrUpdateWorkerPoolResponse> { const poller = await this.beginCreateOrUpdateWorkerPool( resourceGroupName, name, workerPoolName, workerPoolEnvelope, options ); return poller.pollUntilDone(); } /** * Description for Create or update a worker pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param workerPoolEnvelope Properties of the worker pool. * @param options The options parameters. */ updateWorkerPool( resourceGroupName: string, name: string, workerPoolName: string, workerPoolEnvelope: WorkerPoolResource, options?: AppServiceEnvironmentsUpdateWorkerPoolOptionalParams ): Promise<AppServiceEnvironmentsUpdateWorkerPoolResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, workerPoolName, workerPoolEnvelope, options }, updateWorkerPoolOperationSpec ); } /** * Description for Get metric definitions for a specific instance of a worker pool of an App Service * Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param instance Name of the instance in the worker pool. * @param options The options parameters. */ private _listWorkerPoolInstanceMetricDefinitions( resourceGroupName: string, name: string, workerPoolName: string, instance: string, options?: AppServiceEnvironmentsListWorkerPoolInstanceMetricDefinitionsOptionalParams ): Promise< AppServiceEnvironmentsListWorkerPoolInstanceMetricDefinitionsResponse > { return this.client.sendOperationRequest( { resourceGroupName, name, workerPoolName, instance, options }, listWorkerPoolInstanceMetricDefinitionsOperationSpec ); } /** * Description for Get metric definitions for a worker pool of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param options The options parameters. */ private _listWebWorkerMetricDefinitions( resourceGroupName: string, name: string, workerPoolName: string, options?: AppServiceEnvironmentsListWebWorkerMetricDefinitionsOptionalParams ): Promise<AppServiceEnvironmentsListWebWorkerMetricDefinitionsResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, workerPoolName, options }, listWebWorkerMetricDefinitionsOperationSpec ); } /** * Description for Get available SKUs for scaling a worker pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param options The options parameters. */ private _listWorkerPoolSkus( resourceGroupName: string, name: string, workerPoolName: string, options?: AppServiceEnvironmentsListWorkerPoolSkusOptionalParams ): Promise<AppServiceEnvironmentsListWorkerPoolSkusResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, workerPoolName, options }, listWorkerPoolSkusOperationSpec ); } /** * Description for Get usage metrics for a worker pool of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param options The options parameters. */ private _listWebWorkerUsages( resourceGroupName: string, name: string, workerPoolName: string, options?: AppServiceEnvironmentsListWebWorkerUsagesOptionalParams ): Promise<AppServiceEnvironmentsListWebWorkerUsagesResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, workerPoolName, options }, listWebWorkerUsagesOperationSpec ); } /** * ListNext * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( nextLink: string, options?: AppServiceEnvironmentsListNextOptionalParams ): Promise<AppServiceEnvironmentsListNextResponse> { return this.client.sendOperationRequest( { nextLink, options }, listNextOperationSpec ); } /** * ListByResourceGroupNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param nextLink The nextLink from the previous successful call to the ListByResourceGroup method. * @param options The options parameters. */ private _listByResourceGroupNext( resourceGroupName: string, nextLink: string, options?: AppServiceEnvironmentsListByResourceGroupNextOptionalParams ): Promise<AppServiceEnvironmentsListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, nextLink, options }, listByResourceGroupNextOperationSpec ); } /** * ListCapacitiesNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param nextLink The nextLink from the previous successful call to the ListCapacities method. * @param options The options parameters. */ private _listCapacitiesNext( resourceGroupName: string, name: string, nextLink: string, options?: AppServiceEnvironmentsListCapacitiesNextOptionalParams ): Promise<AppServiceEnvironmentsListCapacitiesNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, nextLink, options }, listCapacitiesNextOperationSpec ); } /** * ChangeVnetNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param vnetInfo Details for the new virtual network. * @param nextLink The nextLink from the previous successful call to the ChangeVnet method. * @param options The options parameters. */ private _changeVnetNext( resourceGroupName: string, name: string, vnetInfo: VirtualNetworkProfile, nextLink: string, options?: AppServiceEnvironmentsChangeVnetNextOptionalParams ): Promise<AppServiceEnvironmentsChangeVnetNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, vnetInfo, nextLink, options }, changeVnetNextOperationSpec ); } /** * GetInboundNetworkDependenciesEndpointsNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param nextLink The nextLink from the previous successful call to the * GetInboundNetworkDependenciesEndpoints method. * @param options The options parameters. */ private _getInboundNetworkDependenciesEndpointsNext( resourceGroupName: string, name: string, nextLink: string, options?: AppServiceEnvironmentsGetInboundNetworkDependenciesEndpointsNextOptionalParams ): Promise< AppServiceEnvironmentsGetInboundNetworkDependenciesEndpointsNextResponse > { return this.client.sendOperationRequest( { resourceGroupName, name, nextLink, options }, getInboundNetworkDependenciesEndpointsNextOperationSpec ); } /** * ListMultiRolePoolsNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param nextLink The nextLink from the previous successful call to the ListMultiRolePools method. * @param options The options parameters. */ private _listMultiRolePoolsNext( resourceGroupName: string, name: string, nextLink: string, options?: AppServiceEnvironmentsListMultiRolePoolsNextOptionalParams ): Promise<AppServiceEnvironmentsListMultiRolePoolsNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, nextLink, options }, listMultiRolePoolsNextOperationSpec ); } /** * ListMultiRolePoolInstanceMetricDefinitionsNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param instance Name of the instance in the multi-role pool. * @param nextLink The nextLink from the previous successful call to the * ListMultiRolePoolInstanceMetricDefinitions method. * @param options The options parameters. */ private _listMultiRolePoolInstanceMetricDefinitionsNext( resourceGroupName: string, name: string, instance: string, nextLink: string, options?: AppServiceEnvironmentsListMultiRolePoolInstanceMetricDefinitionsNextOptionalParams ): Promise< AppServiceEnvironmentsListMultiRolePoolInstanceMetricDefinitionsNextResponse > { return this.client.sendOperationRequest( { resourceGroupName, name, instance, nextLink, options }, listMultiRolePoolInstanceMetricDefinitionsNextOperationSpec ); } /** * ListMultiRoleMetricDefinitionsNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param nextLink The nextLink from the previous successful call to the ListMultiRoleMetricDefinitions * method. * @param options The options parameters. */ private _listMultiRoleMetricDefinitionsNext( resourceGroupName: string, name: string, nextLink: string, options?: AppServiceEnvironmentsListMultiRoleMetricDefinitionsNextOptionalParams ): Promise<AppServiceEnvironmentsListMultiRoleMetricDefinitionsNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, nextLink, options }, listMultiRoleMetricDefinitionsNextOperationSpec ); } /** * ListMultiRolePoolSkusNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param nextLink The nextLink from the previous successful call to the ListMultiRolePoolSkus method. * @param options The options parameters. */ private _listMultiRolePoolSkusNext( resourceGroupName: string, name: string, nextLink: string, options?: AppServiceEnvironmentsListMultiRolePoolSkusNextOptionalParams ): Promise<AppServiceEnvironmentsListMultiRolePoolSkusNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, nextLink, options }, listMultiRolePoolSkusNextOperationSpec ); } /** * ListMultiRoleUsagesNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param nextLink The nextLink from the previous successful call to the ListMultiRoleUsages method. * @param options The options parameters. */ private _listMultiRoleUsagesNext( resourceGroupName: string, name: string, nextLink: string, options?: AppServiceEnvironmentsListMultiRoleUsagesNextOptionalParams ): Promise<AppServiceEnvironmentsListMultiRoleUsagesNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, nextLink, options }, listMultiRoleUsagesNextOperationSpec ); } /** * GetOutboundNetworkDependenciesEndpointsNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param nextLink The nextLink from the previous successful call to the * GetOutboundNetworkDependenciesEndpoints method. * @param options The options parameters. */ private _getOutboundNetworkDependenciesEndpointsNext( resourceGroupName: string, name: string, nextLink: string, options?: AppServiceEnvironmentsGetOutboundNetworkDependenciesEndpointsNextOptionalParams ): Promise< AppServiceEnvironmentsGetOutboundNetworkDependenciesEndpointsNextResponse > { return this.client.sendOperationRequest( { resourceGroupName, name, nextLink, options }, getOutboundNetworkDependenciesEndpointsNextOperationSpec ); } /** * ResumeNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param nextLink The nextLink from the previous successful call to the Resume method. * @param options The options parameters. */ private _resumeNext( resourceGroupName: string, name: string, nextLink: string, options?: AppServiceEnvironmentsResumeNextOptionalParams ): Promise<AppServiceEnvironmentsResumeNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, nextLink, options }, resumeNextOperationSpec ); } /** * ListAppServicePlansNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param nextLink The nextLink from the previous successful call to the ListAppServicePlans method. * @param options The options parameters. */ private _listAppServicePlansNext( resourceGroupName: string, name: string, nextLink: string, options?: AppServiceEnvironmentsListAppServicePlansNextOptionalParams ): Promise<AppServiceEnvironmentsListAppServicePlansNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, nextLink, options }, listAppServicePlansNextOperationSpec ); } /** * ListWebAppsNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param nextLink The nextLink from the previous successful call to the ListWebApps method. * @param options The options parameters. */ private _listWebAppsNext( resourceGroupName: string, name: string, nextLink: string, options?: AppServiceEnvironmentsListWebAppsNextOptionalParams ): Promise<AppServiceEnvironmentsListWebAppsNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, nextLink, options }, listWebAppsNextOperationSpec ); } /** * SuspendNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param nextLink The nextLink from the previous successful call to the Suspend method. * @param options The options parameters. */ private _suspendNext( resourceGroupName: string, name: string, nextLink: string, options?: AppServiceEnvironmentsSuspendNextOptionalParams ): Promise<AppServiceEnvironmentsSuspendNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, nextLink, options }, suspendNextOperationSpec ); } /** * ListUsagesNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param nextLink The nextLink from the previous successful call to the ListUsages method. * @param options The options parameters. */ private _listUsagesNext( resourceGroupName: string, name: string, nextLink: string, options?: AppServiceEnvironmentsListUsagesNextOptionalParams ): Promise<AppServiceEnvironmentsListUsagesNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, nextLink, options }, listUsagesNextOperationSpec ); } /** * ListWorkerPoolsNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param nextLink The nextLink from the previous successful call to the ListWorkerPools method. * @param options The options parameters. */ private _listWorkerPoolsNext( resourceGroupName: string, name: string, nextLink: string, options?: AppServiceEnvironmentsListWorkerPoolsNextOptionalParams ): Promise<AppServiceEnvironmentsListWorkerPoolsNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, nextLink, options }, listWorkerPoolsNextOperationSpec ); } /** * ListWorkerPoolInstanceMetricDefinitionsNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param instance Name of the instance in the worker pool. * @param nextLink The nextLink from the previous successful call to the * ListWorkerPoolInstanceMetricDefinitions method. * @param options The options parameters. */ private _listWorkerPoolInstanceMetricDefinitionsNext( resourceGroupName: string, name: string, workerPoolName: string, instance: string, nextLink: string, options?: AppServiceEnvironmentsListWorkerPoolInstanceMetricDefinitionsNextOptionalParams ): Promise< AppServiceEnvironmentsListWorkerPoolInstanceMetricDefinitionsNextResponse > { return this.client.sendOperationRequest( { resourceGroupName, name, workerPoolName, instance, nextLink, options }, listWorkerPoolInstanceMetricDefinitionsNextOperationSpec ); } /** * ListWebWorkerMetricDefinitionsNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param nextLink The nextLink from the previous successful call to the ListWebWorkerMetricDefinitions * method. * @param options The options parameters. */ private _listWebWorkerMetricDefinitionsNext( resourceGroupName: string, name: string, workerPoolName: string, nextLink: string, options?: AppServiceEnvironmentsListWebWorkerMetricDefinitionsNextOptionalParams ): Promise<AppServiceEnvironmentsListWebWorkerMetricDefinitionsNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, workerPoolName, nextLink, options }, listWebWorkerMetricDefinitionsNextOperationSpec ); } /** * ListWorkerPoolSkusNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param nextLink The nextLink from the previous successful call to the ListWorkerPoolSkus method. * @param options The options parameters. */ private _listWorkerPoolSkusNext( resourceGroupName: string, name: string, workerPoolName: string, nextLink: string, options?: AppServiceEnvironmentsListWorkerPoolSkusNextOptionalParams ): Promise<AppServiceEnvironmentsListWorkerPoolSkusNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, workerPoolName, nextLink, options }, listWorkerPoolSkusNextOperationSpec ); } /** * ListWebWorkerUsagesNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param nextLink The nextLink from the previous successful call to the ListWebWorkerUsages method. * @param options The options parameters. */ private _listWebWorkerUsagesNext( resourceGroupName: string, name: string, workerPoolName: string, nextLink: string, options?: AppServiceEnvironmentsListWebWorkerUsagesNextOptionalParams ): Promise<AppServiceEnvironmentsListWebWorkerUsagesNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, workerPoolName, nextLink, options }, listWebWorkerUsagesNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Web/hostingEnvironments", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AppServiceEnvironmentCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept], serializer }; const listByResourceGroupOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AppServiceEnvironmentCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AppServiceEnvironmentResource }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.AppServiceEnvironmentResource }, 201: { bodyMapper: Mappers.AppServiceEnvironmentResource }, 202: { bodyMapper: Mappers.AppServiceEnvironmentResource }, 204: { bodyMapper: Mappers.AppServiceEnvironmentResource }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, requestBody: Parameters.hostingEnvironmentEnvelope, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}", httpMethod: "DELETE", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion, Parameters.forceDelete], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.AppServiceEnvironmentResource }, 201: { bodyMapper: Mappers.AppServiceEnvironmentResource }, 202: { bodyMapper: Mappers.AppServiceEnvironmentResource }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, requestBody: Parameters.hostingEnvironmentEnvelope1, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listCapacitiesOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/capacities/compute", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StampCapacityCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const getVipInfoOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/capacities/virtualip", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AddressResponse }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const changeVnetOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/changeVirtualNetwork", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.WebAppCollection }, 201: { bodyMapper: Mappers.WebAppCollection }, 202: { bodyMapper: Mappers.WebAppCollection }, 204: { bodyMapper: Mappers.WebAppCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, requestBody: Parameters.vnetInfo, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listDiagnosticsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/diagnostics", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Composite", className: "HostingEnvironmentDiagnostics" } } } } }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const getDiagnosticsItemOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/diagnostics/{diagnosticsName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.HostingEnvironmentDiagnostics }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.diagnosticsName ], headerParameters: [Parameters.accept], serializer }; const getInboundNetworkDependenciesEndpointsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/inboundNetworkDependenciesEndpoints", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.InboundEnvironmentEndpointCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const listMultiRolePoolsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/multiRolePools", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.WorkerPoolCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const getMultiRolePoolOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/multiRolePools/default", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.WorkerPoolResource }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateMultiRolePoolOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/multiRolePools/default", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.WorkerPoolResource }, 201: { bodyMapper: Mappers.WorkerPoolResource }, 202: { bodyMapper: Mappers.WorkerPoolResource }, 204: { bodyMapper: Mappers.WorkerPoolResource }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, requestBody: Parameters.multiRolePoolEnvelope, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const updateMultiRolePoolOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/multiRolePools/default", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.WorkerPoolResource }, 202: { bodyMapper: Mappers.WorkerPoolResource }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, requestBody: Parameters.multiRolePoolEnvelope, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listMultiRolePoolInstanceMetricDefinitionsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/multiRolePools/default/instances/{instance}/metricdefinitions", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ResourceMetricDefinitionCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.instance ], headerParameters: [Parameters.accept], serializer }; const listMultiRoleMetricDefinitionsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/multiRolePools/default/metricdefinitions", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ResourceMetricDefinitionCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const listMultiRolePoolSkusOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/multiRolePools/default/skus", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SkuInfoCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const listMultiRoleUsagesOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/multiRolePools/default/usages", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.UsageCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const listOperationsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/operations", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Composite", className: "Operation" } } } } }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const getOutboundNetworkDependenciesEndpointsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/outboundNetworkDependenciesEndpoints", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.OutboundEnvironmentEndpointCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const rebootOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/reboot", httpMethod: "POST", responses: { 202: {}, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const resumeOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/resume", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.WebAppCollection }, 201: { bodyMapper: Mappers.WebAppCollection }, 202: { bodyMapper: Mappers.WebAppCollection }, 204: { bodyMapper: Mappers.WebAppCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const listAppServicePlansOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/serverfarms", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AppServicePlanCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const listWebAppsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/sites", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.WebAppCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion, Parameters.propertiesToInclude], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const suspendOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/suspend", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.WebAppCollection }, 201: { bodyMapper: Mappers.WebAppCollection }, 202: { bodyMapper: Mappers.WebAppCollection }, 204: { bodyMapper: Mappers.WebAppCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const listUsagesOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/usages", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.CsmUsageQuotaCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion, Parameters.filter], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const listWorkerPoolsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/workerPools", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.WorkerPoolCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const getWorkerPoolOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/workerPools/{workerPoolName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.WorkerPoolResource }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.workerPoolName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateWorkerPoolOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/workerPools/{workerPoolName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.WorkerPoolResource }, 201: { bodyMapper: Mappers.WorkerPoolResource }, 202: { bodyMapper: Mappers.WorkerPoolResource }, 204: { bodyMapper: Mappers.WorkerPoolResource }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, requestBody: Parameters.workerPoolEnvelope, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.workerPoolName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const updateWorkerPoolOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/workerPools/{workerPoolName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.WorkerPoolResource }, 202: { bodyMapper: Mappers.WorkerPoolResource }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, requestBody: Parameters.workerPoolEnvelope, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.workerPoolName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listWorkerPoolInstanceMetricDefinitionsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/workerPools/{workerPoolName}/instances/{instance}/metricdefinitions", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ResourceMetricDefinitionCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.instance, Parameters.workerPoolName ], headerParameters: [Parameters.accept], serializer }; const listWebWorkerMetricDefinitionsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/workerPools/{workerPoolName}/metricdefinitions", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ResourceMetricDefinitionCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.workerPoolName ], headerParameters: [Parameters.accept], serializer }; const listWorkerPoolSkusOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/workerPools/{workerPoolName}/skus", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SkuInfoCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.workerPoolName ], headerParameters: [Parameters.accept], serializer }; const listWebWorkerUsagesOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/workerPools/{workerPoolName}/usages", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.UsageCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.workerPoolName ], headerParameters: [Parameters.accept], serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AppServiceEnvironmentCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listByResourceGroupNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AppServiceEnvironmentCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listCapacitiesNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StampCapacityCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const changeVnetNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.WebAppCollection }, 202: { bodyMapper: Mappers.WebAppCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getInboundNetworkDependenciesEndpointsNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.InboundEnvironmentEndpointCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listMultiRolePoolsNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.WorkerPoolCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listMultiRolePoolInstanceMetricDefinitionsNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ResourceMetricDefinitionCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink, Parameters.instance ], headerParameters: [Parameters.accept], serializer }; const listMultiRoleMetricDefinitionsNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ResourceMetricDefinitionCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listMultiRolePoolSkusNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SkuInfoCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listMultiRoleUsagesNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.UsageCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const getOutboundNetworkDependenciesEndpointsNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.OutboundEnvironmentEndpointCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const resumeNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.WebAppCollection }, 202: { bodyMapper: Mappers.WebAppCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listAppServicePlansNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AppServicePlanCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listWebAppsNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.WebAppCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion, Parameters.propertiesToInclude], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const suspendNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.WebAppCollection }, 202: { bodyMapper: Mappers.WebAppCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listUsagesNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.CsmUsageQuotaCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion, Parameters.filter], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listWorkerPoolsNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.WorkerPoolCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listWorkerPoolInstanceMetricDefinitionsNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ResourceMetricDefinitionCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink, Parameters.instance, Parameters.workerPoolName ], headerParameters: [Parameters.accept], serializer }; const listWebWorkerMetricDefinitionsNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ResourceMetricDefinitionCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink, Parameters.workerPoolName ], headerParameters: [Parameters.accept], serializer }; const listWorkerPoolSkusNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SkuInfoCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink, Parameters.workerPoolName ], headerParameters: [Parameters.accept], serializer }; const listWebWorkerUsagesNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.UsageCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink, Parameters.workerPoolName ], headerParameters: [Parameters.accept], serializer };
the_stack
import { Konva } from './Global'; import { Transform, Util } from './Util'; import { Factory } from './Factory'; import { Node, NodeConfig } from './Node'; import { getNumberValidator, getNumberOrAutoValidator, getStringValidator, getBooleanValidator, getStringOrGradientValidator, } from './Validators'; import { Context, SceneContext } from './Context'; import { _registerNode } from './Global'; import * as PointerEvents from './PointerEvents'; import { GetSet, Vector2d } from './types'; import { HitCanvas, SceneCanvas } from './Canvas'; // hack from here https://stackoverflow.com/questions/52667959/what-is-the-purpose-of-bivariancehack-in-typescript-types/52668133#52668133 export type ShapeConfigHandler<TTarget> = { bivarianceHack(ctx: Context, shape: TTarget): void; }['bivarianceHack']; export type LineJoin = 'round' | 'bevel' | 'miter'; export type LineCap = 'butt' | 'round' | 'square'; export interface ShapeConfig extends NodeConfig { fill?: string; fillPatternImage?: HTMLImageElement; fillPatternX?: number; fillPatternY?: number; fillPatternOffset?: Vector2d; fillPatternOffsetX?: number; fillPatternOffsetY?: number; fillPatternScale?: Vector2d; fillPatternScaleX?: number; fillPatternScaleY?: number; fillPatternRotation?: number; fillPatternRepeat?: string; fillLinearGradientStartPoint?: Vector2d; fillLinearGradientStartPointX?: number; fillLinearGradientStartPointY?: number; fillLinearGradientEndPoint?: Vector2d; fillLinearGradientEndPointX?: number; fillLinearGradientEndPointY?: number; fillLinearGradientColorStops?: Array<number | string>; fillRadialGradientStartPoint?: Vector2d; fillRadialGradientStartPointX?: number; fillRadialGradientStartPointY?: number; fillRadialGradientEndPoint?: Vector2d; fillRadialGradientEndPointX?: number; fillRadialGradientEndPointY?: number; fillRadialGradientStartRadius?: number; fillRadialGradientEndRadius?: number; fillRadialGradientColorStops?: Array<number | string>; fillEnabled?: boolean; fillPriority?: string; stroke?: string | CanvasGradient; strokeWidth?: number; fillAfterStrokeEnabled?: boolean; hitStrokeWidth?: number | string; strokeScaleEnabled?: boolean; strokeHitEnabled?: boolean; strokeEnabled?: boolean; lineJoin?: LineJoin; lineCap?: LineCap; sceneFunc?: (con: Context, shape: Shape) => void; hitFunc?: (con: Context, shape: Shape) => void; shadowColor?: string; shadowBlur?: number; shadowOffset?: Vector2d; shadowOffsetX?: number; shadowOffsetY?: number; shadowOpacity?: number; shadowEnabled?: boolean; shadowForStrokeEnabled?: boolean; dash?: number[]; dashOffset?: number; dashEnabled?: boolean; perfectDrawEnabled?: boolean; } export interface ShapeGetClientRectConfig { skipTransform?: boolean; skipShadow?: boolean; skipStroke?: boolean; relativeTo?: Node; } var HAS_SHADOW = 'hasShadow'; var SHADOW_RGBA = 'shadowRGBA'; var patternImage = 'patternImage'; var linearGradient = 'linearGradient'; var radialGradient = 'radialGradient'; let dummyContext: CanvasRenderingContext2D; function getDummyContext(): CanvasRenderingContext2D { if (dummyContext) { return dummyContext; } dummyContext = Util.createCanvasElement().getContext('2d'); return dummyContext; } export const shapes: { [key: string]: Shape } = {}; // TODO: idea - use only "remove" (or destroy method) // how? on add, check that every inner shape has reference in konva store with color // on remove - clear that reference // the approach is good. But what if we want to cache the shape before we add it into the stage // what color to use for hit test? function _fillFunc(context) { context.fill(); } function _strokeFunc(context) { context.stroke(); } function _fillFuncHit(context) { context.fill(); } function _strokeFuncHit(context) { context.stroke(); } function _clearHasShadowCache() { this._clearCache(HAS_SHADOW); } function _clearGetShadowRGBACache() { this._clearCache(SHADOW_RGBA); } function _clearFillPatternCache() { this._clearCache(patternImage); } function _clearLinearGradientCache() { this._clearCache(linearGradient); } function _clearRadialGradientCache() { this._clearCache(radialGradient); } /** * Shape constructor. Shapes are primitive objects such as rectangles, * circles, text, lines, etc. * @constructor * @memberof Konva * @augments Konva.Node * @param {Object} config * @@shapeParams * @@nodeParams * @example * var customShape = new Konva.Shape({ * x: 5, * y: 10, * fill: 'red', * // a Konva.Canvas renderer is passed into the sceneFunc function * sceneFunc (context, shape) { * context.beginPath(); * context.moveTo(200, 50); * context.lineTo(420, 80); * context.quadraticCurveTo(300, 100, 260, 170); * context.closePath(); * // Konva specific method * context.fillStrokeShape(shape); * } *}); */ export class Shape< Config extends ShapeConfig = ShapeConfig > extends Node<Config> { _centroid: boolean; colorKey: string; _fillFunc: (ctx: Context) => void; _strokeFunc: (ctx: Context) => void; _fillFuncHit: (ctx: Context) => void; _strokeFuncHit: (ctx: Context) => void; constructor(config?: Config) { super(config); // set colorKey let key: string; while (true) { key = Util.getRandomColor(); if (key && !(key in shapes)) { break; } } this.colorKey = key; shapes[key] = this; } getContext() { Util.warn( 'shape.getContext() method is deprecated. Please do not use it.' ); return this.getLayer().getContext(); } getCanvas() { Util.warn('shape.getCanvas() method is deprecated. Please do not use it.'); return this.getLayer().getCanvas(); } getSceneFunc() { return this.attrs.sceneFunc || this['_sceneFunc']; } getHitFunc() { return this.attrs.hitFunc || this['_hitFunc']; } /** * returns whether or not a shadow will be rendered * @method * @name Konva.Shape#hasShadow * @returns {Boolean} */ hasShadow() { return this._getCache(HAS_SHADOW, this._hasShadow); } _hasShadow() { return ( this.shadowEnabled() && this.shadowOpacity() !== 0 && !!( this.shadowColor() || this.shadowBlur() || this.shadowOffsetX() || this.shadowOffsetY() ) ); } _getFillPattern() { return this._getCache(patternImage, this.__getFillPattern); } __getFillPattern() { if (this.fillPatternImage()) { var ctx = getDummyContext(); const pattern = ctx.createPattern( this.fillPatternImage(), this.fillPatternRepeat() || 'repeat' ); if (pattern && pattern.setTransform) { const tr = new Transform(); tr.translate(this.fillPatternX(), this.fillPatternY()); tr.rotate(Konva.getAngle(this.fillPatternRotation())); tr.scale(this.fillPatternScaleX(), this.fillPatternScaleY()); tr.translate( -1 * this.fillPatternOffsetX(), -1 * this.fillPatternOffsetY() ); const m = tr.getMatrix(); pattern.setTransform({ a: m[0], // Horizontal scaling. A value of 1 results in no scaling. b: m[1], // Vertical skewing. c: m[2], // Horizontal skewing. d: m[3], e: m[4], // Horizontal translation (moving). f: m[5], // Vertical translation (moving). }); } return pattern; } } _getLinearGradient() { return this._getCache(linearGradient, this.__getLinearGradient); } __getLinearGradient() { var colorStops = this.fillLinearGradientColorStops(); if (colorStops) { var ctx = getDummyContext(); var start = this.fillLinearGradientStartPoint(); var end = this.fillLinearGradientEndPoint(); var grd = ctx.createLinearGradient(start.x, start.y, end.x, end.y); // build color stops for (var n = 0; n < colorStops.length; n += 2) { grd.addColorStop(colorStops[n] as number, colorStops[n + 1] as string); } return grd; } } _getRadialGradient() { return this._getCache(radialGradient, this.__getRadialGradient); } __getRadialGradient() { var colorStops = this.fillRadialGradientColorStops(); if (colorStops) { var ctx = getDummyContext(); var start = this.fillRadialGradientStartPoint(); var end = this.fillRadialGradientEndPoint(); var grd = ctx.createRadialGradient( start.x, start.y, this.fillRadialGradientStartRadius(), end.x, end.y, this.fillRadialGradientEndRadius() ); // build color stops for (var n = 0; n < colorStops.length; n += 2) { grd.addColorStop(colorStops[n] as number, colorStops[n + 1] as string); } return grd; } } getShadowRGBA() { return this._getCache(SHADOW_RGBA, this._getShadowRGBA); } _getShadowRGBA() { if (this.hasShadow()) { var rgba = Util.colorToRGBA(this.shadowColor()); return ( 'rgba(' + rgba.r + ',' + rgba.g + ',' + rgba.b + ',' + rgba.a * (this.shadowOpacity() || 1) + ')' ); } } /** * returns whether or not the shape will be filled * @method * @name Konva.Shape#hasFill * @returns {Boolean} */ hasFill() { return this._calculate( 'hasFill', [ 'fillEnabled', 'fill', 'fillPatternImage', 'fillLinearGradientColorStops', 'fillRadialGradientColorStops', ], () => { return ( this.fillEnabled() && !!( this.fill() || this.fillPatternImage() || this.fillLinearGradientColorStops() || this.fillRadialGradientColorStops() ) ); } ); } /** * returns whether or not the shape will be stroked * @method * @name Konva.Shape#hasStroke * @returns {Boolean} */ hasStroke() { return this._calculate( 'hasStroke', [ 'strokeEnabled', 'strokeWidth', 'stroke', 'strokeLinearGradientColorStops', ], () => { return ( this.strokeEnabled() && this.strokeWidth() && !!(this.stroke() || this.strokeLinearGradientColorStops()) // this.getStrokeRadialGradientColorStops() ); } ); // return ( // this.strokeEnabled() && // this.strokeWidth() && // !!(this.stroke() || this.strokeLinearGradientColorStops()) // // this.getStrokeRadialGradientColorStops() // ); } hasHitStroke() { const width = this.hitStrokeWidth(); // on auto just check by stroke if (width === 'auto') { return this.hasStroke(); } // we should enable hit stroke if stroke is enabled // and we have some value from width return this.strokeEnabled() && !!width; } /** * determines if point is in the shape, regardless if other shapes are on top of it. Note: because * this method clears a temporary canvas and then redraws the shape, it performs very poorly if executed many times * consecutively. Please use the {@link Konva.Stage#getIntersection} method if at all possible * because it performs much better * @method * @name Konva.Shape#intersects * @param {Object} point * @param {Number} point.x * @param {Number} point.y * @returns {Boolean} */ intersects(point) { var stage = this.getStage(), bufferHitCanvas = stage.bufferHitCanvas, p; bufferHitCanvas.getContext().clear(); this.drawHit(bufferHitCanvas, null, true); p = bufferHitCanvas.context.getImageData( Math.round(point.x), Math.round(point.y), 1, 1 ).data; return p[3] > 0; } destroy() { Node.prototype.destroy.call(this); delete shapes[this.colorKey]; delete this.colorKey; return this; } // why do we need buffer canvas? // it give better result when a shape has // stroke with fill and with some opacity _useBufferCanvas(forceFill?: boolean): boolean { // image and sprite still has "fill" as image // so they use that method with forced fill // it probably will be simpler, then copy/paste the code // buffer canvas is available only inside the stage if (!this.getStage()) { return false; } // force skip buffer canvas const perfectDrawEnabled = this.attrs.perfectDrawEnabled ?? true; if (!perfectDrawEnabled) { return false; } const hasFill = forceFill || this.hasFill(); const hasStroke = this.hasStroke(); const isTransparent = this.getAbsoluteOpacity() !== 1; if (hasFill && hasStroke && isTransparent) { return true; } const hasShadow = this.hasShadow(); const strokeForShadow = this.shadowForStrokeEnabled(); if (hasFill && hasStroke && hasShadow && strokeForShadow) { return true; } return false; } setStrokeHitEnabled(val: number) { Util.warn( 'strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead.' ); if (val) { this.hitStrokeWidth('auto'); } else { this.hitStrokeWidth(0); } } getStrokeHitEnabled() { if (this.hitStrokeWidth() === 0) { return false; } else { return true; } } /** * return self rectangle (x, y, width, height) of shape. * This method are not taken into account transformation and styles. * @method * @name Konva.Shape#getSelfRect * @returns {Object} rect with {x, y, width, height} properties * @example * * rect.getSelfRect(); // return {x:0, y:0, width:rect.width(), height:rect.height()} * circle.getSelfRect(); // return {x: - circle.width() / 2, y: - circle.height() / 2, width:circle.width(), height:circle.height()} * */ getSelfRect() { var size = this.size(); return { x: this._centroid ? -size.width / 2 : 0, y: this._centroid ? -size.height / 2 : 0, width: size.width, height: size.height, }; } getClientRect(config: ShapeGetClientRectConfig = {}) { const skipTransform = config.skipTransform; const relativeTo = config.relativeTo; const fillRect = this.getSelfRect(); const applyStroke = !config.skipStroke && this.hasStroke(); const strokeWidth = (applyStroke && this.strokeWidth()) || 0; const fillAndStrokeWidth = fillRect.width + strokeWidth; const fillAndStrokeHeight = fillRect.height + strokeWidth; const applyShadow = !config.skipShadow && this.hasShadow(); const shadowOffsetX = applyShadow ? this.shadowOffsetX() : 0; const shadowOffsetY = applyShadow ? this.shadowOffsetY() : 0; const preWidth = fillAndStrokeWidth + Math.abs(shadowOffsetX); const preHeight = fillAndStrokeHeight + Math.abs(shadowOffsetY); const blurRadius = (applyShadow && this.shadowBlur()) || 0; const width = preWidth + blurRadius * 2; const height = preHeight + blurRadius * 2; // if stroke, for example = 3 // we need to set x to 1.5, but after Math.round it will be 2 // as we have additional offset we need to increase width and height by 1 pixel let roundingOffset = 0; if (Math.round(strokeWidth / 2) !== strokeWidth / 2) { roundingOffset = 1; } const rect = { width: width + roundingOffset, height: height + roundingOffset, x: -Math.round(strokeWidth / 2 + blurRadius) + Math.min(shadowOffsetX, 0) + fillRect.x, y: -Math.round(strokeWidth / 2 + blurRadius) + Math.min(shadowOffsetY, 0) + fillRect.y, }; if (!skipTransform) { return this._transformedRect(rect, relativeTo); } return rect; } drawScene(can?: SceneCanvas, top?: Node) { // basically there are 3 drawing modes // 1 - simple drawing when nothing is cached. // 2 - when we are caching current // 3 - when node is cached and we need to draw it into layer var layer = this.getLayer(), canvas = can || layer.getCanvas(), context = canvas.getContext() as SceneContext, cachedCanvas = this._getCanvasCache(), drawFunc = this.getSceneFunc(), hasShadow = this.hasShadow(), stage, bufferCanvas, bufferContext; var skipBuffer = canvas.isCache; var cachingSelf = top === this; if (!this.isVisible() && !cachingSelf) { return this; } // if node is cached we just need to draw from cache if (cachedCanvas) { context.save(); var m = this.getAbsoluteTransform(top).getMatrix(); context.transform(m[0], m[1], m[2], m[3], m[4], m[5]); this._drawCachedSceneCanvas(context); context.restore(); return this; } if (!drawFunc) { return this; } context.save(); // if buffer canvas is needed if (this._useBufferCanvas() && !skipBuffer) { stage = this.getStage(); bufferCanvas = stage.bufferCanvas; bufferContext = bufferCanvas.getContext(); bufferContext.clear(); bufferContext.save(); bufferContext._applyLineJoin(this); // layer might be undefined if we are using cache before adding to layer var o = this.getAbsoluteTransform(top).getMatrix(); bufferContext.transform(o[0], o[1], o[2], o[3], o[4], o[5]); drawFunc.call(this, bufferContext, this); bufferContext.restore(); var ratio = bufferCanvas.pixelRatio; if (hasShadow) { context._applyShadow(this); } context._applyOpacity(this); context._applyGlobalCompositeOperation(this); context.drawImage( bufferCanvas._canvas, 0, 0, bufferCanvas.width / ratio, bufferCanvas.height / ratio ); } else { context._applyLineJoin(this); if (!cachingSelf) { var o = this.getAbsoluteTransform(top).getMatrix(); context.transform(o[0], o[1], o[2], o[3], o[4], o[5]); context._applyOpacity(this); context._applyGlobalCompositeOperation(this); } if (hasShadow) { context._applyShadow(this); } drawFunc.call(this, context, this); } context.restore(); return this; } drawHit(can?: HitCanvas, top?: Node, skipDragCheck = false) { if (!this.shouldDrawHit(top, skipDragCheck)) { return this; } var layer = this.getLayer(), canvas = can || layer.hitCanvas, context = canvas && canvas.getContext(), drawFunc = this.hitFunc() || this.sceneFunc(), cachedCanvas = this._getCanvasCache(), cachedHitCanvas = cachedCanvas && cachedCanvas.hit; if (!this.colorKey) { Util.warn( 'Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()' ); } if (cachedHitCanvas) { context.save(); var m = this.getAbsoluteTransform(top).getMatrix(); context.transform(m[0], m[1], m[2], m[3], m[4], m[5]); this._drawCachedHitCanvas(context); context.restore(); return this; } if (!drawFunc) { return this; } context.save(); context._applyLineJoin(this); const selfCache = this === top; if (!selfCache) { var o = this.getAbsoluteTransform(top).getMatrix(); context.transform(o[0], o[1], o[2], o[3], o[4], o[5]); } drawFunc.call(this, context, this); context.restore(); return this; } /** * draw hit graph using the cached scene canvas * @method * @name Konva.Shape#drawHitFromCache * @param {Integer} alphaThreshold alpha channel threshold that determines whether or not * a pixel should be drawn onto the hit graph. Must be a value between 0 and 255. * The default is 0 * @returns {Konva.Shape} * @example * shape.cache(); * shape.drawHitFromCache(); */ drawHitFromCache(alphaThreshold = 0) { var cachedCanvas = this._getCanvasCache(), sceneCanvas = this._getCachedSceneCanvas(), hitCanvas = cachedCanvas.hit, hitContext = hitCanvas.getContext(), hitWidth = hitCanvas.getWidth(), hitHeight = hitCanvas.getHeight(), hitImageData, hitData, len, rgbColorKey, i, alpha; hitContext.clear(); hitContext.drawImage(sceneCanvas._canvas, 0, 0, hitWidth, hitHeight); try { hitImageData = hitContext.getImageData(0, 0, hitWidth, hitHeight); hitData = hitImageData.data; len = hitData.length; rgbColorKey = Util._hexToRgb(this.colorKey); // replace non transparent pixels with color key for (i = 0; i < len; i += 4) { alpha = hitData[i + 3]; if (alpha > alphaThreshold) { hitData[i] = rgbColorKey.r; hitData[i + 1] = rgbColorKey.g; hitData[i + 2] = rgbColorKey.b; hitData[i + 3] = 255; } else { hitData[i + 3] = 0; } } hitContext.putImageData(hitImageData, 0, 0); } catch (e) { Util.error( 'Unable to draw hit graph from cached scene canvas. ' + e.message ); } return this; } hasPointerCapture(pointerId: number): boolean { return PointerEvents.hasPointerCapture(pointerId, this); } setPointerCapture(pointerId: number) { PointerEvents.setPointerCapture(pointerId, this); } releaseCapture(pointerId: number) { PointerEvents.releaseCapture(pointerId, this); } draggable: GetSet<boolean, this>; embossBlend: GetSet<boolean, this>; dash: GetSet<number[], this>; dashEnabled: GetSet<boolean, this>; dashOffset: GetSet<number, this>; fill: GetSet<string, this>; fillEnabled: GetSet<boolean, this>; fillLinearGradientColorStops: GetSet<Array<number | string>, this>; fillLinearGradientStartPoint: GetSet<Vector2d, this>; fillLinearGradientStartPointX: GetSet<number, this>; fillLinearGradientStartPointY: GetSet<number, this>; fillLinearGradientEndPoint: GetSet<Vector2d, this>; fillLinearGradientEndPointX: GetSet<number, this>; fillLinearGradientEndPointY: GetSet<number, this>; fillLinearRadialStartPoint: GetSet<Vector2d, this>; fillLinearRadialStartPointX: GetSet<number, this>; fillLinearRadialStartPointY: GetSet<number, this>; fillLinearRadialEndPoint: GetSet<Vector2d, this>; fillLinearRadialEndPointX: GetSet<number, this>; fillLinearRadialEndPointY: GetSet<number, this>; fillPatternImage: GetSet<HTMLImageElement | HTMLCanvasElement, this>; fillRadialGradientStartRadius: GetSet<number, this>; fillRadialGradientEndRadius: GetSet<number, this>; fillRadialGradientColorStops: GetSet<Array<number | string>, this>; fillRadialGradientStartPoint: GetSet<Vector2d, this>; fillRadialGradientStartPointX: GetSet<number, this>; fillRadialGradientStartPointY: GetSet<number, this>; fillRadialGradientEndPoint: GetSet<Vector2d, this>; fillRadialGradientEndPointX: GetSet<number, this>; fillRadialGradientEndPointY: GetSet<number, this>; fillPatternOffset: GetSet<Vector2d, this>; fillPatternOffsetX: GetSet<number, this>; fillPatternOffsetY: GetSet<number, this>; fillPatternRepeat: GetSet<string, this>; fillPatternRotation: GetSet<number, this>; fillPatternScale: GetSet<Vector2d, this>; fillPatternScaleX: GetSet<number, this>; fillPatternScaleY: GetSet<number, this>; fillPatternX: GetSet<number, this>; fillPatternY: GetSet<number, this>; fillPriority: GetSet<string, this>; hitFunc: GetSet<ShapeConfigHandler<this>, this>; lineCap: GetSet<LineCap, this>; lineJoin: GetSet<LineJoin, this>; perfectDrawEnabled: GetSet<boolean, this>; sceneFunc: GetSet<ShapeConfigHandler<this>, this>; shadowColor: GetSet<string, this>; shadowEnabled: GetSet<boolean, this>; shadowForStrokeEnabled: GetSet<boolean, this>; shadowOffset: GetSet<Vector2d, this>; shadowOffsetX: GetSet<number, this>; shadowOffsetY: GetSet<number, this>; shadowOpacity: GetSet<number, this>; shadowBlur: GetSet<number, this>; stroke: GetSet<string, this>; strokeEnabled: GetSet<boolean, this>; fillAfterStrokeEnabled: GetSet<boolean, this>; strokeScaleEnabled: GetSet<boolean, this>; strokeHitEnabled: GetSet<boolean, this>; strokeWidth: GetSet<number, this>; hitStrokeWidth: GetSet<number | 'auto', this>; strokeLinearGradientColorStops: GetSet<Array<number | string>, this>; } Shape.prototype._fillFunc = _fillFunc; Shape.prototype._strokeFunc = _strokeFunc; Shape.prototype._fillFuncHit = _fillFuncHit; Shape.prototype._strokeFuncHit = _strokeFuncHit; Shape.prototype._centroid = false; Shape.prototype.nodeType = 'Shape'; _registerNode(Shape); Shape.prototype.eventListeners = {}; Shape.prototype.on.call( Shape.prototype, 'shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva', _clearHasShadowCache ); Shape.prototype.on.call( Shape.prototype, 'shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva', _clearGetShadowRGBACache ); Shape.prototype.on.call( Shape.prototype, 'fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva', _clearFillPatternCache ); Shape.prototype.on.call( Shape.prototype, 'fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva', _clearLinearGradientCache ); Shape.prototype.on.call( Shape.prototype, 'fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva', _clearRadialGradientCache ); // add getters and setters Factory.addGetterSetter( Shape, 'stroke', undefined, getStringOrGradientValidator() ); /** * get/set stroke color * @name Konva.Shape#stroke * @method * @param {String} color * @returns {String} * @example * // get stroke color * var stroke = shape.stroke(); * * // set stroke color with color string * shape.stroke('green'); * * // set stroke color with hex * shape.stroke('#00ff00'); * * // set stroke color with rgb * shape.stroke('rgb(0,255,0)'); * * // set stroke color with rgba and make it 50% opaque * shape.stroke('rgba(0,255,0,0.5'); */ Factory.addGetterSetter(Shape, 'strokeWidth', 2, getNumberValidator()); /** * get/set stroke width * @name Konva.Shape#strokeWidth * @method * @param {Number} strokeWidth * @returns {Number} * @example * // get stroke width * var strokeWidth = shape.strokeWidth(); * * // set stroke width * shape.strokeWidth(10); */ Factory.addGetterSetter(Shape, 'fillAfterStrokeEnabled', false); /** * get/set fillAfterStrokeEnabled property. By default Konva is drawing filling first, then stroke on top of the fill. * In rare situations you may want a different behavior. When you have a stroke first then fill on top of it. * Especially useful for Text objects. * Default is false. * @name Konva.Shape#fillAfterStrokeEnabled * @method * @param {Boolean} fillAfterStrokeEnabled * @returns {Boolean} * @example * // get stroke width * var fillAfterStrokeEnabled = shape.fillAfterStrokeEnabled(); * * // set stroke width * shape.fillAfterStrokeEnabled(true); */ Factory.addGetterSetter( Shape, 'hitStrokeWidth', 'auto', getNumberOrAutoValidator() ); /** * get/set stroke width for hit detection. Default value is "auto", it means it will be equals to strokeWidth * @name Konva.Shape#hitStrokeWidth * @method * @param {Number} hitStrokeWidth * @returns {Number} * @example * // get stroke width * var hitStrokeWidth = shape.hitStrokeWidth(); * * // set hit stroke width * shape.hitStrokeWidth(20); * // set hit stroke width always equals to scene stroke width * shape.hitStrokeWidth('auto'); */ Factory.addGetterSetter(Shape, 'strokeHitEnabled', true, getBooleanValidator()); /** * **deprecated, use hitStrokeWidth instead!** get/set strokeHitEnabled property. Useful for performance optimization. * You may set `shape.strokeHitEnabled(false)`. In this case stroke will be no draw on hit canvas, so hit area * of shape will be decreased (by lineWidth / 2). Remember that non closed line with `strokeHitEnabled = false` * will be not drawn on hit canvas, that is mean line will no trigger pointer events (like mouseover) * Default value is true. * @name Konva.Shape#strokeHitEnabled * @method * @param {Boolean} strokeHitEnabled * @returns {Boolean} * @example * // get strokeHitEnabled * var strokeHitEnabled = shape.strokeHitEnabled(); * * // set strokeHitEnabled * shape.strokeHitEnabled(); */ Factory.addGetterSetter( Shape, 'perfectDrawEnabled', true, getBooleanValidator() ); /** * get/set perfectDrawEnabled. If a shape has fill, stroke and opacity you may set `perfectDrawEnabled` to false to improve performance. * See http://konvajs.org/docs/performance/Disable_Perfect_Draw.html for more information. * Default value is true * @name Konva.Shape#perfectDrawEnabled * @method * @param {Boolean} perfectDrawEnabled * @returns {Boolean} * @example * // get perfectDrawEnabled * var perfectDrawEnabled = shape.perfectDrawEnabled(); * * // set perfectDrawEnabled * shape.perfectDrawEnabled(); */ Factory.addGetterSetter( Shape, 'shadowForStrokeEnabled', true, getBooleanValidator() ); /** * get/set shadowForStrokeEnabled. Useful for performance optimization. * You may set `shape.shadowForStrokeEnabled(false)`. In this case stroke will no effect shadow. * Remember if you set `shadowForStrokeEnabled = false` for non closed line - that line will have no shadow!. * Default value is true * @name Konva.Shape#shadowForStrokeEnabled * @method * @param {Boolean} shadowForStrokeEnabled * @returns {Boolean} * @example * // get shadowForStrokeEnabled * var shadowForStrokeEnabled = shape.shadowForStrokeEnabled(); * * // set shadowForStrokeEnabled * shape.shadowForStrokeEnabled(); */ Factory.addGetterSetter(Shape, 'lineJoin'); /** * get/set line join. Can be miter, round, or bevel. The * default is miter * @name Konva.Shape#lineJoin * @method * @param {String} lineJoin * @returns {String} * @example * // get line join * var lineJoin = shape.lineJoin(); * * // set line join * shape.lineJoin('round'); */ Factory.addGetterSetter(Shape, 'lineCap'); /** * get/set line cap. Can be butt, round, or square * @name Konva.Shape#lineCap * @method * @param {String} lineCap * @returns {String} * @example * // get line cap * var lineCap = shape.lineCap(); * * // set line cap * shape.lineCap('round'); */ Factory.addGetterSetter(Shape, 'sceneFunc'); /** * get/set scene draw function. That function is used to draw the shape on a canvas. * Also that function will be used to draw hit area of the shape, in case if hitFunc is not defined. * @name Konva.Shape#sceneFunc * @method * @param {Function} drawFunc drawing function * @returns {Function} * @example * // get scene draw function * var sceneFunc = shape.sceneFunc(); * * // set scene draw function * shape.sceneFunc(function(context, shape) { * context.beginPath(); * context.rect(0, 0, shape.width(), shape.height()); * context.closePath(); * // important Konva method that fill and stroke shape from its properties * // like stroke and fill * context.fillStrokeShape(shape); * }); */ Factory.addGetterSetter(Shape, 'hitFunc'); /** * get/set hit draw function. That function is used to draw custom hit area of a shape. * @name Konva.Shape#hitFunc * @method * @param {Function} drawFunc drawing function * @returns {Function} * @example * // get hit draw function * var hitFunc = shape.hitFunc(); * * // set hit draw function * shape.hitFunc(function(context) { * context.beginPath(); * context.rect(0, 0, shape.width(), shape.height()); * context.closePath(); * // important Konva method that fill and stroke shape from its properties * context.fillStrokeShape(shape); * }); */ Factory.addGetterSetter(Shape, 'dash'); /** * get/set dash array for stroke. * @name Konva.Shape#dash * @method * @param {Array} dash * @returns {Array} * @example * // apply dashed stroke that is 10px long and 5 pixels apart * line.dash([10, 5]); * // apply dashed stroke that is made up of alternating dashed * // lines that are 10px long and 20px apart, and dots that have * // a radius of 5px and are 20px apart * line.dash([10, 20, 0.001, 20]); */ Factory.addGetterSetter(Shape, 'dashOffset', 0, getNumberValidator()); /** * get/set dash offset for stroke. * @name Konva.Shape#dash * @method * @param {Number} dash offset * @returns {Number} * @example * // apply dashed stroke that is 10px long and 5 pixels apart with an offset of 5px * line.dash([10, 5]); * line.dashOffset(5); */ Factory.addGetterSetter(Shape, 'shadowColor', undefined, getStringValidator()); /** * get/set shadow color * @name Konva.Shape#shadowColor * @method * @param {String} color * @returns {String} * @example * // get shadow color * var shadow = shape.shadowColor(); * * // set shadow color with color string * shape.shadowColor('green'); * * // set shadow color with hex * shape.shadowColor('#00ff00'); * * // set shadow color with rgb * shape.shadowColor('rgb(0,255,0)'); * * // set shadow color with rgba and make it 50% opaque * shape.shadowColor('rgba(0,255,0,0.5'); */ Factory.addGetterSetter(Shape, 'shadowBlur', 0, getNumberValidator()); /** * get/set shadow blur * @name Konva.Shape#shadowBlur * @method * @param {Number} blur * @returns {Number} * @example * // get shadow blur * var shadowBlur = shape.shadowBlur(); * * // set shadow blur * shape.shadowBlur(10); */ Factory.addGetterSetter(Shape, 'shadowOpacity', 1, getNumberValidator()); /** * get/set shadow opacity. must be a value between 0 and 1 * @name Konva.Shape#shadowOpacity * @method * @param {Number} opacity * @returns {Number} * @example * // get shadow opacity * var shadowOpacity = shape.shadowOpacity(); * * // set shadow opacity * shape.shadowOpacity(0.5); */ Factory.addComponentsGetterSetter(Shape, 'shadowOffset', ['x', 'y']); /** * get/set shadow offset * @name Konva.Shape#shadowOffset * @method * @param {Object} offset * @param {Number} offset.x * @param {Number} offset.y * @returns {Object} * @example * // get shadow offset * var shadowOffset = shape.shadowOffset(); * * // set shadow offset * shape.shadowOffset({ * x: 20, * y: 10 * }); */ Factory.addGetterSetter(Shape, 'shadowOffsetX', 0, getNumberValidator()); /** * get/set shadow offset x * @name Konva.Shape#shadowOffsetX * @method * @param {Number} x * @returns {Number} * @example * // get shadow offset x * var shadowOffsetX = shape.shadowOffsetX(); * * // set shadow offset x * shape.shadowOffsetX(5); */ Factory.addGetterSetter(Shape, 'shadowOffsetY', 0, getNumberValidator()); /** * get/set shadow offset y * @name Konva.Shape#shadowOffsetY * @method * @param {Number} y * @returns {Number} * @example * // get shadow offset y * var shadowOffsetY = shape.shadowOffsetY(); * * // set shadow offset y * shape.shadowOffsetY(5); */ Factory.addGetterSetter(Shape, 'fillPatternImage'); /** * get/set fill pattern image * @name Konva.Shape#fillPatternImage * @method * @param {Image} image object * @returns {Image} * @example * // get fill pattern image * var fillPatternImage = shape.fillPatternImage(); * * // set fill pattern image * var imageObj = new Image(); * imageObj.onload = function() { * shape.fillPatternImage(imageObj); * }; * imageObj.src = 'path/to/image/jpg'; */ Factory.addGetterSetter( Shape, 'fill', undefined, getStringOrGradientValidator() ); /** * get/set fill color * @name Konva.Shape#fill * @method * @param {String} color * @returns {String} * @example * // get fill color * var fill = shape.fill(); * * // set fill color with color string * shape.fill('green'); * * // set fill color with hex * shape.fill('#00ff00'); * * // set fill color with rgb * shape.fill('rgb(0,255,0)'); * * // set fill color with rgba and make it 50% opaque * shape.fill('rgba(0,255,0,0.5'); * * // shape without fill * shape.fill(null); */ Factory.addGetterSetter(Shape, 'fillPatternX', 0, getNumberValidator()); /** * get/set fill pattern x * @name Konva.Shape#fillPatternX * @method * @param {Number} x * @returns {Number} * @example * // get fill pattern x * var fillPatternX = shape.fillPatternX(); * // set fill pattern x * shape.fillPatternX(20); */ Factory.addGetterSetter(Shape, 'fillPatternY', 0, getNumberValidator()); /** * get/set fill pattern y * @name Konva.Shape#fillPatternY * @method * @param {Number} y * @returns {Number} * @example * // get fill pattern y * var fillPatternY = shape.fillPatternY(); * // set fill pattern y * shape.fillPatternY(20); */ Factory.addGetterSetter(Shape, 'fillLinearGradientColorStops'); /** * get/set fill linear gradient color stops * @name Konva.Shape#fillLinearGradientColorStops * @method * @param {Array} colorStops * @returns {Array} colorStops * @example * // get fill linear gradient color stops * var colorStops = shape.fillLinearGradientColorStops(); * * // create a linear gradient that starts with red, changes to blue * // halfway through, and then changes to green * shape.fillLinearGradientColorStops(0, 'red', 0.5, 'blue', 1, 'green'); */ Factory.addGetterSetter(Shape, 'strokeLinearGradientColorStops'); /** * get/set stroke linear gradient color stops * @name Konva.Shape#strokeLinearGradientColorStops * @method * @param {Array} colorStops * @returns {Array} colorStops * @example * // get stroke linear gradient color stops * var colorStops = shape.strokeLinearGradientColorStops(); * * // create a linear gradient that starts with red, changes to blue * // halfway through, and then changes to green * shape.strokeLinearGradientColorStops([0, 'red', 0.5, 'blue', 1, 'green']); */ Factory.addGetterSetter(Shape, 'fillRadialGradientStartRadius', 0); /** * get/set fill radial gradient start radius * @name Konva.Shape#fillRadialGradientStartRadius * @method * @param {Number} radius * @returns {Number} * @example * // get radial gradient start radius * var startRadius = shape.fillRadialGradientStartRadius(); * * // set radial gradient start radius * shape.fillRadialGradientStartRadius(0); */ Factory.addGetterSetter(Shape, 'fillRadialGradientEndRadius', 0); /** * get/set fill radial gradient end radius * @name Konva.Shape#fillRadialGradientEndRadius * @method * @param {Number} radius * @returns {Number} * @example * // get radial gradient end radius * var endRadius = shape.fillRadialGradientEndRadius(); * * // set radial gradient end radius * shape.fillRadialGradientEndRadius(100); */ Factory.addGetterSetter(Shape, 'fillRadialGradientColorStops'); /** * get/set fill radial gradient color stops * @name Konva.Shape#fillRadialGradientColorStops * @method * @param {Number} colorStops * @returns {Array} * @example * // get fill radial gradient color stops * var colorStops = shape.fillRadialGradientColorStops(); * * // create a radial gradient that starts with red, changes to blue * // halfway through, and then changes to green * shape.fillRadialGradientColorStops(0, 'red', 0.5, 'blue', 1, 'green'); */ Factory.addGetterSetter(Shape, 'fillPatternRepeat', 'repeat'); /** * get/set fill pattern repeat. Can be 'repeat', 'repeat-x', 'repeat-y', or 'no-repeat'. The default is 'repeat' * @name Konva.Shape#fillPatternRepeat * @method * @param {String} repeat * @returns {String} * @example * // get fill pattern repeat * var repeat = shape.fillPatternRepeat(); * * // repeat pattern in x direction only * shape.fillPatternRepeat('repeat-x'); * * // do not repeat the pattern * shape.fillPatternRepeat('no-repeat'); */ Factory.addGetterSetter(Shape, 'fillEnabled', true); /** * get/set fill enabled flag * @name Konva.Shape#fillEnabled * @method * @param {Boolean} enabled * @returns {Boolean} * @example * // get fill enabled flag * var fillEnabled = shape.fillEnabled(); * * // disable fill * shape.fillEnabled(false); * * // enable fill * shape.fillEnabled(true); */ Factory.addGetterSetter(Shape, 'strokeEnabled', true); /** * get/set stroke enabled flag * @name Konva.Shape#strokeEnabled * @method * @param {Boolean} enabled * @returns {Boolean} * @example * // get stroke enabled flag * var strokeEnabled = shape.strokeEnabled(); * * // disable stroke * shape.strokeEnabled(false); * * // enable stroke * shape.strokeEnabled(true); */ Factory.addGetterSetter(Shape, 'shadowEnabled', true); /** * get/set shadow enabled flag * @name Konva.Shape#shadowEnabled * @method * @param {Boolean} enabled * @returns {Boolean} * @example * // get shadow enabled flag * var shadowEnabled = shape.shadowEnabled(); * * // disable shadow * shape.shadowEnabled(false); * * // enable shadow * shape.shadowEnabled(true); */ Factory.addGetterSetter(Shape, 'dashEnabled', true); /** * get/set dash enabled flag * @name Konva.Shape#dashEnabled * @method * @param {Boolean} enabled * @returns {Boolean} * @example * // get dash enabled flag * var dashEnabled = shape.dashEnabled(); * * // disable dash * shape.dashEnabled(false); * * // enable dash * shape.dashEnabled(true); */ Factory.addGetterSetter(Shape, 'strokeScaleEnabled', true); /** * get/set strokeScale enabled flag * @name Konva.Shape#strokeScaleEnabled * @method * @param {Boolean} enabled * @returns {Boolean} * @example * // get stroke scale enabled flag * var strokeScaleEnabled = shape.strokeScaleEnabled(); * * // disable stroke scale * shape.strokeScaleEnabled(false); * * // enable stroke scale * shape.strokeScaleEnabled(true); */ Factory.addGetterSetter(Shape, 'fillPriority', 'color'); /** * get/set fill priority. can be color, pattern, linear-gradient, or radial-gradient. The default is color. * This is handy if you want to toggle between different fill types. * @name Konva.Shape#fillPriority * @method * @param {String} priority * @returns {String} * @example * // get fill priority * var fillPriority = shape.fillPriority(); * * // set fill priority * shape.fillPriority('linear-gradient'); */ Factory.addComponentsGetterSetter(Shape, 'fillPatternOffset', ['x', 'y']); /** * get/set fill pattern offset * @name Konva.Shape#fillPatternOffset * @method * @param {Object} offset * @param {Number} offset.x * @param {Number} offset.y * @returns {Object} * @example * // get fill pattern offset * var patternOffset = shape.fillPatternOffset(); * * // set fill pattern offset * shape.fillPatternOffset({ * x: 20, * y: 10 * }); */ Factory.addGetterSetter(Shape, 'fillPatternOffsetX', 0, getNumberValidator()); /** * get/set fill pattern offset x * @name Konva.Shape#fillPatternOffsetX * @method * @param {Number} x * @returns {Number} * @example * // get fill pattern offset x * var patternOffsetX = shape.fillPatternOffsetX(); * * // set fill pattern offset x * shape.fillPatternOffsetX(20); */ Factory.addGetterSetter(Shape, 'fillPatternOffsetY', 0, getNumberValidator()); /** * get/set fill pattern offset y * @name Konva.Shape#fillPatternOffsetY * @method * @param {Number} y * @returns {Number} * @example * // get fill pattern offset y * var patternOffsetY = shape.fillPatternOffsetY(); * * // set fill pattern offset y * shape.fillPatternOffsetY(10); */ Factory.addComponentsGetterSetter(Shape, 'fillPatternScale', ['x', 'y']); /** * get/set fill pattern scale * @name Konva.Shape#fillPatternScale * @method * @param {Object} scale * @param {Number} scale.x * @param {Number} scale.y * @returns {Object} * @example * // get fill pattern scale * var patternScale = shape.fillPatternScale(); * * // set fill pattern scale * shape.fillPatternScale({ * x: 2, * y: 2 * }); */ Factory.addGetterSetter(Shape, 'fillPatternScaleX', 1, getNumberValidator()); /** * get/set fill pattern scale x * @name Konva.Shape#fillPatternScaleX * @method * @param {Number} x * @returns {Number} * @example * // get fill pattern scale x * var patternScaleX = shape.fillPatternScaleX(); * * // set fill pattern scale x * shape.fillPatternScaleX(2); */ Factory.addGetterSetter(Shape, 'fillPatternScaleY', 1, getNumberValidator()); /** * get/set fill pattern scale y * @name Konva.Shape#fillPatternScaleY * @method * @param {Number} y * @returns {Number} * @example * // get fill pattern scale y * var patternScaleY = shape.fillPatternScaleY(); * * // set fill pattern scale y * shape.fillPatternScaleY(2); */ Factory.addComponentsGetterSetter(Shape, 'fillLinearGradientStartPoint', [ 'x', 'y', ]); /** * get/set fill linear gradient start point * @name Konva.Shape#fillLinearGradientStartPoint * @method * @param {Object} startPoint * @param {Number} startPoint.x * @param {Number} startPoint.y * @returns {Object} * @example * // get fill linear gradient start point * var startPoint = shape.fillLinearGradientStartPoint(); * * // set fill linear gradient start point * shape.fillLinearGradientStartPoint({ * x: 20, * y: 10 * }); */ Factory.addComponentsGetterSetter(Shape, 'strokeLinearGradientStartPoint', [ 'x', 'y', ]); /** * get/set stroke linear gradient start point * @name Konva.Shape#strokeLinearGradientStartPoint * @method * @param {Object} startPoint * @param {Number} startPoint.x * @param {Number} startPoint.y * @returns {Object} * @example * // get stroke linear gradient start point * var startPoint = shape.strokeLinearGradientStartPoint(); * * // set stroke linear gradient start point * shape.strokeLinearGradientStartPoint({ * x: 20, * y: 10 * }); */ Factory.addGetterSetter(Shape, 'fillLinearGradientStartPointX', 0); /** * get/set fill linear gradient start point x * @name Konva.Shape#fillLinearGradientStartPointX * @method * @param {Number} x * @returns {Number} * @example * // get fill linear gradient start point x * var startPointX = shape.fillLinearGradientStartPointX(); * * // set fill linear gradient start point x * shape.fillLinearGradientStartPointX(20); */ Factory.addGetterSetter(Shape, 'strokeLinearGradientStartPointX', 0); /** * get/set stroke linear gradient start point x * @name Konva.Shape#linearLinearGradientStartPointX * @method * @param {Number} x * @returns {Number} * @example * // get stroke linear gradient start point x * var startPointX = shape.strokeLinearGradientStartPointX(); * * // set stroke linear gradient start point x * shape.strokeLinearGradientStartPointX(20); */ Factory.addGetterSetter(Shape, 'fillLinearGradientStartPointY', 0); /** * get/set fill linear gradient start point y * @name Konva.Shape#fillLinearGradientStartPointY * @method * @param {Number} y * @returns {Number} * @example * // get fill linear gradient start point y * var startPointY = shape.fillLinearGradientStartPointY(); * * // set fill linear gradient start point y * shape.fillLinearGradientStartPointY(20); */ Factory.addGetterSetter(Shape, 'strokeLinearGradientStartPointY', 0); /** * get/set stroke linear gradient start point y * @name Konva.Shape#strokeLinearGradientStartPointY * @method * @param {Number} y * @returns {Number} * @example * // get stroke linear gradient start point y * var startPointY = shape.strokeLinearGradientStartPointY(); * * // set stroke linear gradient start point y * shape.strokeLinearGradientStartPointY(20); */ Factory.addComponentsGetterSetter(Shape, 'fillLinearGradientEndPoint', [ 'x', 'y', ]); /** * get/set fill linear gradient end point * @name Konva.Shape#fillLinearGradientEndPoint * @method * @param {Object} endPoint * @param {Number} endPoint.x * @param {Number} endPoint.y * @returns {Object} * @example * // get fill linear gradient end point * var endPoint = shape.fillLinearGradientEndPoint(); * * // set fill linear gradient end point * shape.fillLinearGradientEndPoint({ * x: 20, * y: 10 * }); */ Factory.addComponentsGetterSetter(Shape, 'strokeLinearGradientEndPoint', [ 'x', 'y', ]); /** * get/set stroke linear gradient end point * @name Konva.Shape#strokeLinearGradientEndPoint * @method * @param {Object} endPoint * @param {Number} endPoint.x * @param {Number} endPoint.y * @returns {Object} * @example * // get stroke linear gradient end point * var endPoint = shape.strokeLinearGradientEndPoint(); * * // set stroke linear gradient end point * shape.strokeLinearGradientEndPoint({ * x: 20, * y: 10 * }); */ Factory.addGetterSetter(Shape, 'fillLinearGradientEndPointX', 0); /** * get/set fill linear gradient end point x * @name Konva.Shape#fillLinearGradientEndPointX * @method * @param {Number} x * @returns {Number} * @example * // get fill linear gradient end point x * var endPointX = shape.fillLinearGradientEndPointX(); * * // set fill linear gradient end point x * shape.fillLinearGradientEndPointX(20); */ Factory.addGetterSetter(Shape, 'strokeLinearGradientEndPointX', 0); /** * get/set fill linear gradient end point x * @name Konva.Shape#strokeLinearGradientEndPointX * @method * @param {Number} x * @returns {Number} * @example * // get stroke linear gradient end point x * var endPointX = shape.strokeLinearGradientEndPointX(); * * // set stroke linear gradient end point x * shape.strokeLinearGradientEndPointX(20); */ Factory.addGetterSetter(Shape, 'fillLinearGradientEndPointY', 0); /** * get/set fill linear gradient end point y * @name Konva.Shape#fillLinearGradientEndPointY * @method * @param {Number} y * @returns {Number} * @example * // get fill linear gradient end point y * var endPointY = shape.fillLinearGradientEndPointY(); * * // set fill linear gradient end point y * shape.fillLinearGradientEndPointY(20); */ Factory.addGetterSetter(Shape, 'strokeLinearGradientEndPointY', 0); /** * get/set stroke linear gradient end point y * @name Konva.Shape#strokeLinearGradientEndPointY * @method * @param {Number} y * @returns {Number} * @example * // get stroke linear gradient end point y * var endPointY = shape.strokeLinearGradientEndPointY(); * * // set stroke linear gradient end point y * shape.strokeLinearGradientEndPointY(20); */ Factory.addComponentsGetterSetter(Shape, 'fillRadialGradientStartPoint', [ 'x', 'y', ]); /** * get/set fill radial gradient start point * @name Konva.Shape#fillRadialGradientStartPoint * @method * @param {Object} startPoint * @param {Number} startPoint.x * @param {Number} startPoint.y * @returns {Object} * @example * // get fill radial gradient start point * var startPoint = shape.fillRadialGradientStartPoint(); * * // set fill radial gradient start point * shape.fillRadialGradientStartPoint({ * x: 20, * y: 10 * }); */ Factory.addGetterSetter(Shape, 'fillRadialGradientStartPointX', 0); /** * get/set fill radial gradient start point x * @name Konva.Shape#fillRadialGradientStartPointX * @method * @param {Number} x * @returns {Number} * @example * // get fill radial gradient start point x * var startPointX = shape.fillRadialGradientStartPointX(); * * // set fill radial gradient start point x * shape.fillRadialGradientStartPointX(20); */ Factory.addGetterSetter(Shape, 'fillRadialGradientStartPointY', 0); /** * get/set fill radial gradient start point y * @name Konva.Shape#fillRadialGradientStartPointY * @method * @param {Number} y * @returns {Number} * @example * // get fill radial gradient start point y * var startPointY = shape.fillRadialGradientStartPointY(); * * // set fill radial gradient start point y * shape.fillRadialGradientStartPointY(20); */ Factory.addComponentsGetterSetter(Shape, 'fillRadialGradientEndPoint', [ 'x', 'y', ]); /** * get/set fill radial gradient end point * @name Konva.Shape#fillRadialGradientEndPoint * @method * @param {Object} endPoint * @param {Number} endPoint.x * @param {Number} endPoint.y * @returns {Object} * @example * // get fill radial gradient end point * var endPoint = shape.fillRadialGradientEndPoint(); * * // set fill radial gradient end point * shape.fillRadialGradientEndPoint({ * x: 20, * y: 10 * }); */ Factory.addGetterSetter(Shape, 'fillRadialGradientEndPointX', 0); /** * get/set fill radial gradient end point x * @name Konva.Shape#fillRadialGradientEndPointX * @method * @param {Number} x * @returns {Number} * @example * // get fill radial gradient end point x * var endPointX = shape.fillRadialGradientEndPointX(); * * // set fill radial gradient end point x * shape.fillRadialGradientEndPointX(20); */ Factory.addGetterSetter(Shape, 'fillRadialGradientEndPointY', 0); /** * get/set fill radial gradient end point y * @name Konva.Shape#fillRadialGradientEndPointY * @method * @param {Number} y * @returns {Number} * @example * // get fill radial gradient end point y * var endPointY = shape.fillRadialGradientEndPointY(); * * // set fill radial gradient end point y * shape.fillRadialGradientEndPointY(20); */ Factory.addGetterSetter(Shape, 'fillPatternRotation', 0); /** * get/set fill pattern rotation in degrees * @name Konva.Shape#fillPatternRotation * @method * @param {Number} rotation * @returns {Konva.Shape} * @example * // get fill pattern rotation * var patternRotation = shape.fillPatternRotation(); * * // set fill pattern rotation * shape.fillPatternRotation(20); */ Factory.backCompat(Shape, { dashArray: 'dash', getDashArray: 'getDash', setDashArray: 'getDash', drawFunc: 'sceneFunc', getDrawFunc: 'getSceneFunc', setDrawFunc: 'setSceneFunc', drawHitFunc: 'hitFunc', getDrawHitFunc: 'getHitFunc', setDrawHitFunc: 'setHitFunc', });
the_stack
import { createSelector } from '@ngrx/store'; import { ServiceOffering, serviceOfferingParamKey, Tag } from '../../../shared/models'; import { CustomComputeOfferingHardwareRestrictions, CustomComputeOfferingHardwareValues, CustomComputeOfferingParameters, HardwareLimits, } from '../../../shared/models/config'; import { ComputeOfferingViewModel } from '../../view-models'; import { configSelectors, UserTagsSelectors } from '../../../root-store'; import * as computeOffering from '../../../reducers/service-offerings/redux/service-offerings.reducers'; import * as fromVms from '../../../reducers/vm/redux/vm.reducers'; import * as fromAccounts from '../../../reducers/accounts/redux/accounts.reducers'; interface Resources { cpuNumber: number | string; memory: number | string; } const getFixedAndCustomOfferingsArrays = (offerings: ServiceOffering[]) => { const offeringsArrays = { customOfferings: [], fixedOfferings: [], }; return offerings.reduce((result, offering) => { if (offering.iscustomized) { result.customOfferings.push(offering); } else { result.fixedOfferings.push(offering); } return result; }, offeringsArrays); }; const getCustomOfferingHardwareParameters = ( offering: ServiceOffering, offeringsParameters: CustomComputeOfferingParameters[], ): CustomComputeOfferingParameters | undefined => { return ( offeringsParameters && offeringsParameters.find(parameters => parameters.offeringId === offering.id) ); }; const getCustomHardwareValues = ( params: CustomComputeOfferingParameters | undefined, ): CustomComputeOfferingHardwareValues | null => { if (!params) { return null; } return { cpunumber: params.cpunumber.value, cpuspeed: params.cpuspeed.value, memory: params.memory.value, }; }; const getCustomHardwareRestrictions = ( params: CustomComputeOfferingParameters | undefined, ): CustomComputeOfferingHardwareRestrictions | null => { if (!params) { return null; } return { cpunumber: { min: params.cpunumber.min, max: params.cpunumber.max, }, cpuspeed: { min: params.cpuspeed.min, max: params.cpuspeed.max, }, memory: { min: params.memory.min, max: params.memory.max, }, }; }; const getHardwareValuesFromTags = ( serviceOffering: ServiceOffering, tags: Tag[], ): CustomComputeOfferingHardwareValues | null => { const getValue = param => { const key = `${serviceOfferingParamKey}.${serviceOffering.id}.${param}`; const tag = tags.find(t => t.key === key); return tag && tag.value; }; const cpunumber = parseInt(getValue('cpunumber'), 10); const cpuspeed = parseInt(getValue('cpuspeed'), 10); const memory = parseInt(getValue('memory'), 10); if (cpunumber && cpuspeed && memory) { return { cpunumber, cpuspeed, memory }; } return null; }; const checkAvailabilityForFixedByResources = ( cpuNumber: number, memory: number, availableResources: Resources, ): boolean => { const isEnoughCpuNumber = availableResources.cpuNumber === 'Unlimited' || cpuNumber <= availableResources.cpuNumber; const isEnoughMemory = availableResources.memory === 'Unlimited' || memory <= availableResources.memory; return isEnoughCpuNumber && isEnoughMemory; }; const checkAvailabilityForCustomByResources = ( cpuNumberRestrictions: HardwareLimits, memoryRestrictions: HardwareLimits, availableResources: Resources, ): boolean => { const isEnoughCpuNumber = availableResources.cpuNumber === 'Unlimited' || cpuNumberRestrictions.min <= availableResources.cpuNumber; const isEnoughMemory = availableResources.memory === 'Unlimited' || memoryRestrictions.min <= availableResources.memory; return isEnoughCpuNumber && isEnoughMemory; }; const getValueThatSatisfiesRestrictions = (defaultValue: number, restrictions: HardwareLimits) => { if (restrictions.min > defaultValue) { return restrictions.min; } if (defaultValue > restrictions.max) { return restrictions.max; } return defaultValue; }; const getValueThatSatisfiesResources = ( defaultValue: number, resourceLimit: string | number, ): number => { const limit = Number(resourceLimit); if (!isNaN(limit) && limit < defaultValue) { return limit; } return defaultValue; }; const getRestrictionsThatSatisfiesResources = ( restrictions: CustomComputeOfferingHardwareRestrictions, resources: Resources, ): CustomComputeOfferingHardwareRestrictions => { const cpuResource = Number(resources.cpuNumber); const memoryResource = Number(resources.memory); let maxCpuNumber = restrictions.cpunumber.max; if (!isNaN(cpuResource)) { maxCpuNumber = restrictions.cpunumber.max > cpuResource ? cpuResource : restrictions.cpunumber.max; } let maxMemory = restrictions.memory.max; if (!isNaN(memoryResource)) { maxMemory = restrictions.memory.max > memoryResource ? memoryResource : restrictions.memory.max; } return { ...restrictions, cpunumber: { min: restrictions.cpunumber.min, max: maxCpuNumber, }, memory: { min: restrictions.memory.min, max: maxMemory, }, }; }; const getComputeOfferingViewModel = ( offerings, customComputeOfferingParameters, defaultRestrictions, defaultHardwareValues, tags, availableResources, ): ComputeOfferingViewModel[] => { const { customOfferings, fixedOfferings } = getFixedAndCustomOfferingsArrays(offerings); const customOfferingsWithMetadata: ComputeOfferingViewModel[] = customOfferings.map( (offering: ServiceOffering) => { const customParameters = getCustomOfferingHardwareParameters( offering, customComputeOfferingParameters, ); const customHardwareValues = getCustomHardwareValues(customParameters); const customHardwareRestrictions = getCustomHardwareRestrictions(customParameters); const hardwareValuesFromTags = getHardwareValuesFromTags(offering, tags); const prioritizedHardwareValues = hardwareValuesFromTags || customHardwareValues || defaultHardwareValues; const prioritizedRestrictions = customHardwareRestrictions || defaultRestrictions; const isAvailableByResources = checkAvailabilityForCustomByResources( prioritizedRestrictions.cpunumber, prioritizedRestrictions.memory, availableResources, ); let cpunumber = getValueThatSatisfiesRestrictions( prioritizedHardwareValues.cpunumber, prioritizedRestrictions.cpunumber, ); const cpuspeed = getValueThatSatisfiesRestrictions( prioritizedHardwareValues.cpuspeed, prioritizedRestrictions.cpuspeed, ); let memory = getValueThatSatisfiesRestrictions( prioritizedHardwareValues.memory, prioritizedRestrictions.memory, ); if (isAvailableByResources) { cpunumber = getValueThatSatisfiesResources(cpunumber, availableResources.cpuNumber); memory = getValueThatSatisfiesResources(memory, availableResources.memory); } const customOfferingRestrictions = getRestrictionsThatSatisfiesResources( prioritizedRestrictions, availableResources, ); const offeringViewModel: ComputeOfferingViewModel = { ...offering, cpunumber, cpuspeed, memory, customOfferingRestrictions, isAvailableByResources, }; return offeringViewModel; }, ); const fixedOfferingWithMeta = fixedOfferings.map(offering => { const offeringViewModel: ComputeOfferingViewModel = { ...offering, isAvailableByResources: checkAvailabilityForFixedByResources( offering.cpunumber, offering.memory, availableResources, ), }; return offeringViewModel; }); return [...fixedOfferingWithMeta, ...customOfferingsWithMetadata]; }; const getAvailableResources = ( resource: number | string, usedResource: number, ): number | string => { return resource && resource === 'Unlimited' ? resource : Number(resource) + usedResource || 0; }; export const getComputeOfferingForVmEditing = createSelector( fromAccounts.selectUserAccount, computeOffering.selectAll, configSelectors.get('customComputeOfferingParameters'), configSelectors.get('defaultCustomComputeOfferingRestrictions'), configSelectors.get('customComputeOfferingHardwareValues'), UserTagsSelectors.getServiceOfferingParamTags, fromVms.getSelectedVM, ( account, offerings, customComputeOfferingParameters, defaultRestrictions, defaultHardwareValues, tags, vm, ): ComputeOfferingViewModel[] => { if (!vm || !account) { return []; } const memoryUsed = vm.memory; const cpuNumberUsed = vm.cpunumber; const cpuNumber = getAvailableResources(account.cpuavailable, cpuNumberUsed); const memory = getAvailableResources(account.memoryavailable, memoryUsed); const availableResources: Resources = { cpuNumber, memory }; return getComputeOfferingViewModel( offerings, customComputeOfferingParameters, defaultRestrictions, defaultHardwareValues, tags, availableResources, ); }, ); export const getComputeOfferingForVmCreation = createSelector( fromAccounts.selectUserAccount, computeOffering.selectAll, configSelectors.get('customComputeOfferingParameters'), configSelectors.get('defaultCustomComputeOfferingRestrictions'), configSelectors.get('customComputeOfferingHardwareValues'), UserTagsSelectors.getServiceOfferingParamTags, ( account, offerings, customComputeOfferingParameters, defaultRestrictions, defaultHardwareValues, tags, ): ComputeOfferingViewModel[] => { /** * '0' used to prevent an error when account is not loaded yet * it happened when you go to vm creation dialog by url */ const availableResources: Resources = { cpuNumber: (account && account.cpuavailable) || '0', memory: (account && account.memoryavailable) || '0', }; return getComputeOfferingViewModel( offerings, customComputeOfferingParameters, defaultRestrictions, defaultHardwareValues, tags, availableResources, ); }, );
the_stack
import { ERC1155MintableContract, Erc1155Wrapper } from '@0x/contracts-erc1155'; import { artifacts as erc20Artifacts, DummyERC20TokenContract, DummyERC20TokenTransferEventArgs, DummyMultipleReturnERC20TokenContract, DummyNoReturnERC20TokenContract, } from '@0x/contracts-erc20'; import { artifacts as erc721Artifacts, DummyERC721ReceiverContract, DummyERC721TokenContract, } from '@0x/contracts-erc721'; import { chaiSetup, constants, expectTransactionFailedAsync, expectTransactionFailedWithoutReasonAsync, LogDecoder, provider, txDefaults, web3Wrapper, } from '@0x/contracts-test-utils'; import { BlockchainLifecycle } from '@0x/dev-utils'; import { AssetProxyId, RevertReason } from '@0x/types'; import { BigNumber } from '@0x/utils'; import * as chai from 'chai'; import { LogWithDecodedArgs } from 'ethereum-types'; import * as _ from 'lodash'; import { encodeERC1155AssetData, encodeERC20AssetData, encodeERC721AssetData, encodeMultiAssetData, } from '../src/asset_data'; import { ERC1155ProxyWrapper } from '../src/erc1155_proxy_wrapper'; import { ERC20Wrapper } from '../src/erc20_wrapper'; import { ERC721Wrapper } from '../src/erc721_wrapper'; import { ERC1155ProxyContract, ERC20ProxyContract, ERC721ProxyContract } from '../src/wrappers'; import { artifacts } from './artifacts'; import { IAssetProxyContract, MultiAssetProxyContract } from './wrappers'; chaiSetup.configure(); const expect = chai.expect; const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper); const assetProxyInterface = new IAssetProxyContract(constants.NULL_ADDRESS, provider); // tslint:disable:no-unnecessary-type-assertion describe('Asset Transfer Proxies', () => { let owner: string; let notAuthorized: string; let authorized: string; let fromAddress: string; let toAddress: string; let erc20TokenA: DummyERC20TokenContract; let erc20TokenB: DummyERC20TokenContract; let erc721TokenA: DummyERC721TokenContract; let erc721TokenB: DummyERC721TokenContract; let erc721Receiver: DummyERC721ReceiverContract; let erc20Proxy: ERC20ProxyContract; let erc721Proxy: ERC721ProxyContract; let noReturnErc20Token: DummyNoReturnERC20TokenContract; let multipleReturnErc20Token: DummyMultipleReturnERC20TokenContract; let multiAssetProxy: MultiAssetProxyContract; let erc20Wrapper: ERC20Wrapper; let erc721Wrapper: ERC721Wrapper; let erc721AFromTokenId: BigNumber; let erc721BFromTokenId: BigNumber; let erc1155Proxy: ERC1155ProxyContract; let erc1155ProxyWrapper: ERC1155ProxyWrapper; let erc1155Contract: ERC1155MintableContract; let erc1155Contract2: ERC1155MintableContract; let erc1155Wrapper: Erc1155Wrapper; let erc1155Wrapper2: Erc1155Wrapper; let erc1155FungibleTokens: BigNumber[]; let erc1155NonFungibleTokensOwnedBySpender: BigNumber[]; before(async () => { await blockchainLifecycle.startAsync(); }); after(async () => { await blockchainLifecycle.revertAsync(); }); before(async () => { const accounts = await web3Wrapper.getAvailableAddressesAsync(); const usedAddresses = ([owner, notAuthorized, authorized, fromAddress, toAddress] = _.slice(accounts, 0, 5)); erc20Wrapper = new ERC20Wrapper(provider, usedAddresses, owner); erc721Wrapper = new ERC721Wrapper(provider, usedAddresses, owner); // Deploy AssetProxies erc20Proxy = await erc20Wrapper.deployProxyAsync(); erc721Proxy = await erc721Wrapper.deployProxyAsync(); multiAssetProxy = await MultiAssetProxyContract.deployFrom0xArtifactAsync( artifacts.MultiAssetProxy, provider, txDefaults, artifacts, ); // Configure ERC20Proxy await erc20Proxy.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner }); await erc20Proxy.addAuthorizedAddress(multiAssetProxy.address).awaitTransactionSuccessAsync({ from: owner }); // Configure ERC721Proxy await erc721Proxy.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner }); await erc721Proxy.addAuthorizedAddress(multiAssetProxy.address).awaitTransactionSuccessAsync({ from: owner }); // Configure ERC115Proxy erc1155ProxyWrapper = new ERC1155ProxyWrapper(provider, usedAddresses, owner); erc1155Proxy = await erc1155ProxyWrapper.deployProxyAsync(); await erc1155Proxy.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner }); await erc1155Proxy.addAuthorizedAddress(multiAssetProxy.address).awaitTransactionSuccessAsync({ from: owner }); // Configure MultiAssetProxy await multiAssetProxy.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner }); await multiAssetProxy.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: owner }); await multiAssetProxy.registerAssetProxy(erc721Proxy.address).awaitTransactionSuccessAsync({ from: owner }); await multiAssetProxy.registerAssetProxy(erc1155Proxy.address).awaitTransactionSuccessAsync({ from: owner }); // Deploy and configure ERC20 tokens const numDummyErc20ToDeploy = 2; [erc20TokenA, erc20TokenB] = await erc20Wrapper.deployDummyTokensAsync( numDummyErc20ToDeploy, constants.DUMMY_TOKEN_DECIMALS, ); noReturnErc20Token = await DummyNoReturnERC20TokenContract.deployFrom0xArtifactAsync( erc20Artifacts.DummyNoReturnERC20Token, provider, txDefaults, artifacts, constants.DUMMY_TOKEN_NAME, constants.DUMMY_TOKEN_SYMBOL, constants.DUMMY_TOKEN_DECIMALS, constants.DUMMY_TOKEN_TOTAL_SUPPLY, ); multipleReturnErc20Token = await DummyMultipleReturnERC20TokenContract.deployFrom0xArtifactAsync( erc20Artifacts.DummyMultipleReturnERC20Token, provider, txDefaults, artifacts, constants.DUMMY_TOKEN_NAME, constants.DUMMY_TOKEN_SYMBOL, constants.DUMMY_TOKEN_DECIMALS, constants.DUMMY_TOKEN_TOTAL_SUPPLY, ); await erc20Wrapper.setBalancesAndAllowancesAsync(); await noReturnErc20Token.setBalance(fromAddress, constants.INITIAL_ERC20_BALANCE).awaitTransactionSuccessAsync({ from: owner, }); await noReturnErc20Token .approve(erc20Proxy.address, constants.INITIAL_ERC20_ALLOWANCE) .awaitTransactionSuccessAsync({ from: fromAddress }); await multipleReturnErc20Token .setBalance(fromAddress, constants.INITIAL_ERC20_BALANCE) .awaitTransactionSuccessAsync({ from: owner, }); await multipleReturnErc20Token .approve(erc20Proxy.address, constants.INITIAL_ERC20_ALLOWANCE) .awaitTransactionSuccessAsync({ from: fromAddress }); // Deploy and configure ERC721 tokens and receiver [erc721TokenA, erc721TokenB] = await erc721Wrapper.deployDummyTokensAsync(); erc721Receiver = await DummyERC721ReceiverContract.deployFrom0xArtifactAsync( erc721Artifacts.DummyERC721Receiver, provider, txDefaults, artifacts, ); await erc721Wrapper.setBalancesAndAllowancesAsync(); const erc721Balances = await erc721Wrapper.getBalancesAsync(); erc721AFromTokenId = erc721Balances[fromAddress][erc721TokenA.address][0]; erc721BFromTokenId = erc721Balances[fromAddress][erc721TokenB.address][0]; // Deploy & configure ERC1155 tokens and receiver [erc1155Wrapper, erc1155Wrapper2] = await erc1155ProxyWrapper.deployDummyContractsAsync(); erc1155Contract = erc1155Wrapper.getContract(); erc1155Contract2 = erc1155Wrapper2.getContract(); await erc1155ProxyWrapper.setBalancesAndAllowancesAsync(); erc1155FungibleTokens = erc1155ProxyWrapper.getFungibleTokenIds(); const nonFungibleTokens = erc1155ProxyWrapper.getNonFungibleTokenIds(); const tokenBalances = await erc1155ProxyWrapper.getBalancesAsync(); erc1155NonFungibleTokensOwnedBySpender = []; _.each(nonFungibleTokens, (nonFungibleToken: BigNumber) => { const nonFungibleTokenAsString = nonFungibleToken.toString(); const nonFungibleTokenHeldBySpender = tokenBalances.nonFungible[fromAddress][erc1155Contract.address][nonFungibleTokenAsString][0]; erc1155NonFungibleTokensOwnedBySpender.push(nonFungibleTokenHeldBySpender); }); }); beforeEach(async () => { await blockchainLifecycle.startAsync(); }); afterEach(async () => { await blockchainLifecycle.revertAsync(); }); describe('ERC20Proxy', () => { it('should revert if undefined function is called', async () => { const undefinedSelector = '0x01020304'; await expectTransactionFailedWithoutReasonAsync( web3Wrapper.sendTransactionAsync({ from: owner, to: erc20Proxy.address, value: constants.ZERO_AMOUNT, data: undefinedSelector, }), ); }); it('should have an id of 0xf47261b0', async () => { const proxyId = await erc20Proxy.getProxyId().callAsync(); const expectedProxyId = '0xf47261b0'; expect(proxyId).to.equal(expectedProxyId); }); describe('transferFrom', () => { it('should successfully transfer tokens', async () => { // Construct ERC20 asset data const encodedAssetData = encodeERC20AssetData(erc20TokenA.address); // Perform a transfer from fromAddress to toAddress const erc20Balances = await erc20Wrapper.getBalancesAsync(); const amount = new BigNumber(10); const data = assetProxyInterface .transferFrom(encodedAssetData, fromAddress, toAddress, amount) .getABIEncodedTransactionData(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: erc20Proxy.address, data, from: authorized, }), constants.AWAIT_TRANSACTION_MINED_MS, ); // Verify transfer was successful const newBalances = await erc20Wrapper.getBalancesAsync(); expect(newBalances[fromAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[fromAddress][erc20TokenA.address].minus(amount), ); expect(newBalances[toAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[toAddress][erc20TokenA.address].plus(amount), ); }); it('should successfully transfer tokens that do not return a value', async () => { // Construct ERC20 asset data const encodedAssetData = encodeERC20AssetData(noReturnErc20Token.address); // Perform a transfer from fromAddress to toAddress const initialFromBalance = await noReturnErc20Token.balanceOf(fromAddress).callAsync(); const initialToBalance = await noReturnErc20Token.balanceOf(toAddress).callAsync(); const amount = new BigNumber(10); const data = assetProxyInterface .transferFrom(encodedAssetData, fromAddress, toAddress, amount) .getABIEncodedTransactionData(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: erc20Proxy.address, data, from: authorized, }), constants.AWAIT_TRANSACTION_MINED_MS, ); // Verify transfer was successful const newFromBalance = await noReturnErc20Token.balanceOf(fromAddress).callAsync(); const newToBalance = await noReturnErc20Token.balanceOf(toAddress).callAsync(); expect(newFromBalance).to.be.bignumber.equal(initialFromBalance.minus(amount)); expect(newToBalance).to.be.bignumber.equal(initialToBalance.plus(amount)); }); it('should successfully transfer tokens and ignore extra assetData', async () => { // Construct ERC20 asset data const extraData = '0102030405060708'; const encodedAssetData = `${encodeERC20AssetData(erc20TokenA.address)}${extraData}`; // Perform a transfer from fromAddress to toAddress const erc20Balances = await erc20Wrapper.getBalancesAsync(); const amount = new BigNumber(10); const data = assetProxyInterface .transferFrom(encodedAssetData, fromAddress, toAddress, amount) .getABIEncodedTransactionData(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: erc20Proxy.address, data, from: authorized, }), constants.AWAIT_TRANSACTION_MINED_MS, ); // Verify transfer was successful const newBalances = await erc20Wrapper.getBalancesAsync(); expect(newBalances[fromAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[fromAddress][erc20TokenA.address].minus(amount), ); expect(newBalances[toAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[toAddress][erc20TokenA.address].plus(amount), ); }); it('should do nothing if transferring 0 amount of a token', async () => { // Construct ERC20 asset data const encodedAssetData = encodeERC20AssetData(erc20TokenA.address); // Perform a transfer from fromAddress to toAddress const erc20Balances = await erc20Wrapper.getBalancesAsync(); const amount = new BigNumber(0); const data = assetProxyInterface .transferFrom(encodedAssetData, fromAddress, toAddress, amount) .getABIEncodedTransactionData(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: erc20Proxy.address, data, from: authorized, }), constants.AWAIT_TRANSACTION_MINED_MS, ); // Verify transfer was successful const newBalances = await erc20Wrapper.getBalancesAsync(); expect(newBalances[fromAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[fromAddress][erc20TokenA.address], ); expect(newBalances[toAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[toAddress][erc20TokenA.address], ); }); it('should revert if allowances are too low', async () => { // Construct ERC20 asset data const encodedAssetData = encodeERC20AssetData(erc20TokenA.address); // Create allowance less than transfer amount. Set allowance on proxy. const allowance = new BigNumber(0); const amount = new BigNumber(10); const data = assetProxyInterface .transferFrom(encodedAssetData, fromAddress, toAddress, amount) .getABIEncodedTransactionData(); await erc20TokenA.approve(erc20Proxy.address, allowance).awaitTransactionSuccessAsync({ from: fromAddress, }); const erc20Balances = await erc20Wrapper.getBalancesAsync(); // Perform a transfer; expect this to fail. await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: erc20Proxy.address, data, from: authorized, }), RevertReason.TransferFailed, ); const newBalances = await erc20Wrapper.getBalancesAsync(); expect(newBalances).to.deep.equal(erc20Balances); }); it('should revert if allowances are too low and token does not return a value', async () => { // Construct ERC20 asset data const encodedAssetData = encodeERC20AssetData(noReturnErc20Token.address); // Create allowance less than transfer amount. Set allowance on proxy. const allowance = new BigNumber(0); const amount = new BigNumber(10); const data = assetProxyInterface .transferFrom(encodedAssetData, fromAddress, toAddress, amount) .getABIEncodedTransactionData(); await noReturnErc20Token.approve(erc20Proxy.address, allowance).awaitTransactionSuccessAsync({ from: fromAddress, }); const initialFromBalance = await noReturnErc20Token.balanceOf(fromAddress).callAsync(); const initialToBalance = await noReturnErc20Token.balanceOf(toAddress).callAsync(); // Perform a transfer; expect this to fail. await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: erc20Proxy.address, data, from: authorized, }), RevertReason.TransferFailed, ); const newFromBalance = await noReturnErc20Token.balanceOf(fromAddress).callAsync(); const newToBalance = await noReturnErc20Token.balanceOf(toAddress).callAsync(); expect(newFromBalance).to.be.bignumber.equal(initialFromBalance); expect(newToBalance).to.be.bignumber.equal(initialToBalance); }); it('should revert if caller is not authorized', async () => { // Construct ERC20 asset data const encodedAssetData = encodeERC20AssetData(erc20TokenA.address); // Perform a transfer from fromAddress to toAddress const amount = new BigNumber(10); const data = assetProxyInterface .transferFrom(encodedAssetData, fromAddress, toAddress, amount) .getABIEncodedTransactionData(); const erc20Balances = await erc20Wrapper.getBalancesAsync(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: erc20Proxy.address, data, from: notAuthorized, }), RevertReason.SenderNotAuthorized, ); const newBalances = await erc20Wrapper.getBalancesAsync(); expect(newBalances).to.deep.equal(erc20Balances); }); it('should revert if token returns more than 32 bytes', async () => { // Construct ERC20 asset data const encodedAssetData = encodeERC20AssetData(multipleReturnErc20Token.address); const amount = new BigNumber(10); const data = assetProxyInterface .transferFrom(encodedAssetData, fromAddress, toAddress, amount) .getABIEncodedTransactionData(); const initialFromBalance = await multipleReturnErc20Token.balanceOf(fromAddress).callAsync(); const initialToBalance = await multipleReturnErc20Token.balanceOf(toAddress).callAsync(); // Perform a transfer; expect this to fail. await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: erc20Proxy.address, data, from: authorized, }), RevertReason.TransferFailed, ); const newFromBalance = await multipleReturnErc20Token.balanceOf(fromAddress).callAsync(); const newToBalance = await multipleReturnErc20Token.balanceOf(toAddress).callAsync(); expect(newFromBalance).to.be.bignumber.equal(initialFromBalance); expect(newToBalance).to.be.bignumber.equal(initialToBalance); }); }); }); describe('ERC721Proxy', () => { it('should revert if undefined function is called', async () => { const undefinedSelector = '0x01020304'; await expectTransactionFailedWithoutReasonAsync( web3Wrapper.sendTransactionAsync({ from: owner, to: erc721Proxy.address, value: constants.ZERO_AMOUNT, data: undefinedSelector, }), ); }); it('should have an id of 0x02571792', async () => { const proxyId = await erc721Proxy.getProxyId().callAsync(); const expectedProxyId = '0x02571792'; expect(proxyId).to.equal(expectedProxyId); }); describe('transferFrom', () => { it('should successfully transfer tokens', async () => { // Construct ERC721 asset data const encodedAssetData = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId); // Verify pre-condition const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); // Perform a transfer from fromAddress to toAddress const amount = new BigNumber(1); const data = assetProxyInterface .transferFrom(encodedAssetData, fromAddress, toAddress, amount) .getABIEncodedTransactionData(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: erc721Proxy.address, data, from: authorized, }), constants.AWAIT_TRANSACTION_MINED_MS, ); // Verify transfer was successful const newOwnerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwnerFromAsset).to.be.bignumber.equal(toAddress); }); it('should successfully transfer tokens and ignore extra assetData', async () => { // Construct ERC721 asset data const extraData = '0102030405060708'; const encodedAssetData = `${encodeERC721AssetData( erc721TokenA.address, erc721AFromTokenId, )}${extraData}`; // Verify pre-condition const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); // Perform a transfer from fromAddress to toAddress const amount = new BigNumber(1); const data = assetProxyInterface .transferFrom(encodedAssetData, fromAddress, toAddress, amount) .getABIEncodedTransactionData(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: erc721Proxy.address, data, from: authorized, }), constants.AWAIT_TRANSACTION_MINED_MS, ); // Verify transfer was successful const newOwnerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwnerFromAsset).to.be.bignumber.equal(toAddress); }); it('should not call onERC721Received when transferring to a smart contract', async () => { // Construct ERC721 asset data const encodedAssetData = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId); // Verify pre-condition const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); // Perform a transfer from fromAddress to toAddress const amount = new BigNumber(1); const data = assetProxyInterface .transferFrom(encodedAssetData, fromAddress, erc721Receiver.address, amount) .getABIEncodedTransactionData(); const logDecoder = new LogDecoder(web3Wrapper, { ...artifacts, ...erc721Artifacts }); const tx = await logDecoder.getTxWithDecodedLogsAsync( await web3Wrapper.sendTransactionAsync({ to: erc721Proxy.address, data, from: authorized, gas: constants.MAX_TRANSFER_FROM_GAS, }), ); // Verify that no log was emitted by erc721 receiver expect(tx.logs.length).to.be.equal(1); // Verify transfer was successful const newOwnerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwnerFromAsset).to.be.bignumber.equal(erc721Receiver.address); }); it('should revert if transferring 0 amount of a token', async () => { // Construct ERC721 asset data const encodedAssetData = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId); // Verify pre-condition const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); // Perform a transfer from fromAddress to toAddress const amount = new BigNumber(0); const data = assetProxyInterface .transferFrom(encodedAssetData, fromAddress, toAddress, amount) .getABIEncodedTransactionData(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: erc721Proxy.address, data, from: authorized, }), RevertReason.InvalidAmount, ); const newOwner = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwner).to.be.equal(ownerFromAsset); }); it('should revert if transferring > 1 amount of a token', async () => { // Construct ERC721 asset data const encodedAssetData = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId); // Verify pre-condition const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); // Perform a transfer from fromAddress to toAddress const amount = new BigNumber(500); const data = assetProxyInterface .transferFrom(encodedAssetData, fromAddress, toAddress, amount) .getABIEncodedTransactionData(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: erc721Proxy.address, data, from: authorized, }), RevertReason.InvalidAmount, ); const newOwner = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwner).to.be.equal(ownerFromAsset); }); it('should revert if allowances are too low', async () => { // Construct ERC721 asset data const encodedAssetData = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId); // Verify pre-condition const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); // Remove blanket transfer approval for fromAddress. await erc721TokenA.setApprovalForAll(erc721Proxy.address, false).awaitTransactionSuccessAsync({ from: fromAddress, }); // Remove token transfer approval for fromAddress. await erc721TokenA.approve(constants.NULL_ADDRESS, erc721AFromTokenId).awaitTransactionSuccessAsync({ from: fromAddress, }); // Perform a transfer; expect this to fail. const amount = new BigNumber(1); const data = assetProxyInterface .transferFrom(encodedAssetData, fromAddress, toAddress, amount) .getABIEncodedTransactionData(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: erc721Proxy.address, data, from: authorized, }), RevertReason.TransferFailed, ); const newOwner = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwner).to.be.equal(ownerFromAsset); }); it('should revert if caller is not authorized', async () => { // Construct ERC721 asset data const encodedAssetData = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId); // Verify pre-condition const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); // Perform a transfer from fromAddress to toAddress const amount = new BigNumber(1); const data = assetProxyInterface .transferFrom(encodedAssetData, fromAddress, toAddress, amount) .getABIEncodedTransactionData(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: erc721Proxy.address, data, from: notAuthorized, }), RevertReason.SenderNotAuthorized, ); const newOwner = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwner).to.be.equal(ownerFromAsset); }); }); }); describe('MultiAssetProxy', () => { it('should revert if undefined function is called', async () => { const undefinedSelector = '0x01020304'; await expectTransactionFailedWithoutReasonAsync( web3Wrapper.sendTransactionAsync({ from: owner, to: multiAssetProxy.address, value: constants.ZERO_AMOUNT, data: undefinedSelector, }), ); }); it('should have an id of 0x94cfcdd7', async () => { const proxyId = await multiAssetProxy.getProxyId().callAsync(); // first 4 bytes of `keccak256('MultiAsset(uint256[],bytes[])')` const expectedProxyId = '0x94cfcdd7'; expect(proxyId).to.equal(expectedProxyId); }); describe('transferFrom', () => { it('should transfer a single ERC20 token', async () => { const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); const erc20AssetData = encodeERC20AssetData(erc20TokenA.address); const amounts = [erc20Amount]; const nestedAssetData = [erc20AssetData]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); const erc20Balances = await erc20Wrapper.getBalancesAsync(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: authorized, }), constants.AWAIT_TRANSACTION_MINED_MS, ); const newBalances = await erc20Wrapper.getBalancesAsync(); const totalAmount = inputAmount.times(erc20Amount); expect(newBalances[fromAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[fromAddress][erc20TokenA.address].minus(totalAmount), ); expect(newBalances[toAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[toAddress][erc20TokenA.address].plus(totalAmount), ); }); it('should dispatch an ERC20 transfer when input amount is 0', async () => { const inputAmount = constants.ZERO_AMOUNT; const erc20Amount = new BigNumber(10); const erc20AssetData = encodeERC20AssetData(erc20TokenA.address); const amounts = [erc20Amount]; const nestedAssetData = [erc20AssetData]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); const erc20Balances = await erc20Wrapper.getBalancesAsync(); const logDecoder = new LogDecoder(web3Wrapper, { ...artifacts, ...erc20Artifacts }); const tx = await logDecoder.getTxWithDecodedLogsAsync( await web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: authorized, }), ); expect(tx.logs.length).to.be.equal(1); const log = tx.logs[0] as LogWithDecodedArgs<DummyERC20TokenTransferEventArgs>; const transferEventName = 'Transfer'; expect(log.event).to.equal(transferEventName); expect(log.args._value).to.be.bignumber.equal(constants.ZERO_AMOUNT); const newBalances = await erc20Wrapper.getBalancesAsync(); expect(newBalances).to.deep.equal(erc20Balances); }); it('should successfully transfer multiple of the same ERC20 token', async () => { const inputAmount = new BigNumber(1); const erc20Amount1 = new BigNumber(10); const erc20Amount2 = new BigNumber(20); const erc20AssetData1 = encodeERC20AssetData(erc20TokenA.address); const erc20AssetData2 = encodeERC20AssetData(erc20TokenA.address); const amounts = [erc20Amount1, erc20Amount2]; const nestedAssetData = [erc20AssetData1, erc20AssetData2]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); const erc20Balances = await erc20Wrapper.getBalancesAsync(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: authorized, }), constants.AWAIT_TRANSACTION_MINED_MS, ); const newBalances = await erc20Wrapper.getBalancesAsync(); const totalAmount = inputAmount.times(erc20Amount1).plus(inputAmount.times(erc20Amount2)); expect(newBalances[fromAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[fromAddress][erc20TokenA.address].minus(totalAmount), ); expect(newBalances[toAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[toAddress][erc20TokenA.address].plus(totalAmount), ); }); it('should successfully transfer multiple different ERC20 tokens', async () => { const inputAmount = new BigNumber(1); const erc20Amount1 = new BigNumber(10); const erc20Amount2 = new BigNumber(20); const erc20AssetData1 = encodeERC20AssetData(erc20TokenA.address); const erc20AssetData2 = encodeERC20AssetData(erc20TokenB.address); const amounts = [erc20Amount1, erc20Amount2]; const nestedAssetData = [erc20AssetData1, erc20AssetData2]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); const erc20Balances = await erc20Wrapper.getBalancesAsync(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: authorized, }), constants.AWAIT_TRANSACTION_MINED_MS, ); const newBalances = await erc20Wrapper.getBalancesAsync(); const totalErc20AAmount = inputAmount.times(erc20Amount1); const totalErc20BAmount = inputAmount.times(erc20Amount2); expect(newBalances[fromAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[fromAddress][erc20TokenA.address].minus(totalErc20AAmount), ); expect(newBalances[toAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[toAddress][erc20TokenA.address].plus(totalErc20AAmount), ); expect(newBalances[fromAddress][erc20TokenB.address]).to.be.bignumber.equal( erc20Balances[fromAddress][erc20TokenB.address].minus(totalErc20BAmount), ); expect(newBalances[toAddress][erc20TokenB.address]).to.be.bignumber.equal( erc20Balances[toAddress][erc20TokenB.address].plus(totalErc20BAmount), ); }); it('should transfer a single ERC721 token', async () => { const inputAmount = new BigNumber(1); const erc721Amount = new BigNumber(1); const erc721AssetData = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId); const amounts = [erc721Amount]; const nestedAssetData = [erc721AssetData]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: authorized, }), constants.AWAIT_TRANSACTION_MINED_MS, ); const newOwnerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwnerFromAsset).to.be.equal(toAddress); }); it('should successfully transfer multiple of the same ERC721 token', async () => { const erc721Balances = await erc721Wrapper.getBalancesAsync(); const erc721AFromTokenId2 = erc721Balances[fromAddress][erc721TokenA.address][1]; const erc721AssetData1 = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId); const erc721AssetData2 = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId2); const inputAmount = new BigNumber(1); const erc721Amount = new BigNumber(1); const amounts = [erc721Amount, erc721Amount]; const nestedAssetData = [erc721AssetData1, erc721AssetData2]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); const ownerFromAsset1 = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset1).to.be.equal(fromAddress); const ownerFromAsset2 = await erc721TokenA.ownerOf(erc721AFromTokenId2).callAsync(); expect(ownerFromAsset2).to.be.equal(fromAddress); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: authorized, gas: constants.MAX_TRANSFER_FROM_GAS, }), constants.AWAIT_TRANSACTION_MINED_MS, ); const newOwnerFromAsset1 = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); const newOwnerFromAsset2 = await erc721TokenA.ownerOf(erc721AFromTokenId2).callAsync(); expect(newOwnerFromAsset1).to.be.equal(toAddress); expect(newOwnerFromAsset2).to.be.equal(toAddress); }); it('should successfully transfer multiple different ERC721 tokens', async () => { const erc721AssetData1 = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId); const erc721AssetData2 = encodeERC721AssetData(erc721TokenB.address, erc721BFromTokenId); const inputAmount = new BigNumber(1); const erc721Amount = new BigNumber(1); const amounts = [erc721Amount, erc721Amount]; const nestedAssetData = [erc721AssetData1, erc721AssetData2]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); const ownerFromAsset1 = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset1).to.be.equal(fromAddress); const ownerFromAsset2 = await erc721TokenB.ownerOf(erc721BFromTokenId).callAsync(); expect(ownerFromAsset2).to.be.equal(fromAddress); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: authorized, gas: constants.MAX_TRANSFER_FROM_GAS, }), constants.AWAIT_TRANSACTION_MINED_MS, ); const newOwnerFromAsset1 = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); const newOwnerFromAsset2 = await erc721TokenB.ownerOf(erc721BFromTokenId).callAsync(); expect(newOwnerFromAsset1).to.be.equal(toAddress); expect(newOwnerFromAsset2).to.be.equal(toAddress); }); it('should transfer a fungible ERC1155 token', async () => { // setup test parameters const tokenHolders = [fromAddress, toAddress]; const tokensToTransfer = erc1155FungibleTokens.slice(0, 1); const valuesToTransfer = [new BigNumber(25)]; const valueMultiplier = new BigNumber(23); const receiverCallbackData = '0x0102030405'; // check balances before transfer const expectedInitialBalances = [ // from constants.INITIAL_ERC1155_FUNGIBLE_BALANCE, // to constants.INITIAL_ERC1155_FUNGIBLE_BALANCE, ]; await erc1155Wrapper.assertBalancesAsync(tokenHolders, tokensToTransfer, expectedInitialBalances); // encode erc1155 asset data const erc1155AssetData = encodeERC1155AssetData( erc1155Contract.address, tokensToTransfer, valuesToTransfer, receiverCallbackData, ); // encode multi-asset data const multiAssetAmount = new BigNumber(5); const amounts = [valueMultiplier]; const nestedAssetData = [erc1155AssetData]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, multiAssetAmount) .getABIEncodedTransactionData(); // execute transfer await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: authorized, }), constants.AWAIT_TRANSACTION_MINED_MS, ); // check balances const totalValueTransferred = valuesToTransfer[0].times(valueMultiplier).times(multiAssetAmount); const expectedFinalBalances = [ // from expectedInitialBalances[0].minus(totalValueTransferred), // to expectedInitialBalances[1].plus(totalValueTransferred), ]; await erc1155Wrapper.assertBalancesAsync(tokenHolders, tokensToTransfer, expectedFinalBalances); }); it('should successfully transfer multiple fungible tokens of the same ERC1155 contract', async () => { // setup test parameters const tokenHolders = [fromAddress, toAddress]; const tokensToTransfer = erc1155FungibleTokens.slice(0, 3); const valuesToTransfer = [new BigNumber(25), new BigNumber(35), new BigNumber(45)]; const valueMultiplier = new BigNumber(23); const receiverCallbackData = '0x0102030405'; // check balances before transfer const expectedInitialBalances = [ // from constants.INITIAL_ERC1155_FUNGIBLE_BALANCE, constants.INITIAL_ERC1155_FUNGIBLE_BALANCE, constants.INITIAL_ERC1155_FUNGIBLE_BALANCE, // to constants.INITIAL_ERC1155_FUNGIBLE_BALANCE, constants.INITIAL_ERC1155_FUNGIBLE_BALANCE, constants.INITIAL_ERC1155_FUNGIBLE_BALANCE, ]; await erc1155Wrapper.assertBalancesAsync(tokenHolders, tokensToTransfer, expectedInitialBalances); // encode erc1155 asset data const erc1155AssetData = encodeERC1155AssetData( erc1155Contract.address, tokensToTransfer, valuesToTransfer, receiverCallbackData, ); // encode multi-asset data const multiAssetAmount = new BigNumber(5); const amounts = [valueMultiplier]; const nestedAssetData = [erc1155AssetData]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, multiAssetAmount) .getABIEncodedTransactionData(); // execute transfer await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: authorized, }), constants.AWAIT_TRANSACTION_MINED_MS, ); // check balances const totalValuesTransferred = _.map(valuesToTransfer, (value: BigNumber) => { return value.times(valueMultiplier).times(multiAssetAmount); }); const expectedFinalBalances = [ // from expectedInitialBalances[0].minus(totalValuesTransferred[0]), expectedInitialBalances[1].minus(totalValuesTransferred[1]), expectedInitialBalances[2].minus(totalValuesTransferred[2]), // to expectedInitialBalances[3].plus(totalValuesTransferred[0]), expectedInitialBalances[4].plus(totalValuesTransferred[1]), expectedInitialBalances[5].plus(totalValuesTransferred[2]), ]; await erc1155Wrapper.assertBalancesAsync(tokenHolders, tokensToTransfer, expectedFinalBalances); }); it('should successfully transfer multiple fungible/non-fungible tokens of the same ERC1155 contract', async () => { // setup test parameters const tokenHolders = [fromAddress, toAddress]; const fungibleTokensToTransfer = erc1155FungibleTokens.slice(0, 1); const nonFungibleTokensToTransfer = erc1155NonFungibleTokensOwnedBySpender.slice(0, 1); const tokensToTransfer = fungibleTokensToTransfer.concat(nonFungibleTokensToTransfer); const valuesToTransfer = [new BigNumber(25), new BigNumber(1)]; const valueMultiplier = new BigNumber(1); const receiverCallbackData = '0x0102030405'; // check balances before transfer const nftOwnerBalance = new BigNumber(1); const nftNotOwnerBalance = new BigNumber(0); const expectedInitialBalances = [ // from constants.INITIAL_ERC1155_FUNGIBLE_BALANCE, nftOwnerBalance, // to constants.INITIAL_ERC1155_FUNGIBLE_BALANCE, nftNotOwnerBalance, ]; await erc1155Wrapper.assertBalancesAsync(tokenHolders, tokensToTransfer, expectedInitialBalances); // encode erc1155 asset data const erc1155AssetData = encodeERC1155AssetData( erc1155Contract.address, tokensToTransfer, valuesToTransfer, receiverCallbackData, ); // encode multi-asset data const multiAssetAmount = new BigNumber(1); const amounts = [valueMultiplier]; const nestedAssetData = [erc1155AssetData]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, multiAssetAmount) .getABIEncodedTransactionData(); // execute transfer await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: authorized, }), constants.AWAIT_TRANSACTION_MINED_MS, ); // check balances const totalValuesTransferred = _.map(valuesToTransfer, (value: BigNumber) => { return value.times(valueMultiplier).times(multiAssetAmount); }); const expectedFinalBalances = [ // from expectedInitialBalances[0].minus(totalValuesTransferred[0]), expectedInitialBalances[1].minus(totalValuesTransferred[1]), // to expectedInitialBalances[2].plus(totalValuesTransferred[0]), expectedInitialBalances[3].plus(totalValuesTransferred[1]), ]; await erc1155Wrapper.assertBalancesAsync(tokenHolders, tokensToTransfer, expectedFinalBalances); }); // TODO(dorothy-zbornak): Figure out why this test fails. it.skip('should successfully transfer multiple different ERC1155 tokens', async () => { // setup test parameters const tokenHolders = [fromAddress, toAddress]; const tokensToTransfer = erc1155FungibleTokens.slice(0, 1); const valuesToTransfer = [new BigNumber(25)]; const valueMultiplier = new BigNumber(23); const receiverCallbackData = '0x0102030405'; // check balances before transfer const expectedInitialBalances = [ // from constants.INITIAL_ERC1155_FUNGIBLE_BALANCE, // to constants.INITIAL_ERC1155_FUNGIBLE_BALANCE, ]; await erc1155Wrapper.assertBalancesAsync(tokenHolders, tokensToTransfer, expectedInitialBalances); await erc1155Wrapper2.assertBalancesAsync(tokenHolders, tokensToTransfer, expectedInitialBalances); // encode erc1155 asset data const erc1155AssetData1 = encodeERC1155AssetData( erc1155Contract.address, tokensToTransfer, valuesToTransfer, receiverCallbackData, ); const erc1155AssetData2 = encodeERC1155AssetData( erc1155Contract2.address, tokensToTransfer, valuesToTransfer, receiverCallbackData, ); // encode multi-asset data const multiAssetAmount = new BigNumber(5); const amounts = [valueMultiplier, valueMultiplier]; const nestedAssetData = [erc1155AssetData1, erc1155AssetData2]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, multiAssetAmount) .getABIEncodedTransactionData(); // execute transfer await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: authorized, }), constants.AWAIT_TRANSACTION_MINED_MS, ); // check balances const totalValueTransferred = valuesToTransfer[0].times(valueMultiplier).times(multiAssetAmount); const expectedFinalBalances = [ // from expectedInitialBalances[0].minus(totalValueTransferred), // to expectedInitialBalances[1].plus(totalValueTransferred), ]; await erc1155Wrapper.assertBalancesAsync(tokenHolders, tokensToTransfer, expectedFinalBalances); await erc1155Wrapper2.assertBalancesAsync(tokenHolders, tokensToTransfer, expectedFinalBalances); }); it('should successfully transfer a combination of ERC20, ERC721, and ERC1155 tokens', async () => { // setup test parameters const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); const erc20AssetData = encodeERC20AssetData(erc20TokenA.address); const erc721Amount = new BigNumber(1); const erc721AssetData = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId); const erc1155TokenHolders = [fromAddress, toAddress]; const erc1155TokensToTransfer = erc1155FungibleTokens.slice(0, 1); const erc1155ValuesToTransfer = [new BigNumber(25)]; const erc1155Amount = new BigNumber(23); const erc1155ReceiverCallbackData = '0x0102030405'; const erc1155AssetData = encodeERC1155AssetData( erc1155Contract.address, erc1155TokensToTransfer, erc1155ValuesToTransfer, erc1155ReceiverCallbackData, ); const amounts = [erc20Amount, erc721Amount, erc1155Amount]; const nestedAssetData = [erc20AssetData, erc721AssetData, erc1155AssetData]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); // check balances before transfer const erc20Balances = await erc20Wrapper.getBalancesAsync(); const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); const erc1155ExpectedInitialBalances = [ constants.INITIAL_ERC1155_FUNGIBLE_BALANCE, constants.INITIAL_ERC1155_FUNGIBLE_BALANCE, ]; await erc1155Wrapper.assertBalancesAsync( erc1155TokenHolders, erc1155TokensToTransfer, erc1155ExpectedInitialBalances, ); // execute transfer await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: authorized, gas: 1000000, }), constants.AWAIT_TRANSACTION_MINED_MS, ); // check balances after transfer const newBalances = await erc20Wrapper.getBalancesAsync(); const totalAmount = inputAmount.times(erc20Amount); expect(newBalances[fromAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[fromAddress][erc20TokenA.address].minus(totalAmount), ); expect(newBalances[toAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[toAddress][erc20TokenA.address].plus(totalAmount), ); const newOwnerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwnerFromAsset).to.be.equal(toAddress); const erc1155TotalValueTransferred = erc1155ValuesToTransfer[0].times(erc1155Amount).times(inputAmount); const expectedFinalBalances = [ erc1155ExpectedInitialBalances[0].minus(erc1155TotalValueTransferred), erc1155ExpectedInitialBalances[1].plus(erc1155TotalValueTransferred), ]; await erc1155Wrapper.assertBalancesAsync( erc1155TokenHolders, erc1155TokensToTransfer, expectedFinalBalances, ); }); it('should successfully transfer a combination of ERC20 and ERC721 tokens', async () => { const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); const erc20AssetData = encodeERC20AssetData(erc20TokenA.address); const erc721Amount = new BigNumber(1); const erc721AssetData = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId); const amounts = [erc20Amount, erc721Amount]; const nestedAssetData = [erc20AssetData, erc721AssetData]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); const erc20Balances = await erc20Wrapper.getBalancesAsync(); const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: authorized, }), constants.AWAIT_TRANSACTION_MINED_MS, ); const newBalances = await erc20Wrapper.getBalancesAsync(); const totalAmount = inputAmount.times(erc20Amount); expect(newBalances[fromAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[fromAddress][erc20TokenA.address].minus(totalAmount), ); expect(newBalances[toAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[toAddress][erc20TokenA.address].plus(totalAmount), ); const newOwnerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwnerFromAsset).to.be.equal(toAddress); }); // TODO(dorothy-zbornak): Figure out why this test fails. it.skip('should successfully transfer tokens and ignore extra assetData', async () => { const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); const erc20AssetData = encodeERC20AssetData(erc20TokenA.address); const erc721Amount = new BigNumber(1); const erc721AssetData = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId); const amounts = [erc20Amount, erc721Amount]; const nestedAssetData = [erc20AssetData, erc721AssetData]; const extraData = '0102030405060708090001020304050607080900010203040506070809000102'; const assetData = `${encodeMultiAssetData(amounts, nestedAssetData)}${extraData}`; const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); const erc20Balances = await erc20Wrapper.getBalancesAsync(); const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: authorized, }), constants.AWAIT_TRANSACTION_MINED_MS, ); const newBalances = await erc20Wrapper.getBalancesAsync(); const totalAmount = inputAmount.times(erc20Amount); expect(newBalances[fromAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[fromAddress][erc20TokenA.address].minus(totalAmount), ); expect(newBalances[toAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[toAddress][erc20TokenA.address].plus(totalAmount), ); const newOwnerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwnerFromAsset).to.be.equal(toAddress); }); it('should successfully transfer correct amounts when the `amount` > 1', async () => { const inputAmount = new BigNumber(100); const erc20Amount1 = new BigNumber(10); const erc20Amount2 = new BigNumber(20); const erc20AssetData1 = encodeERC20AssetData(erc20TokenA.address); const erc20AssetData2 = encodeERC20AssetData(erc20TokenB.address); const amounts = [erc20Amount1, erc20Amount2]; const nestedAssetData = [erc20AssetData1, erc20AssetData2]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); const erc20Balances = await erc20Wrapper.getBalancesAsync(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: authorized, }), constants.AWAIT_TRANSACTION_MINED_MS, ); const newBalances = await erc20Wrapper.getBalancesAsync(); const totalErc20AAmount = inputAmount.times(erc20Amount1); const totalErc20BAmount = inputAmount.times(erc20Amount2); expect(newBalances[fromAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[fromAddress][erc20TokenA.address].minus(totalErc20AAmount), ); expect(newBalances[toAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[toAddress][erc20TokenA.address].plus(totalErc20AAmount), ); expect(newBalances[fromAddress][erc20TokenB.address]).to.be.bignumber.equal( erc20Balances[fromAddress][erc20TokenB.address].minus(totalErc20BAmount), ); expect(newBalances[toAddress][erc20TokenB.address]).to.be.bignumber.equal( erc20Balances[toAddress][erc20TokenB.address].plus(totalErc20BAmount), ); }); it('should successfully transfer a large amount of tokens', async () => { const inputAmount = new BigNumber(1); const erc20Amount1 = new BigNumber(10); const erc20Amount2 = new BigNumber(20); const erc20AssetData1 = encodeERC20AssetData(erc20TokenA.address); const erc20AssetData2 = encodeERC20AssetData(erc20TokenB.address); const erc721Amount = new BigNumber(1); const erc721Balances = await erc721Wrapper.getBalancesAsync(); const erc721AFromTokenId2 = erc721Balances[fromAddress][erc721TokenA.address][1]; const erc721BFromTokenId2 = erc721Balances[fromAddress][erc721TokenB.address][1]; const erc721AssetData1 = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId); const erc721AssetData2 = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId2); const erc721AssetData3 = encodeERC721AssetData(erc721TokenB.address, erc721BFromTokenId); const erc721AssetData4 = encodeERC721AssetData(erc721TokenB.address, erc721BFromTokenId2); const amounts = [erc721Amount, erc20Amount1, erc721Amount, erc20Amount2, erc721Amount, erc721Amount]; const nestedAssetData = [ erc721AssetData1, erc20AssetData1, erc721AssetData2, erc20AssetData2, erc721AssetData3, erc721AssetData4, ]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); const ownerFromAsset1 = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset1).to.be.equal(fromAddress); const ownerFromAsset2 = await erc721TokenA.ownerOf(erc721AFromTokenId2).callAsync(); expect(ownerFromAsset2).to.be.equal(fromAddress); const ownerFromAsset3 = await erc721TokenB.ownerOf(erc721BFromTokenId).callAsync(); expect(ownerFromAsset3).to.be.equal(fromAddress); const ownerFromAsset4 = await erc721TokenB.ownerOf(erc721BFromTokenId2).callAsync(); expect(ownerFromAsset4).to.be.equal(fromAddress); const erc20Balances = await erc20Wrapper.getBalancesAsync(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: authorized, gas: constants.MAX_EXECUTE_TRANSACTION_GAS, }), constants.AWAIT_TRANSACTION_MINED_MS, ); const newOwnerFromAsset1 = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); const newOwnerFromAsset2 = await erc721TokenA.ownerOf(erc721AFromTokenId2).callAsync(); const newOwnerFromAsset3 = await erc721TokenB.ownerOf(erc721BFromTokenId).callAsync(); const newOwnerFromAsset4 = await erc721TokenB.ownerOf(erc721BFromTokenId2).callAsync(); expect(newOwnerFromAsset1).to.be.equal(toAddress); expect(newOwnerFromAsset2).to.be.equal(toAddress); expect(newOwnerFromAsset3).to.be.equal(toAddress); expect(newOwnerFromAsset4).to.be.equal(toAddress); const newBalances = await erc20Wrapper.getBalancesAsync(); const totalErc20AAmount = inputAmount.times(erc20Amount1); const totalErc20BAmount = inputAmount.times(erc20Amount2); expect(newBalances[fromAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[fromAddress][erc20TokenA.address].minus(totalErc20AAmount), ); expect(newBalances[toAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[toAddress][erc20TokenA.address].plus(totalErc20AAmount), ); expect(newBalances[fromAddress][erc20TokenB.address]).to.be.bignumber.equal( erc20Balances[fromAddress][erc20TokenB.address].minus(totalErc20BAmount), ); expect(newBalances[toAddress][erc20TokenB.address]).to.be.bignumber.equal( erc20Balances[toAddress][erc20TokenB.address].plus(totalErc20BAmount), ); }); it('should revert if a single transfer fails', async () => { const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); const erc20AssetData = encodeERC20AssetData(erc20TokenA.address); // 2 is an invalid erc721 amount const erc721Amount = new BigNumber(2); const erc721AssetData = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId); const amounts = [erc20Amount, erc721Amount]; const nestedAssetData = [erc20AssetData, erc721AssetData]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: authorized, }), RevertReason.InvalidAmount, ); }); it('should revert if an AssetProxy is not registered', async () => { const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); const erc20AssetData = encodeERC20AssetData(erc20TokenA.address); const erc721Amount = new BigNumber(1); const erc721AssetData = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId); const invalidProxyId = '0x12345678'; const invalidErc721AssetData = `${invalidProxyId}${erc721AssetData.slice(10)}`; const amounts = [erc20Amount, erc721Amount]; const nestedAssetData = [erc20AssetData, invalidErc721AssetData]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: authorized, }), RevertReason.AssetProxyDoesNotExist, ); }); it('should revert if the length of `amounts` does not match the length of `nestedAssetData`', async () => { const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); const erc20AssetData = encodeERC20AssetData(erc20TokenA.address); const erc721AssetData = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId); const amounts = [erc20Amount]; const nestedAssetData = [erc20AssetData, erc721AssetData]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: authorized, }), RevertReason.LengthMismatch, ); }); it('should revert if amounts multiplication results in an overflow', async () => { const inputAmount = new BigNumber(2).pow(128); const erc20Amount = new BigNumber(2).pow(128); const erc20AssetData = encodeERC20AssetData(erc20TokenA.address); const amounts = [erc20Amount]; const nestedAssetData = [erc20AssetData]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: authorized, }), RevertReason.Uint256Overflow, ); }); it('should revert if an element of `nestedAssetData` is < 4 bytes long', async () => { const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); const erc20AssetData = encodeERC20AssetData(erc20TokenA.address); const erc721Amount = new BigNumber(1); const erc721AssetData = '0x123456'; const amounts = [erc20Amount, erc721Amount]; const nestedAssetData = [erc20AssetData, erc721AssetData]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: authorized, }), RevertReason.LengthGreaterThan3Required, ); }); it('should revert if caller is not authorized', async () => { const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); const erc20AssetData = encodeERC20AssetData(erc20TokenA.address); const erc721Amount = new BigNumber(1); const erc721AssetData = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId); const amounts = [erc20Amount, erc721Amount]; const nestedAssetData = [erc20AssetData, erc721AssetData]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data, from: notAuthorized, }), RevertReason.SenderNotAuthorized, ); }); it('should revert if asset data overflows beyond the bounds of calldata', async () => { const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); const erc20AssetData = encodeERC20AssetData(erc20TokenA.address); const erc721Amount = new BigNumber(1); const erc721AssetData = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId); const amounts = [erc20Amount, erc721Amount]; const nestedAssetData = [erc20AssetData, erc721AssetData]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); // append asset data to end of tx data with a length of 0x300 bytes, which will extend past actual calldata. const offsetToAssetData = '0000000000000000000000000000000000000000000000000000000000000080'; const invalidOffsetToAssetData = '00000000000000000000000000000000000000000000000000000000000002a0'; const newAssetData = '0000000000000000000000000000000000000000000000000000000000000304'; const badData = `${data.replace(offsetToAssetData, invalidOffsetToAssetData)}${newAssetData}`; // execute transfer await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data: badData, from: authorized, }), RevertReason.InvalidAssetDataEnd, ); }); it('should revert if asset data resolves to a location beyond the bounds of calldata', async () => { const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); const erc20AssetData = encodeERC20AssetData(erc20TokenA.address); const erc721Amount = new BigNumber(1); const erc721AssetData = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId); const amounts = [erc20Amount, erc721Amount]; const nestedAssetData = [erc20AssetData, erc721AssetData]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const data = assetProxyInterface .transferFrom(assetData, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); const offsetToAssetData = '0000000000000000000000000000000000000000000000000000000000000080'; const invalidOffsetToAssetData = '0000000000000000000000000000000000000000000000000000000000000400'; const badData = data.replace(offsetToAssetData, invalidOffsetToAssetData); // execute transfer // note that this triggers `InvalidAssetDataLength` because the length is zero, otherwise it would // trigger `InvalidAssetDataEnd`. await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data: badData, from: authorized, }), RevertReason.InvalidAssetDataLength, ); }); it('should revert if length of assetData, excluding the selector, is not a multiple of 32', async () => { // setup test parameters const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); const erc20AssetData = encodeERC20AssetData(erc20TokenA.address); const erc721Amount = new BigNumber(1); const erc721AssetData = encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId); const amounts = [erc20Amount, erc721Amount]; const nestedAssetData = [erc20AssetData, erc721AssetData]; const assetData = encodeMultiAssetData(amounts, nestedAssetData); const extraData = '01'; const assetDataWithExtraData = `${assetData}${extraData}`; const badData = assetProxyInterface .transferFrom(assetDataWithExtraData, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); // execute transfer await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data: badData, from: authorized, }), RevertReason.InvalidAssetDataLength, ); }); it('should revert if length of assetData is less than 68 bytes', async () => { // setup test parameters const inputAmount = new BigNumber(1); // we'll construct asset data that has a 4 byte selector plus // 32 byte payload. This results in asset data that is 36 bytes // long and will trigger the `invalid length` error. // we must be sure to use a # of bytes that is still %32 // so that we know the error is not triggered by another check in the code. const zeros32Bytes = '0'.repeat(64); const assetData36Bytes = `${AssetProxyId.MultiAsset}${zeros32Bytes}`; const badData = assetProxyInterface .transferFrom(assetData36Bytes, fromAddress, toAddress, inputAmount) .getABIEncodedTransactionData(); // execute transfer await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, data: badData, from: authorized, }), RevertReason.InvalidAssetDataLength, ); }); }); }); }); // tslint:enable:no-unnecessary-type-assertion // tslint:disable:max-file-line-count
the_stack
import config from "../config"; import { Connection, MessageType } from "../connection"; import Utils from "../utils"; import UIC from "./components"; import { Platform, SpotifyUtils } from "../spotify-apis"; import Resources from "../resources"; import ComponentsStyle from "./css/components.css"; import SettingsStyle from "./css/settings.css"; import StatusIndicatorStyle from "./css/status-indicator.css"; import { PathTemplate, TemplatedSearchTree } from "../path-template"; const MergedStyles = [ComponentsStyle, SettingsStyle, StatusIndicatorStyle].join('\n'); //TODO: find a better way to do this export const Icons = { Apps: `<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M4 8h4V4H4v4zm6 12h4v-4h-4v4zm-6 0h4v-4H4v4zm0-6h4v-4H4v4zm6 0h4v-4h-4v4zm6-10v4h4V4h-4zm-6 4h4V4h-4v4zm6 6h4v-4h-4v4zm0 6h4v-4h-4v4z"/></svg>`, Album: `<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 14.5c-2.49 0-4.5-2.01-4.5-4.5S9.51 7.5 12 7.5s4.5 2.01 4.5 4.5-2.01 4.5-4.5 4.5zm0-5.5c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1z"/></svg>`, List: `<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M2 17h2v.5H3v1h1v.5H2v1h3v-4H2v1zm1-9h1V4H2v1h1v3zm-1 3h1.8L2 13.1v.9h3v-1H3.2L5 10.9V10H2v1zm5-6v2h14V5H7zm0 14h14v-2H7v2zm0-6h14v-2H7v2z"/></svg>`, MagicWand: `<svg width="24" height="24" viewBox="-2 -2 28 28" fill="currentColor"><path d="M7.5 5.6L10 7 8.6 4.5 10 2 7.5 3.4 5 2l1.4 2.5L5 7zm12 9.8L17 14l1.4 2.5L17 19l2.5-1.4L22 19l-1.4-2.5L22 14zM22 2l-2.5 1.4L17 2l1.4 2.5L17 7l2.5-1.4L22 7l-1.4-2.5zm-7.63 5.29c-.39-.39-1.02-.39-1.41 0L1.29 18.96c-.39.39-.39 1.02 0 1.41l2.34 2.34c.39.39 1.02.39 1.41 0L16.7 11.05c.39-.39.39-1.02 0-1.41l-2.33-2.35zm-1.03 5.49l-2.12-2.12 2.44-2.44 2.12 2.12-2.44 2.44z"></path></svg>`, Folder: `<svg width="24px" height="24px" viewBox="0 0 24 24" fill="currentColor"><path d="M10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"></path></svg>`, Sliders: `<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M3 17v2h6v-2H3zM3 5v2h10V5H3zm10 16v-2h8v-2h-8v-2h-2v6h2zM7 9v2H3v2h4v2h2V9H7zm14 4v-2H11v2h10zm-6-4h2V7h4V5h-4V3h-2v6z"></path></svg>`, Done: `<svg width="16" height="16" viewBox="0 0 16 16" fill="#3f3"><path d="M13.985 2.383L5.127 12.754 1.388 8.375l-.658.77 4.397 5.149 9.618-11.262z"/></svg>`, Error: `<svg width="16" height="16" viewBox="0 0 16 16" fill="#f22"><path d="M14.354 2.353l-.708-.707L8 7.293 2.353 1.646l-.707.707L7.293 8l-5.647 5.646.707.708L8 8.707l5.646 5.647.708-.708L8.707 8z"/></svg>`, InProgress: `<svg width="18" height="18" viewBox="0 0 24 24" fill="#29f"><path d="M18.32,4.26C16.84,3.05,15.01,2.25,13,2.05v2.02c1.46,0.18,2.79,0.76,3.9,1.62L18.32,4.26z M19.93,11h2.02 c-0.2-2.01-1-3.84-2.21-5.32L18.31,7.1C19.17,8.21,19.75,9.54,19.93,11z M18.31,16.9l1.43,1.43c1.21-1.48,2.01-3.32,2.21-5.32 h-2.02C19.75,14.46,19.17,15.79,18.31,16.9z M13,19.93v2.02c2.01-0.2,3.84-1,5.32-2.21l-1.43-1.43 C15.79,19.17,14.46,19.75,13,19.93z M15.59,10.59L13,13.17V7h-2v6.17l-2.59-2.59L7,12l5,5l5-5L15.59,10.59z M11,19.93v2.02 c-5.05-0.5-9-4.76-9-9.95s3.95-9.45,9-9.95v2.02C7.05,4.56,4,7.92,4,12S7.05,19.44,11,19.93z"/></svg>`, Processing: `<svg width="18" height="18" viewBox="0 0 24 24" fill="#ddd"><path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z"><animateTransform attributeName="transform" attributeType="XML" type="rotate" from="360 12 12" to="0 12 12" dur="3s" repeatCount="indefinite"/></path></svg>`, Warning: `<svg width="18" height="18" viewBox="0 0 24 24" fill="#fbd935"><path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/></svg>`, DoneBig: `<svg width="24" height="24" viewBox="0 0 24 24" fill="#3f3"><path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z"/></svg>`, ErrorBig: `<svg width="24" height="24" viewBox="0 0 24 24" fill="#f22"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"/></svg>` }; export default class UI { private _styleElement: HTMLStyleElement; private _settingsButton: HTMLButtonElement; private _conn: Connection; private _bodyObs: MutationObserver; private _ctxMenuHooks: ContextMenuItemFactory[] = []; constructor(conn: Connection) { this._conn = conn; this._styleElement = document.createElement("style"); this._styleElement.innerHTML = MergedStyles; this._bodyObs = new MutationObserver(this.onDocBodyChanged.bind(this)); this._bodyObs.observe(document.body, { childList: true }); } install() { document.head.appendChild(this._styleElement); this._settingsButton = UIC.addTopbarButton( "Soggfy", //TODO: design a icon for this //https://fonts.google.com/icons?selected=Material+Icons:settings&icon.query=down `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="currentColor"><path d="M18,15v3H6v-3H4v3c0,1.1,0.9,2,2,2h12c1.1,0,2-0.9,2-2v-3H18z M17,11l-1.41-1.41L13,12.17V4h-2v8.17L8.41,9.59L7,11l5,5 L17,11z"></path></svg>`, () => document.body.append(this.createSettingsDialog()) ); this.addContextMenuHook(menuList => { for (let item of menuList.children) { let props = Utils.getReactProps(menuList, item); let isTarget = props && ( (props.contextUri && props.highlightedUri) || //Track: Show credits (props.uri && props.hasOwnProperty("onRemoveCallback")) || //Album: Add/remove to library (props.uri && props.isPublished != null) //Playlist: Add/remove to profile ); if (isTarget) { let uri = props.contextUri ?? props.uri; return { text: "Export M3U", location: item as HTMLLIElement, locationOffset: "beforebegin", onClick: () => this.createM3U(uri) }; } } }); } setEnabled(enabled: boolean) { this._settingsButton.disabled = !enabled; } private async createM3U(uri: string) { let info = await Resources.getTracks(uri); let tracks = info.tracks; let saveResult = await this._conn.request(MessageType.OPEN_FILE_PICKER, { type: 2 /* SAVE_FILE */, initialPath: config.savePaths.basePath + `/${PathTemplate.escapePath(info.name)}.m3u8`, fileTypes: [ "M3U Playlist|*.m3u8" ] }, null, -1); let savePath = saveResult.payload.path; if (!saveResult.payload.success) return; let tree = new TemplatedSearchTree(config.savePaths.track); for (let track of tracks) { tree.add(track.uri, track.vars); } let data = await this._conn.request(MessageType.DOWNLOAD_STATUS, { searchTree: tree.root, basePath: config.savePaths.basePath }, null, -1); let results = data.payload.results; let plData = `#EXTM3U\n#PLAYLIST:${info.name}\n\n`; let numExported = 0; for (let track of tracks) { let loc = results[track.uri]; if (!loc) continue; plData += `#EXTINF:${(track.durationMs / 1000).toFixed(0)},${track.vars.artist_name} - ${track.vars.track_name}\n`; plData += `${loc.path}\n\n`; numExported++; } this._conn.send(MessageType.WRITE_FILE, { path: savePath, mode: "replace", text: plData }); this.showNotification(Icons.DoneBig, `Exported ${numExported} tracks`); } private createSettingsDialog() { //TODO: refactor (+ react port?) let onChange = this.configAccessor.bind(this); let speedSlider = UIC.slider( "playbackSpeed", { min: 1, max: 20, step: 1, formatter: val => val + "x" }, (key, newValue) => { if (newValue) { SpotifyUtils.resetCurrentTrack(false); } return onChange(key, newValue); } ); let defaultFormats = { "Original OGG": { ext: "", args: "-c copy" }, "MP3 320K": { ext: "mp3", args: "-c:a libmp3lame -b:a 320k -id3v2_version 3 -c:v copy" }, "MP3 256K": { ext: "mp3", args: "-c:a libmp3lame -b:a 256k -id3v2_version 3 -c:v copy" }, "MP3 192K": { ext: "mp3", args: "-c:a libmp3lame -b:a 192k -id3v2_version 3 -c:v copy" }, "M4A 256K (AAC)": { ext: "m4a", args: "-c:a aac -b:a 256k -disposition:v attached_pic -c:v copy" }, //TODO: aac quality disclaimer / libfdk "M4A 192K (AAC)": { ext: "m4a", args: "-c:a aac -b:a 192k -disposition:v attached_pic -c:v copy" }, "Opus 160K": { ext: "opus",args: "-c:a libopus -b:a 160k" }, "Custom": { ext: "mp3", args: "-c:a libmp3lame -b:a 320k -id3v2_version 3 -c:v copy" }, }; let extensions = { "MP3": "mp3", "M4A": "m4a", "MP4": "mp4", "OGG": "ogg", "Opus": "opus" }; let customFormatSection = UIC.subSection( UIC.rows("FFmpeg arguments", UIC.textInput("outputFormat.args", onChange)), //TODO: allow this to be editable UIC.row("Extension", UIC.select("outputFormat.ext", extensions, onChange)) ); customFormatSection.style.display = "none"; let onFormatChange = (key: string, name?: string) => { if (name === undefined) { let currFormat = config.outputFormat; let preset = Object.entries(defaultFormats) .find(v => v[1].args === currFormat.args && v[1].ext === currFormat.ext); name = preset?.[0] ?? "Custom"; } else { onChange("outputFormat", defaultFormats[name]); } customFormatSection.style.display = name === "Custom" ? "block" : "none"; return name; }; let basePathTextInput = UIC.textInput("savePaths.basePath", onChange); let browseBasePath = async () => { let resp = await this._conn.request(MessageType.OPEN_FILE_PICKER, { type: 3 /* SELECT_FOLDER */, initialPath: config.savePaths.basePath }, null, -1); basePathTextInput.value = resp.payload.path; onChange("savePaths.basePath", resp.payload.path); }; let pathVarTags = []; for (let pv of PathTemplate.Vars) { let name = `{${pv.name}}`; let tag = UIC.tagButton(name, () => { Platform.getClipboardAPI().copy(name); UIC.notification("Copied", tag, "up", true, 1); }); tag.title = pv.desc; pathVarTags.push(tag); } let canvasPathTxt = UIC.rows("Canvas template", UIC.textInput("savePaths.canvas", onChange)); let invalidCharModes = { "Unicodes": "unicode", "Dashes (-)": "-", "Underlines (_)": "_", "None (remove)": "" }; return UIC.createSettingOverlay( UIC.section("General", UIC.row("Playback speed", speedSlider), UIC.row("Output format", UIC.select("outputFormat", Object.getOwnPropertyNames(defaultFormats), onFormatChange)), customFormatSection, UIC.row("Skip downloaded tracks", UIC.toggle("skipDownloadedTracks", onChange)), UIC.row("Embed cover art", UIC.toggle("embedCoverArt", onChange)), UIC.row("Save cover art in album folder", UIC.toggle("saveCoverArt", onChange)), UIC.row("Embed lyrics", UIC.toggle("embedLyrics", onChange)), UIC.row("Save lyrics as .lrc/.txt", UIC.toggle("saveLyrics", onChange)), UIC.row("Save canvas", UIC.toggle("saveCanvas", (k, v) => { v = onChange(k, v); canvasPathTxt.style.display = v ? "block" : "none"; return v; })) ), UIC.section("Paths", UIC.rows("Base path", UIC.colSection(basePathTextInput, UIC.button(null, Icons.Folder, browseBasePath))), UIC.rows("Track template", UIC.textInput("savePaths.track", onChange)), UIC.rows("Podcast template", UIC.textInput("savePaths.episode", onChange)), canvasPathTxt, UIC.row("Replace invalid characters with", UIC.select("savePaths.invalidCharRepl", invalidCharModes, onChange)), UIC.rows(UIC.collapsible("Variables", ...pathVarTags)) ), UIC.section("Misc", UIC.row("Block telemetry", UIC.toggle("blockAds", onChange)), ) ); } public showNotification(icon: string, text: string) { let anchor = document.querySelector(".Root__now-playing-bar"); let node = UIC.parse(` <div class="sgf-notification-wrapper"> ${icon} <span>${text}</span> </div>`); UIC.notification(node, anchor, "up", false, 3); } private onDocBodyChanged(records: MutationRecord[]) { for (let record of records) { for (let node of record.addedNodes) { let elem = node as HTMLElement; if (!elem.querySelector("#context-menu")) continue; if (elem.querySelector("ul")) { this.onContextMenuOpened(elem); } else { //the ... popup has a delay before being populated let obs = new MutationObserver(() => { if (elem.querySelector("ul")) { this.onContextMenuOpened(elem); } obs.disconnect(); }); obs.observe(elem, { childList: true, subtree: true }); } } } } public addContextMenuHook(itemFactory: ContextMenuItemFactory) { this._ctxMenuHooks.push(itemFactory); } private onContextMenuOpened(popdiv: HTMLElement) { let list = popdiv.querySelector("ul"); for (let factory of this._ctxMenuHooks) { let desc = factory(list); if (!desc) continue; let itemTemplate = list.querySelector("li button[aria-disabled='false'] span").parentElement.parentElement; let item = itemTemplate.cloneNode(true) as HTMLLIElement; item.querySelector("span").innerText = desc.text; item.querySelector("button").onclick = () => { desc.onClick(); popdiv["_tippy"]?.props?.onClickOutside(); //based on Spicetify code }; if (!list.contains(desc.location)) throw Error("Location must be inside list"); desc.location.insertAdjacentElement(desc.locationOffset ?? "afterend", item); } } private configAccessor(key: string, newValue?: any) { let finalValue = Utils.accessObjectPath(config, key.split('.'), newValue); if (newValue !== undefined) { let delta = {}; let field = key.split('.')[0]; //sync only supports topmost field delta[field] = config[field]; this._conn.send(MessageType.SYNC_CONFIG, delta); } return finalValue; } } type ContextMenuItemFactory = (menuList: HTMLUListElement) => ContextMenuItemDesc | null; interface ContextMenuItemDesc { text: string; location?: HTMLLIElement; locationOffset?: "beforebegin" | "afterend"; onClick: () => void; } /** * Extracts the specified CSS selectors from xpui.js. * Note: This function is expansive and results should be cached. */ async function extractSelectors(...names: string[]) { let pattern = `(${names.join('|')}):\\s*"(.+?)"`; let regex = new RegExp(pattern, "g"); let results: any = {}; let req = await fetch("/xpui.js"); let js = await req.text(); let match: RegExpExecArray; while (match = regex.exec(js)) { let key = match[1]; let val = match[2]; results[key] = "." + val; } return results; } let selectors = await extractSelectors( "trackListRow", "rowTitle", "rowSubTitle", "rowSectionEnd", "rowMoreButton" ); export { selectors as Selectors }
the_stack
import { Orbit } from '@orbit/core'; import { serializeRecordIdentity, deserializeRecordIdentity, InitializedRecord, RecordIdentity, RecordQueryBuilder, RecordTransformBuilder } from '@orbit/records'; import { RecordRelationshipIdentity, AsyncRecordCache, AsyncRecordCacheSettings, RecordCacheQueryOptions, RecordCacheTransformOptions, RecordCacheUpdateDetails, RecordTransformBuffer, SimpleRecordTransformBuffer } from '@orbit/record-cache'; import { supportsIndexedDB } from './lib/indexeddb'; import { RequestOptions } from '@orbit/data'; const { assert } = Orbit; const INVERSE_RELS = '__inverseRels__'; const DB_NOT_OPEN = 'IndexedDB database is not yet open'; interface InverseRelationshipForIDB { id: string; recordIdentity: string; relationship: string; relatedIdentity: string; type: string; relatedType: string; } export interface IndexedDBCacheSettings< QO extends RequestOptions = RecordCacheQueryOptions, TO extends RequestOptions = RecordCacheTransformOptions, QB = RecordQueryBuilder, TB = RecordTransformBuilder > extends AsyncRecordCacheSettings<QO, TO, QB, TB> { namespace?: string; } export interface IndexedDBCacheClass< QO extends RequestOptions = RecordCacheQueryOptions, TO extends RequestOptions = RecordCacheTransformOptions, QB = RecordQueryBuilder, TB = RecordTransformBuilder, QRD = unknown, TRD extends RecordCacheUpdateDetails = RecordCacheUpdateDetails > { new (settings: IndexedDBCacheSettings<QO, TO, QB, TB>): IndexedDBCache< QO, TO, QB, TB, QRD, TRD >; } /** * A cache used to access records in an IndexedDB database. * * Because IndexedDB access is async, this cache extends `AsyncRecordCache`. */ export class IndexedDBCache< QO extends RequestOptions = RecordCacheQueryOptions, TO extends RequestOptions = RecordCacheTransformOptions, QB = RecordQueryBuilder, TB = RecordTransformBuilder, QRD = unknown, TRD extends RecordCacheUpdateDetails = RecordCacheUpdateDetails > extends AsyncRecordCache<QO, TO, QB, TB, QRD, TRD> { protected _namespace: string; protected _db?: IDBDatabase; protected _openingDB?: Promise<IDBDatabase>; constructor(settings: IndexedDBCacheSettings<QO, TO, QB, TB>) { assert('Your browser does not support IndexedDB!', supportsIndexedDB()); super(settings); this._namespace = settings.namespace || 'orbit'; } get namespace(): string { return this._namespace; } async upgrade(): Promise<void> { await this.reopenDB(); for (let processor of this._processors) { await processor.upgrade(); } } async reset(): Promise<void> { await this.deleteDB(); for (let processor of this._processors) { await processor.reset(); } } /** * The version to specify when opening the IndexedDB database. */ get dbVersion(): number { return this._schema.version; } /** * IndexedDB database name. * * Defaults to the namespace of the app, which can be overridden in the constructor. */ get dbName(): string { return this._namespace; } get isDBOpen(): boolean { return !!this._db; } openDB(): Promise<IDBDatabase> { return (this._openingDB = new Promise((resolve, reject) => { if (this._db) { resolve(this._db); } else { let request = Orbit.globals.indexedDB.open(this.dbName, this.dbVersion); request.onsuccess = () => { const db = (this._db = request.result); resolve(db); }; request.onerror = () => { reject(request.error); }; request.onupgradeneeded = (event: any) => { // console.log('indexedDB upgrade needed'); const db = (this._db = event.target.result); if (event && event.oldVersion > 0) { this.migrateDB(db, event); } else { this.createDB(db); } }; } })); } async closeDB(): Promise<void> { if (this.isDBOpen) { // Finish opening DB before closing it to avoid problems if (this._openingDB) { await this._openingDB; this._openingDB = undefined; } if (this._db) { this._db.close(); this._db = undefined; } } } async reopenDB(): Promise<IDBDatabase> { await this.closeDB(); return this.openDB(); } /** * Initializes the contents of the database. * * Idempotently register models which do not yet have corresponding object * stores. Also, creates an object store for tracking inverse relationships, * if it is missing. * * Override this method and/or `registerModel` to provide more advanced * db initialization. */ createDB(db: IDBDatabase): void { const objectStoreNames = db.objectStoreNames; Object.keys(this.schema.models).forEach((model) => { if (!objectStoreNames.contains(model)) { this.registerModel(db, model); } }); if (!objectStoreNames.contains(INVERSE_RELS)) { this.createInverseRelationshipStore(db); } } createInverseRelationshipStore(db: IDBDatabase): void { let objectStore = db.createObjectStore(INVERSE_RELS, { keyPath: 'id' }); objectStore.createIndex('recordIdentity', 'recordIdentity', { unique: false }); objectStore.createIndex('relatedIdentity', 'relatedIdentity', { unique: false }); } /** * Migrates the database to align with an updated schema. * * By default, this will attempt a naive migration by invoking `createDB`, * which idempotently creates object stores as needed. * * Override this method to provide more sophisticated migrations. */ migrateDB(db: IDBDatabase, event: IDBVersionChangeEvent): void { if (Orbit.debug) { console.log( `IndexedDBCache#migrateDB - upgrading ${event.oldVersion} -> ${event.newVersion}` ); } // Attempt naive migration, creating object stores as needed. this.createDB(db); } async deleteDB(): Promise<void> { await this.closeDB(); return new Promise((resolve, reject) => { let request = Orbit.globals.indexedDB.deleteDatabase(this.dbName); request.onsuccess = () => { resolve(); }; request.onerror = () => { reject(request.error); }; }); } createTransaction( storeNames: string[], mode?: IDBTransactionMode ): IDBTransaction { if (!this._db) throw new Error(DB_NOT_OPEN); return this._db.transaction(storeNames, mode); } registerModel(db: IDBDatabase, type: string): void { db.createObjectStore(type, { keyPath: 'id' }); // TODO - override and create appropriate indices } clearRecords(type: string): Promise<void> { return new Promise((resolve, reject) => { const transaction = this.createTransaction([type], 'readwrite'); const objectStore = transaction.objectStore(type); const request = objectStore.clear(); request.onsuccess = () => { resolve(); }; request.onerror = () => { reject(request.error); }; }); } getRecordAsync( record: RecordIdentity ): Promise<InitializedRecord | undefined> { return new Promise((resolve, reject) => { const transaction = this.createTransaction([record.type]); const objectStore = transaction.objectStore(record.type); const request = objectStore.get(record.id); request.onsuccess = () => { let result = request.result; if (result) { if (this._keyMap) this._keyMap.pushRecord(result); resolve(result); } else { resolve(undefined); } }; request.onerror = () => { reject(request.error); }; }); } getRecordsAsync( typeOrIdentities?: string | RecordIdentity[] ): Promise<InitializedRecord[]> { if (typeOrIdentities === undefined) { return this._getAllRecords(); } else if (typeof typeOrIdentities === 'string') { const type: string = typeOrIdentities; return new Promise((resolve, reject) => { const transaction = this.createTransaction([type]); const objectStore = transaction.objectStore(type); const records: InitializedRecord[] = []; const request = objectStore.openCursor(); request.onsuccess = (event: any) => { const cursor = event.target.result; if (cursor) { let record = cursor.value; if (this._keyMap) this._keyMap.pushRecord(record); records.push(record); cursor.continue(); } else { resolve(records); } }; request.onerror = () => { reject(request.error); }; }); } else { const identities: RecordIdentity[] = typeOrIdentities; const records: InitializedRecord[] = []; if (identities.length > 0) { const types: string[] = []; for (let identity of identities) { if (!types.includes(identity.type)) { types.push(identity.type); } } const transaction = this.createTransaction(types); return new Promise((resolve, reject) => { const len = identities.length; const last = len - 1; for (let i = 0; i < len; i++) { const identity = identities[i]; const objectStore = transaction.objectStore(identity.type); const request = objectStore.get(identity.id); request.onsuccess = () => { const record = request.result; if (record) { if (this._keyMap) this._keyMap.pushRecord(record); records.push(record); } if (i === last) resolve(records); }; request.onerror = () => reject(request.error); } }); } else { return Promise.resolve(records); } } } setRecordAsync(record: InitializedRecord): Promise<void> { const transaction = this.createTransaction([record.type], 'readwrite'); const objectStore = transaction.objectStore(record.type); return new Promise((resolve, reject) => { const request = objectStore.put(record); request.onsuccess = () => { if (this._keyMap) this._keyMap.pushRecord(record); resolve(); }; request.onerror = () => reject(request.error); }); } setRecordsAsync(records: InitializedRecord[]): Promise<void> { if (records.length > 0) { const types: string[] = []; for (let record of records) { if (!types.includes(record.type)) { types.push(record.type); } } const transaction = this.createTransaction(types, 'readwrite'); return new Promise((resolve, reject) => { const len = records.length; const last = len - 1; for (let i = 0; i < len; i++) { const record = records[i]; const objectStore = transaction.objectStore(record.type); const request = objectStore.put(record); if (i === last) { request.onsuccess = () => { if (this._keyMap) { records.forEach((record) => this._keyMap?.pushRecord(record)); } resolve(); }; } request.onerror = () => reject(request.error); } }); } else { return Promise.resolve(); } } removeRecordAsync( recordIdentity: RecordIdentity ): Promise<InitializedRecord | undefined> { return new Promise((resolve, reject) => { const transaction = this.createTransaction( [recordIdentity.type], 'readwrite' ); const objectStore = transaction.objectStore(recordIdentity.type); const request = objectStore.delete(recordIdentity.id); request.onsuccess = () => resolve(undefined); request.onerror = () => reject(request.error); }); } removeRecordsAsync(records: RecordIdentity[]): Promise<InitializedRecord[]> { if (records.length > 0) { const types: string[] = []; for (let record of records) { if (!types.includes(record.type)) { types.push(record.type); } } const transaction = this.createTransaction(types, 'readwrite'); return new Promise((resolve, reject) => { const len = records.length; const last = len - 1; for (let i = 0; i < len; i++) { const record = records[i]; const objectStore = transaction.objectStore(record.type); const request = objectStore.delete(record.id); if (i === last) { request.onsuccess = () => resolve(records); } request.onerror = () => reject(request.error); } }); } else { return Promise.resolve([]); } } getInverseRelationshipsAsync( recordIdentityOrIdentities: RecordIdentity | RecordIdentity[] ): Promise<RecordRelationshipIdentity[]> { // console.log('getInverseRelationshipsAsync', recordIdentityOrIdentities); return new Promise((resolve, reject) => { const transaction = this.createTransaction([INVERSE_RELS]); const objectStore = transaction.objectStore(INVERSE_RELS); const results: RecordRelationshipIdentity[] = []; let index; try { index = objectStore.index('relatedIdentity'); } catch (e) { console.error( `[@orbit/indexeddb] The 'relatedIdentity' index is missing from the ${INVERSE_RELS} object store in IndexedDB. ` + 'Please add this index using a DB migration as described in https://github.com/orbitjs/orbit/pull/823' ); resolve([]); return; } const identities: RecordIdentity[] = Array.isArray( recordIdentityOrIdentities ) ? recordIdentityOrIdentities : [recordIdentityOrIdentities]; const len = identities.length; let completed = 0; for (let i = 0; i < len; i++) { const identity = identities[i]; const keyRange = Orbit.globals.IDBKeyRange.only( serializeRecordIdentity(identity) ); const request = index.openCursor(keyRange); request.onsuccess = (event: any) => { const cursor = event.target.result; if (cursor) { let result = this._fromInverseRelationshipForIDB(cursor.value); results.push(result); cursor.continue(); } else { completed += 1; if (completed === len) { resolve(results); } } }; request.onerror = () => reject(request.error); } }); } addInverseRelationshipsAsync( relationships: RecordRelationshipIdentity[] ): Promise<void> { // console.log('addInverseRelationshipsAsync', relationships); if (relationships.length > 0) { const transaction = this.createTransaction([INVERSE_RELS], 'readwrite'); const objectStore = transaction.objectStore(INVERSE_RELS); return new Promise((resolve, reject) => { const len = relationships.length; const last = len - 1; for (let i = 0; i < len; i++) { const relationship = relationships[i]; const ir = this._toInverseRelationshipForIDB(relationship); const request = objectStore.put(ir); if (i === last) { request.onsuccess = () => resolve(); } request.onerror = () => reject(request.error); } }); } else { return Promise.resolve(); } } removeInverseRelationshipsAsync( relationships: RecordRelationshipIdentity[] ): Promise<void> { // console.log('removeInverseRelationshipsAsync', relationships); if (relationships.length > 0) { const transaction = this.createTransaction([INVERSE_RELS], 'readwrite'); const objectStore = transaction.objectStore(INVERSE_RELS); return new Promise((resolve, reject) => { const len = relationships.length; const last = len - 1; for (let i = 0; i < len; i++) { const relationship = relationships[i]; const id = this._serializeInverseRelationshipIdentity(relationship); const request = objectStore.delete(id); if (i === last) { request.onsuccess = () => resolve(); } request.onerror = () => reject(request.error); } }); } else { return Promise.resolve(); } } ///////////////////////////////////////////////////////////////////////////// // Protected methods ///////////////////////////////////////////////////////////////////////////// /** * Override `_getTransformBuffer` on base `AsyncRecordCache` to provide a * `transformBuffer` if a custom one hasn't been provided via the constructor * setting. */ protected _getTransformBuffer(): RecordTransformBuffer { if (this._transformBuffer === undefined) { const { schema, keyMap } = this; this._transformBuffer = new SimpleRecordTransformBuffer({ schema, keyMap }); } return this._transformBuffer; } protected async _getAllRecords(): Promise<InitializedRecord[]> { const types = Object.keys(this.schema.models); const recordsets = await Promise.all( types.map((type) => this.getRecordsAsync(type)) ); const allRecords: InitializedRecord[] = []; recordsets.forEach((records) => Array.prototype.push.apply(allRecords, records) ); return allRecords; } protected _serializeInverseRelationshipIdentity( ri: RecordRelationshipIdentity ): string { return [ serializeRecordIdentity(ri.record), ri.relationship, serializeRecordIdentity(ri.relatedRecord) ].join('::'); } protected _toInverseRelationshipForIDB( ri: RecordRelationshipIdentity ): InverseRelationshipForIDB { return { id: this._serializeInverseRelationshipIdentity(ri), recordIdentity: serializeRecordIdentity(ri.record), relationship: ri.relationship, relatedIdentity: serializeRecordIdentity(ri.relatedRecord), type: ri.record.type, relatedType: ri.relatedRecord.type }; } protected _fromInverseRelationshipForIDB( ir: InverseRelationshipForIDB ): RecordRelationshipIdentity { return { record: deserializeRecordIdentity(ir.recordIdentity), relatedRecord: deserializeRecordIdentity(ir.relatedIdentity), relationship: ir.relationship }; } }
the_stack
* @module Item */ import classnames from "classnames"; import * as React from "react"; import { Logger } from "@itwin/core-bentley"; import { BadgeType, ConditionalStringValue, OnItemExecutedFunc, SpecialKey, StringGetter, UiSyncEventArgs } from "@itwin/appui-abstract"; import { BadgeUtilities, CommonProps, Icon, IconSpec, SizeProps, withOnOutsideClick } from "@itwin/core-react"; import { Direction, ExpandableItem, GroupColumn, GroupTool, GroupToolExpander, Item, NestedGroup as NestedToolGroupComponent, ToolbarDirectionContext, Group as ToolGroupComponent, withDragInteraction, } from "@itwin/appui-layout-react"; import { ToolGroupPanelContext } from "../frontstage/FrontstageComposer"; import { FrontstageManager, ToolActivatedEventArgs } from "../frontstage/FrontstageManager"; import { KeyboardShortcutManager } from "../keyboardshortcut/KeyboardShortcut"; import { ActionButtonItemDef } from "../shared/ActionButtonItemDef"; import { AnyItemDef } from "../shared/AnyItemDef"; import { GroupItemProps } from "../shared/GroupItemProps"; import { BaseItemState, ItemDefBase } from "../shared/ItemDefBase"; import { ItemList, ItemMap } from "../shared/ItemMap"; import { SyncUiEventDispatcher } from "../syncui/SyncUiEventDispatcher"; import { UiFramework } from "../UiFramework"; import { PropsHelper } from "../utils/PropsHelper"; import { ToolbarDragInteractionContext } from "./DragInteraction"; // eslint-disable-next-line @typescript-eslint/naming-convention, deprecation/deprecation const ToolGroup = withOnOutsideClick(ToolGroupComponent, undefined, false); // eslint-disable-next-line @typescript-eslint/naming-convention, deprecation/deprecation const NestedToolGroup = withOnOutsideClick(NestedToolGroupComponent, undefined, false); // eslint-disable-next-line @typescript-eslint/naming-convention, deprecation/deprecation const ItemWithDragInteraction = withDragInteraction(Item); // ----------------------------------------------------------------------------- // GroupItemDef class // ----------------------------------------------------------------------------- /** An Item that opens a group of items. * @public */ export class GroupItemDef extends ActionButtonItemDef { private static _sId = 0; public static groupIdPrefix = "Group-"; public groupId: string; public direction: Direction; // eslint-disable-line deprecation/deprecation public itemsInColumn: number; public items: AnyItemDef[]; public directionExplicit: boolean; public defaultActiveItemId?: string; /** @internal */ public overflow: boolean = false; private _itemList!: ItemList; private _itemMap!: ItemMap; private _panelLabel: string | StringGetter | ConditionalStringValue = ""; constructor(groupItemProps: GroupItemProps, onItemExecuted?: OnItemExecutedFunc) { super(groupItemProps, onItemExecuted); this.groupId = (groupItemProps.groupId !== undefined) ? groupItemProps.groupId : ""; if (groupItemProps.groupId) this.groupId = groupItemProps.groupId; else { GroupItemDef._sId++; this.groupId = GroupItemDef.groupIdPrefix + GroupItemDef._sId; } this.directionExplicit = (groupItemProps.direction !== undefined); this.direction = (groupItemProps.direction !== undefined) ? groupItemProps.direction : Direction.Bottom; // eslint-disable-line deprecation/deprecation this.itemsInColumn = (groupItemProps.itemsInColumn !== undefined) ? groupItemProps.itemsInColumn : 7; this._panelLabel = PropsHelper.getStringSpec(groupItemProps.panelLabel, groupItemProps.panelLabelKey); // eslint-disable-line deprecation/deprecation this.items = groupItemProps.items; this.defaultActiveItemId = groupItemProps.defaultActiveItemId; } public get id(): string { return this.groupId; } /** Get the panelLabel string */ public get panelLabel(): string { return PropsHelper.getStringFromSpec(this._panelLabel); } /** Set the panelLabel. * @param v A string or a function to get the string. */ public setPanelLabel(v: string | StringGetter | ConditionalStringValue) { this._panelLabel = v; } public resolveItems(force?: boolean): void { if (this._itemList && !force) return; this._itemList = new ItemList(); this._itemMap = new ItemMap(); this.items.map((item: AnyItemDef) => { const id: string = item.id; this._itemList.addItem(item); this._itemMap.set(id, item); }); } public getItemById(id: string): ItemDefBase | undefined { return this._itemMap.get(id); } public getItemByIndex(index: number): ItemDefBase | undefined { return this._itemList.items[index]; } public get itemCount(): number { return this._itemList.items.length; } public override execute(): void { } public override toolbarReactNode(index?: number): React.ReactNode { this.resolveItems(); const key = this.getKey(index); return ( <GroupItem groupItemDef={this} key={key} onSizeKnown={this.handleSizeKnown} /> ); } } // ----------------------------------------------------------------------------- // GroupItem component, props & state // ----------------------------------------------------------------------------- interface ToolGroupItem { iconSpec?: IconSpec; label: string; trayId?: string; badgeType?: BadgeType; } interface ToolGroupTray { title: string; items: Map<string, ToolGroupItem>; groupItemDef: GroupItemDef; } type ToolGroupTrayMap = Map<string, ToolGroupTray>; interface GroupItemComponentProps extends CommonProps { groupItemDef: GroupItemDef; onSizeKnown?: (size: SizeProps) => void; } interface GroupItemState extends BaseItemState { activeItemId: string; // One of group items id. activeToolId: string; // FrontstageManager.activeToolId groupItemDef: GroupItemDef; trayId: string; backTrays: ReadonlyArray<string>; trays: ToolGroupTrayMap; } /** Group Item React component. * @internal */ export class GroupItem extends React.Component<GroupItemComponentProps, GroupItemState> { /** @internal */ public override readonly state: Readonly<GroupItemState>; private _componentUnmounting = false; private _childSyncIds?: Set<string>; private _childRefreshRequired = false; private _trayIndex = 0; private _closeOnPanelOpened = true; private _ref = React.createRef<HTMLDivElement>(); constructor(props: GroupItemComponentProps) { super(props); this._loadChildSyncIds(props); const state = this.getGroupItemState(this.props); const activeItemId = this.props.groupItemDef.defaultActiveItemId !== undefined ? this.props.groupItemDef.defaultActiveItemId : getFirstItemId(this.props.groupItemDef); this.state = { ...state, activeItemId, }; } private _loadChildSyncIds(props: GroupItemComponentProps) { // istanbul ignore else if (props.groupItemDef && props.groupItemDef.items.length > 0) { props.groupItemDef.items.forEach((itemDef: AnyItemDef) => { const item: ItemDefBase | undefined = itemDef; if (item.stateSyncIds.length > 0) { // eslint-disable-line deprecation/deprecation if (undefined === this._childSyncIds) this._childSyncIds = new Set<string>(); item.stateSyncIds.forEach((value) => this._childSyncIds!.add(value)); // eslint-disable-line deprecation/deprecation } }); } } private _handleSyncUiEvent = (args: UiSyncEventArgs): void => { // istanbul ignore next if (this._componentUnmounting) return; let refreshState = false; // istanbul ignore else if (this._childSyncIds && this._childSyncIds.size > 0) if ([...this._childSyncIds].some((value: string): boolean => args.eventIds.has(value.toLowerCase()))) this._childRefreshRequired = true; // this is cleared when render occurs let newState: GroupItemState = { ...this.state }; if (this.props.groupItemDef.stateSyncIds && this.props.groupItemDef.stateSyncIds.length > 0) // eslint-disable-line deprecation/deprecation refreshState = this.props.groupItemDef.stateSyncIds.some((value: string): boolean => args.eventIds.has(value.toLowerCase())); // eslint-disable-line deprecation/deprecation if (refreshState || this._childRefreshRequired) { if (this.props.groupItemDef.stateFunc) // eslint-disable-line deprecation/deprecation newState = this.props.groupItemDef.stateFunc(newState) as GroupItemState; // eslint-disable-line deprecation/deprecation // istanbul ignore else if ((this.state.isActive !== newState.isActive) || (this.state.isEnabled !== newState.isEnabled) || (this.state.isVisible !== newState.isVisible) || this._childRefreshRequired) { this.setState({ isActive: newState.isActive, isEnabled: newState.isEnabled, isVisible: newState.isVisible, isPressed: newState.isPressed }); } } }; public override componentDidMount() { SyncUiEventDispatcher.onSyncUiEvent.addListener(this._handleSyncUiEvent); FrontstageManager.onToolActivatedEvent.addListener(this._handleToolActivatedEvent); FrontstageManager.onToolPanelOpenedEvent.addListener(this._handleToolPanelOpenedEvent); } public override componentWillUnmount() { this._componentUnmounting = true; SyncUiEventDispatcher.onSyncUiEvent.removeListener(this._handleSyncUiEvent); FrontstageManager.onToolActivatedEvent.removeListener(this._handleToolActivatedEvent); FrontstageManager.onToolPanelOpenedEvent.removeListener(this._handleToolPanelOpenedEvent); } public override shouldComponentUpdate(nextProps: GroupItemComponentProps, nextState: GroupItemState) { if (!PropsHelper.isShallowEqual(nextState, this.state)) return true; if (!PropsHelper.isShallowEqual(nextProps, this.props)) return true; // istanbul ignore else if (this._childRefreshRequired) { this._childRefreshRequired = false; return true; } // istanbul ignore next return false; } private getGroupItemState(props: GroupItemComponentProps) { const groupItemDef = props.groupItemDef; // Separate into trays const trays = new Map<string, ToolGroupTray>(); const trayId = this.resetTrayId(); this.processGroupItemDef(groupItemDef, trayId, trays); return { activeToolId: FrontstageManager.activeToolId, groupItemDef, isEnabled: groupItemDef.isEnabled, // eslint-disable-line deprecation/deprecation isPressed: groupItemDef.isPressed, isVisible: groupItemDef.isVisible, // eslint-disable-line deprecation/deprecation trayId, backTrays: [], trays, }; } private resetTrayId(): string { this._trayIndex = 1; return `tray-${this._trayIndex}`; } private generateTrayId(): string { return `tray-${this._trayIndex}`; } private processGroupItemDef(groupItemDef: GroupItemDef, trayId: string, trays: ToolGroupTrayMap): void { // Separate into column items const items = new Map<string, ToolGroupItem>(); for (let itemIndex = 0; itemIndex < groupItemDef.itemCount; itemIndex++) { const item = groupItemDef.getItemByIndex(itemIndex)!; if (item instanceof GroupItemDef) { item.resolveItems(); this._trayIndex++; const itemTrayId = this.generateTrayId(); const groupItem: ToolGroupItem = { iconSpec: item.iconSpec, label: item.label, trayId: itemTrayId, badgeType: item.badgeType, }; items.set(item.id, groupItem); this.processGroupItemDef(item, itemTrayId, trays); } else { items.set(item.id, item); } } trays.set(trayId, { items, title: groupItemDef.panelLabel ? groupItemDef.panelLabel : groupItemDef.tooltip, // we fallback to use tooltip since tooltip was originally (and confusingly) used as a panelLabel groupItemDef, }); } public override componentDidUpdate(prevProps: GroupItemComponentProps, _prevState: GroupItemState) { if (this.props !== prevProps) { // istanbul ignore next if (this.props.groupItemDef !== prevProps.groupItemDef) Logger.logTrace(UiFramework.loggerCategory(this), `Different GroupItemDef for same groupId of ${this.state.groupItemDef.groupId}`); this.setState((_, props) => this.getGroupItemState(props)); } } private get _tray() { const tray = this.state.trays.get(this.state.trayId); // istanbul ignore next if (!tray) throw new RangeError(); return tray; } private getTray(trayId: string) { const tray = this.state.trays.get(trayId); // istanbul ignore next if (!tray) throw new RangeError(); return tray; } private _handleKeyDown = (e: React.KeyboardEvent): void => { // istanbul ignore else if (e.key === SpecialKey.Escape) { this.closeGroupButton(); KeyboardShortcutManager.setFocusToHome(); } }; public override render(): React.ReactNode { if (!this.state.isVisible) return null; const activeItem = this.getItemById(this.state.activeItemId); if (!activeItem) return null; const { groupItemDef, className, ...props } = this.props; const classNames = classnames( className, groupItemDef.overflow && "nz-toolbar-item-overflow", ); const badge = BadgeUtilities.getComponentForBadgeType(groupItemDef.badgeType); return ( <ToolbarDirectionContext.Consumer> {(direction) => ( <ToolbarDragInteractionContext.Consumer> {(dragInteraction) => ( <ExpandableItem // eslint-disable-line deprecation/deprecation {...props} className={classNames} key={this.state.groupItemDef.id} panel={this.getGroupTray(dragInteraction)} > {dragInteraction ? ( <div ref={this._ref}> <ItemWithDragInteraction badge={badge} className={groupItemDef.overflow ? "nz-ellipsis-icon" : undefined} direction={direction} icon={<Icon iconSpec={groupItemDef.overflow ? "nz-ellipsis" : activeItem.iconSpec} />} isActive={groupItemDef.overflow ? false : this.state.activeToolId === this.state.activeItemId} isDisabled={!this.state.isEnabled} onClick={groupItemDef.overflow ? this._handleOverflowClick : this._handleDragInteractionClick} onKeyDown={this._handleKeyDown} onOpenPanel={this._handleOpenPanel} onSizeKnown={this.props.onSizeKnown} title={groupItemDef.overflow ? groupItemDef.label : activeItem.label} /> </div> ) : ( <div ref={this._ref}> <Item // eslint-disable-line deprecation/deprecation badge={badge} className={groupItemDef.overflow ? "nz-ellipsis-icon" : undefined} icon={<Icon iconSpec={groupItemDef.overflow ? "nz-ellipsis" : groupItemDef.iconSpec} />} isDisabled={!this.state.isEnabled} onClick={this._handleClick} onKeyDown={this._handleKeyDown} onSizeKnown={this.props.onSizeKnown} title={this.state.groupItemDef.label} /> </div> )} </ExpandableItem> )} </ToolbarDragInteractionContext.Consumer> )} </ToolbarDirectionContext.Consumer> ); } private _handleOpenPanel = () => { this.setState({ isPressed: true, }); this._closeOnPanelOpened = false; FrontstageManager.onToolPanelOpenedEvent.emit(); this._closeOnPanelOpened = true; }; private _handleClick = () => { this.setState((prevState) => ({ isPressed: !prevState.isPressed, })); }; private _handleDragInteractionClick = () => { const activeItem = this.getItemById(this.state.activeItemId); activeItem && activeItem instanceof ActionButtonItemDef && activeItem.execute(); }; private _handleOverflowClick = () => { this.setState((prevState) => { const isPressed = !prevState.isPressed; return { isPressed, }; }, () => { this._closeOnPanelOpened = false; !!this.state.isPressed && FrontstageManager.onToolPanelOpenedEvent.emit(); this._closeOnPanelOpened = true; }); }; private _handleDragInteractionOutsideClick = (e: MouseEvent) => { if (this.props.groupItemDef.overflow) { this._ref.current && (e.target instanceof Node) && !this._ref.current.contains(e.target) && this.closeGroupButton(); return; } this.closeGroupButton(); }; private _handleOutsideClick = (e: MouseEvent) => { this._ref.current && (e.target instanceof Node) && !this._ref.current.contains(e.target) && this.closeGroupButton(); }; private _handleToolActivatedEvent = ({ toolId }: ToolActivatedEventArgs) => { this.setState({ activeToolId: toolId, }); }; private _handleToolPanelOpenedEvent = () => { // istanbul ignore else if (!this._closeOnPanelOpened) return; // istanbul ignore next this.closeGroupButton(); }; private closeGroupButton() { const trayId = this.resetTrayId(); this.setState({ isPressed: false, trayId, backTrays: [], }); } private handleToolGroupItemClicked(trayKey: string, itemKey: string) { const trayId = this.resetTrayId(); this.setState( { activeItemId: itemKey, isPressed: false, trayId, backTrays: [], }, () => { const tray = this.getTray(trayKey); const childItem = tray.groupItemDef.getItemById(itemKey); childItem && childItem instanceof ActionButtonItemDef && childItem.execute(); }, ); } private getGroupTray(dragInteraction: boolean): React.ReactNode { if (!this.state.isPressed) return undefined; return ( <ToolGroupPanelContext.Consumer> {(activateOnPointerUp) => { const tray = this._tray; const itemsInColumn = tray.groupItemDef.itemsInColumn; const items = [...tray.items.keys()]; activateOnPointerUp = activateOnPointerUp && dragInteraction; // Divide items equally between columns. const numberOfColumns = Math.ceil(items.length / itemsInColumn); const numberItemsInColumn = Math.ceil(items.length / numberOfColumns); const columnToItems = items.reduce<ReadonlyArray<ReadonlyArray<string>>>((acc, item, index) => { const columnIndex = Math.floor(index / numberItemsInColumn); if (columnIndex >= acc.length) { return [ ...acc, [item], ]; } return [ ...acc.slice(0, columnIndex), [ ...acc[columnIndex], item, ], ...acc.slice(columnIndex + 1), ]; }, []); const columns = (columnToItems.map((columnItems, columnIndex) => <GroupColumn key={columnIndex}> {/* eslint-disable-line deprecation/deprecation */} {columnItems.map((itemKey) => { const item = tray.items.get(itemKey)!; const icon = <Icon iconSpec={item.iconSpec} />; let isVisible = true; let isActive = itemKey === this.state.activeToolId; let isEnabled = true; const badge = BadgeUtilities.getComponentForBadgeType(item.badgeType); if (item instanceof ItemDefBase) { isVisible = item.isVisible; // eslint-disable-line deprecation/deprecation isEnabled = item.isEnabled; // eslint-disable-line deprecation/deprecation if (item.stateFunc) { // eslint-disable-line deprecation/deprecation const newState = item.stateFunc({ isVisible, isActive, isEnabled }); // eslint-disable-line deprecation/deprecation isVisible = undefined !== newState.isVisible ? newState.isVisible : /* istanbul ignore next */ isVisible; isEnabled = undefined !== newState.isEnabled ? newState.isEnabled : /* istanbul ignore next */ isEnabled; isActive = undefined !== newState.isActive ? newState.isActive : /* istanbul ignore next */ isActive; } } const trayId = item.trayId; if (trayId) { return ( isVisible && <GroupToolExpander isDisabled={!isEnabled} key={itemKey} label={item.label} icon={icon} badge={badge} onClick={() => this._handleExpanderClick(trayId)} onPointerUp={activateOnPointerUp ? () => this._handleExpanderClick(trayId) : undefined} /> ); } return ( isVisible && <GroupTool isDisabled={!isEnabled} isActive={isActive} key={itemKey} label={item.label} onClick={() => this.handleToolGroupItemClicked(this.state.trayId, itemKey)} onPointerUp={activateOnPointerUp ? () => this.handleToolGroupItemClicked(this.state.trayId, itemKey) : undefined} icon={icon} badge={badge} /> ); })} </GroupColumn>, )); if (this.state.backTrays.length > 0) return ( <NestedToolGroup columns={columns} onBack={this._handleBack} onBackPointerUp={activateOnPointerUp ? this._handleBack : undefined} onOutsideClick={dragInteraction ? this._handleDragInteractionOutsideClick : this._handleOutsideClick} title={tray.title} /> ); return ( <ToolGroup columns={columns} onOutsideClick={dragInteraction ? this._handleDragInteractionOutsideClick : this._handleOutsideClick} title={tray.title} /> ); }} </ToolGroupPanelContext.Consumer> ); } public getItemById(id: string): ItemDefBase | undefined { for (const [, tray] of this.state.trays) { const item = tray.groupItemDef.getItemById(id); if (item) return item; } return undefined; } private _handleBack = () => { this.setState((prevState) => { const trayId = prevState.backTrays.length > 0 ? prevState.backTrays[prevState.backTrays.length - 1] : prevState.trayId; const backTrays = prevState.backTrays.slice(0, -1); return { trayId, backTrays, }; }); }; private _handleExpanderClick = (trayId: string) => { this.setState((prevState) => { return { trayId, backTrays: [...prevState.backTrays, prevState.trayId], }; }); }; } /** Properties for the [[GroupButton]] React component * @public */ export interface GroupButtonProps extends GroupItemProps, CommonProps { } /** Group Button React component * @public */ export function GroupButton(props: GroupButtonProps) { const groupItemDef = new GroupItemDef(props); groupItemDef.resolveItems(); return ( <GroupItem {...props} groupItemDef={groupItemDef} key={groupItemDef.id} /> ); } /** @internal */ export const getFirstItem = (groupItemDef: GroupItemDef): AnyItemDef | undefined => { for (const item of groupItemDef.items) { if (item instanceof GroupItemDef) { const firstItem = getFirstItem(item); if (firstItem) return firstItem; continue; } return item; } return undefined; }; /** @internal */ export const getFirstItemId = (groupItemDef: GroupItemDef): string => { const item = getFirstItem(groupItemDef); return item ? item.id : ""; };
the_stack
import Ganache, { Server } from "../index"; import * as assert from "assert"; import request from "superagent"; import WebSocket from "ws"; import { ServerStatus } from "../src/server"; import { MAX_PAYLOAD_SIZE as WS_MAX_PAYLOAD_SIZE } from "../src/servers/ws-server"; import http from "http"; // https://github.com/sindresorhus/into-stream/releases/tag/v6.0.0 import intoStream = require("into-stream"); import { PromiEvent } from "@ganache/utils"; import { promisify } from "util"; import { ServerOptions } from "../src/options"; import { Connector, Provider as EthereumProvider } from "@ganache/ethereum"; const IS_WINDOWS = process.platform === "win32"; describe("server", () => { const port = 5234; const networkId = 1234; const jsonRpcJson: any = { jsonrpc: "2.0", id: "1", method: "net_version", params: [] }; const logger = { log: (_message: string) => {} }; let s: Server; async function setup( options: ServerOptions = { chain: { networkId }, logging: { logger } } ) { // @ts-ignore - `s` errors if you run tsc and then test // because it tries to compare the built declaration file to // the TS file, causing missing #<var> private variables s = Ganache.server(options); return s.listen(port); } async function teardown() { // if the server is opening or open, try to close it. if (s && (s.status & ServerStatus.openingOrOpen) !== 0) { await s.close(); } } describe("http", () => { async function simpleTest() { const response = await request .post("http://localhost:" + port) .send(jsonRpcJson); assert.strictEqual(response.status, 200); // make sure we aren't including the uwebsockets header assert.strictEqual("uwebsockets" in response.headers, false); const json = JSON.parse(response.text); assert.strictEqual(json.result, `${networkId}`); return response; } it("handles connector initialization errors by rejecting on .listen", async () => { // This Ganache.server({...}) here will cause an internal error in the // Ethereum provider initialization. We don't want to throw an unhandled // promise reject; so we handle it in the `listen` method. const s = Ganache.server({ fork: { url: "https://mainnet.infura.io/v3/INVALID_URL" } }); await assert.rejects(s.listen(port)); }); it("returns its status", async () => { const s = Ganache.server(); try { assert.strictEqual(s.status, ServerStatus.ready); const pendingListen = s.listen(port); assert.strictEqual(s.status, ServerStatus.opening); assert.ok( s.status & ServerStatus.opening, "Bitmask broken: can't be used to determine `opening` state" ); await pendingListen; assert.strictEqual(s.status, ServerStatus.open); assert.ok( s.status & ServerStatus.open, "Bitmask broken: can't be used to determine `open` state" ); const pendingClose = s.close(); assert.strictEqual(s.status, ServerStatus.closing); assert.ok( s.status & ServerStatus.closing, "Bitmask broken: can't be used to determine `closing` state" ); await pendingClose; assert.strictEqual(s.status, ServerStatus.closed); assert.ok( s.status & ServerStatus.closed, "Bitmask broken: can't be used to determine `closed` state" ); } catch (e) { // in case of failure, make sure we properly shut things down if (s.status & ServerStatus.open) { await s.close().catch(e => e); } throw e; } }); it("returns the net_version", async () => { await setup(); try { await simpleTest(); } finally { await teardown(); } }); it("returns the net_version over a legacy-style connection listener", done => { // @ts-ignore - `s` errors if you run tsc and then test // because it tries to compare the built declaration file to // the TS file, causing missing #<var> private variables s = Ganache.server({ chain: { networkId } }); s.listen(port, async () => { try { await simpleTest(); } finally { await teardown(); } done(); }); }); it("fails to `.listen()` twice, Promise", async () => { await setup(); try { // the call to `setup()` above calls `listen()` already. if we call it // again it should fail. await assert.rejects(s.listen(port), { message: `Server is already open, or is opening, on port: ${port}.` }); } finally { await teardown(); } }); it("fails to `.listen()` twice, Callback", async () => { await setup(); try { // the call to `setup()` above calls `listen()` already. if we call it // again it should fail. const listen = promisify(s.listen.bind(s)); await assert.rejects(listen(port), { message: `Server is already open, or is opening, on port: ${port}.` }); } finally { await teardown(); } }); it("fails to `.close()` if server is closed", async () => { await setup(); try { await s.close(); await assert.rejects(s.close(), { message: "Server is already closing or closed." }); } finally { await teardown(); } }); it("fails to `.close()` if server is closed", async () => { await setup(); try { s.close(); await assert.rejects(s.close(), { message: "Server is already closing or closed." }); } finally { await teardown(); } }); it("fails to listen if the socket is already in use by 3rd party, Promise", async () => { const server = http.createServer(); server.listen(port); try { await assert.rejects( setup(), `Error: listen EADDRINUSE: address already in use 127.0.0.1:${port}.` ); } finally { await Promise.all([ teardown(), new Promise<void>((resolve, reject) => server.close(err => (err ? reject(err) : resolve())) ) ]); } }); it("fails to listen if the socket is already in use by 3rd party, Callback", async () => { const server = http.createServer(); server.listen(port); try { // @ts-ignore - `s` errors if you run tsc and then test // because it tries to compare the built declaration file to // the TS file, causing missing #<var> private variables const s = Ganache.server(); const listen = promisify(s.listen.bind(s)); await assert.rejects(listen(port), { message: `listen EADDRINUSE: address already in use 127.0.0.1:${port}.` }); } finally { await Promise.all([ teardown(), new Promise<void>((resolve, reject) => server.close(err => (err ? reject(err) : resolve())) ) ]); } }); // skip on Windows until https://github.com/uNetworking/uSockets/pull/101 is merged (IS_WINDOWS ? xit : it)( "fails to listen if the socket is already in use by Ganache", async () => { await new Promise<void>(async resolve => { await setup(); // @ts-ignore - `s` errors if you run tsc and then test // because it tries to compare the built declaration file to // the TS file, causing missing #<var> private variables const s2 = Ganache.server(); const expectedErrorRegex = new RegExp(`EADDRINUSE.*${port}`); const localTearDown = async () => { process.removeListener( "uncaughtException", handleUncaughtException ); process.on("uncaughtException", mochaListener); try { await s2.close(); } catch (e: any) { if ( e.message !== "Cannot close server while it is opening." && e.message !== "Server is already closing or closed." ) { throw e; } } await teardown(); }; let uncaughtExceptionOccurred = false; const handleUncaughtException = async err => { uncaughtExceptionOccurred = true; await localTearDown(); assert.notStrictEqual( expectedErrorRegex.exec(err.message), `Received unexpected error: ${err.message}` ); resolve(); }; const mochaListener = process.listeners("uncaughtException").pop(); process.removeListener("uncaughtException", mochaListener); process.on("uncaughtException", handleUncaughtException); try { await s2.listen(port); await new Promise(resolve => setTimeout(resolve, 500)); if (!uncaughtExceptionOccurred) { assert.fail( "Successfully listened twice on the same port instead of erroring" ); } } catch (e: any) { if (e.code === "ERR_ASSERTION") { throw e; } else { assert.notStrictEqual( expectedErrorRegex.exec(e.message), `Received unexpected error: ${e.message}` ); } } finally { if (!uncaughtExceptionOccurred) { await localTearDown(); resolve(); } } }); } ); it("rejects if listen called while server is closing, Promise", async () => { await setup(); try { const closer = s.close(); await assert.rejects(s.listen(4444), { message: "Cannot start server while it is closing." }); await closer; } finally { await teardown(); } }); it("rejects if listen called while server is closing, Callback", async () => { await setup(); try { const closer = s.close(); const listen = promisify(s.listen.bind(s)); await assert.rejects(listen(4444), { message: "Cannot start server while it is closing." }); await closer; } finally { await teardown(); } }); it("rejects if close is called while opening", async () => { const pendingSetup = setup(); try { await assert.rejects(s.close(), { message: "Cannot close server while it is opening." }); } finally { await pendingSetup; await teardown(); } }); it("does not start a websocket server when `ws` is false", async () => { await setup({ server: { ws: false } }); try { const ws = new WebSocket("ws://localhost:" + port); await assert.rejects( new Promise((resolve, reject) => { ws.on("open", resolve); ws.on("error", reject); }), { message: "Unexpected server response: 400" } ); } finally { await teardown(); } }); it("handles chunked requests (note: doesn't test sending with `transfer-encoding: chunked`)", async () => { await setup(); try { const req = request.post("http://localhost:" + port); const json = JSON.stringify(jsonRpcJson); // we have to set the content-length because we can't use // `Transfer-Encoding: chunked` to uWebSockets.js as of v15.9.0 req.set("Content-Length", json.length.toString()); await new Promise((resolve, reject) => { req.on("response", response => { const json = JSON.parse(response.text); assert.strictEqual(json.result, `${networkId}`); resolve(void 0); }); req.on("error", () => { reject(); }); const readableStream = intoStream(json); // make sure the data is sent as tiny pieces. (readableStream as any)._readableState.highWaterMark = 8; readableStream.pipe(req as any); }); } finally { await teardown(); } }); it("responds with transfer-encoding: chunked responses when bufferification is triggered", async () => { const originalThreshold = Connector.BUFFERIFY_THRESHOLD; // This will trigger bufferication in the Ethereum connector // for calls to debug_traceTransaction that return structLogs that have a // length greater than BUFFERIFY_THRESHOLD Connector.BUFFERIFY_THRESHOLD = 0; try { await setup(); const [from] = await s.provider.send("eth_accounts"); await s.provider.send("eth_subscribe", ["newHeads"]); const ops = [ { op: "PUSH1", code: "60", data: "00" }, { op: "PUSH1", code: "60", data: "00" }, { op: "RETURN", code: "f3", data: "" } ]; // a silly "contract" we can trace later: PUSH 0, PUSH, 0, RETURN const data = "0x" + ops.map(op => op.code + op.data).join(""); const hash = s.provider.send("eth_sendTransaction", [{ from, data }]); await s.provider.once("message"); // send a `debug_traceTransaction` request to the *server* so we can // test for `transfer-encoding: chunked` and bufferfication. const jsonRpcJson: any = { jsonrpc: "2.0", id: "1", method: "debug_traceTransaction", params: [await hash] }; const { text, header, status } = await request .post("http://localhost:" + port) .send(jsonRpcJson); const { result } = JSON.parse(text); assert.strictEqual(header["transfer-encoding"], "chunked"); assert.strictEqual(header["content-type"], "application/json"); assert.strictEqual(status, 200); assert.strictEqual(result.structLogs.length, ops.length); } finally { Connector.BUFFERIFY_THRESHOLD = originalThreshold; await teardown(); } }); it("returns 200/OK for RPC errors over HTTP", async () => { await setup(); const jsonRpcJson: any = { jsonrpc: "2.0", id: "1", method: "eth_subscribe", params: [] }; try { const response = await request .post("http://localhost:" + port) .send(jsonRpcJson); assert.strictEqual(response.status, 200); assert.strictEqual( JSON.parse(response.text).error.message, "notifications not supported" ); } finally { await teardown(); } }); it("handles batched json-rpc requests/responses", async () => { await setup(); const jsonRpcJson: any = [ { jsonrpc: "2.0", id: "1", method: "net_version", params: [] }, { jsonrpc: "2.0", id: "2", method: "eth_chainId", params: [] }, { jsonrpc: "2.0", id: "3", method: "eth_subscribe", // this one fails over HTTP params: ["newHeads"] } ]; try { const response = await request .post("http://localhost:" + port) .send(jsonRpcJson); const json = JSON.parse(response.text); assert.deepStrictEqual(json[0], { jsonrpc: "2.0", id: "1", result: "1234" }); assert.deepStrictEqual(json[1], { jsonrpc: "2.0", id: "2", result: "0x539" }); assert.deepStrictEqual(json[2].jsonrpc, "2.0"); assert.deepStrictEqual(json[2].id, "3"); assert.deepStrictEqual(json[2].error.code, -32004); assert.deepStrictEqual( json[2].error.message, "notifications not supported" ); } finally { await teardown(); } }); it("returns a teapot (easter egg)", async () => { await setup(); try { const result = await request .get("http://localhost:" + port + "/418") .catch(e => e); assert.strictEqual(result.status, 418); assert.strictEqual(result.message, "I'm a Teapot"); } finally { await teardown(); } }); it("returns 404 for bad routes", async () => { await setup(); const methods = [ "get", "post", "head", "options", "put", "delete", "patch", "trace" ] as const; try { const requests = methods.map(async method => { const result = await request[method]( "http://localhost:" + port + "/there-is-no-spoon" ).catch((e: any) => e); assert.strictEqual(result.status, 404); assert.strictEqual(result.message, "Not Found"); }); await Promise.all(requests); } finally { await teardown(); } }); it("doesn't crash when the request is aborted while waiting for repsonse", async () => { await setup(); try { const provider = s.provider as EthereumProvider; const oldRequestRaw = (provider as any)._requestRaw; const req = request.post("http://localhost:" + port); const abortPromise = new Promise(resolve => { (provider as any)._requestRaw = () => { // abort the request object after intercepting the request req.abort(); return new Promise(innerResolve => { // It takes 2 passes of the event loop to register the `abort` // server-side: setImmediate(setImmediate, () => { // resolve the `provider.send` to make sure the server can // handle _not_ responding to a request that has been aborted: innerResolve({ value: Promise.resolve() as any }); // and finally, resolve the `abort` promise: resolve(void 0); }); }); }; }); const result = await req.send(jsonRpcJson).catch(e => e); assert.strictEqual(result.code, "ABORTED", "Response was not aborted"); // wait for the server to react to the requesrt's `abort` await abortPromise; provider._requestRaw = oldRequestRaw; // now make sure we are still up and running: await simpleTest(); } finally { await teardown(); } }); it("server closes when told to", async () => { await setup(); try { await s.close(); const req = request.post("http://localhost:" + port); await assert.rejects(req.send(jsonRpcJson), { code: "ECONNREFUSED" }); } finally { await teardown(); } }); describe("CORS", () => { const optionsHeaders = [ "Access-Control-Allow-Methods", "Access-Control-Allow-Headers", "Access-Control-Max-Age" ] as const; const baseHeaders = [ "Access-Control-Allow-Credentials", "Access-Control-Allow-Origin" ] as const; const allCorsHeaders = [...optionsHeaders, ...baseHeaders] as const; it("does not return CORS headers for non-CORS requests", async () => { await setup(); try { const resp = await simpleTest(); allCorsHeaders.forEach(header => { assert.strictEqual( resp.header[header.toLowerCase()], void 0, `Non-CORS response should not contain header ${header}` ); }); } finally { await teardown(); } }); it("returns only base CORS headers for post request with origin header", async () => { await setup(); const origin = "origin"; try { const resp = await request .post("http://localhost:" + port) .set("origin", origin) .send(jsonRpcJson); assert.strictEqual(resp.status, 200); assert.strictEqual( resp.header["access-control-allow-credentials"], "true" ); assert.strictEqual( resp.header["access-control-allow-origin"], origin ); optionsHeaders.forEach(header => { assert.strictEqual( resp.header[header.toLowerCase()], void 0, `Non-CORS response should not contain header ${header}` ); }); } finally { await teardown(); } }); it("returns all CORS headers for request options request with origin header", async () => { await setup(); const origin = "origin"; try { const resp = await request .options("http://localhost:" + port) .set("origin", origin) .send(jsonRpcJson); assert.strictEqual(resp.status, 204); assert.strictEqual( resp.header["access-control-allow-methods"], "POST" ); assert.strictEqual( resp.header["access-control-allow-origin"], origin ); assert.strictEqual(resp.header["access-control-max-age"], "600"); // TODO: enable this check once https://github.com/uNetworking/uWebSockets/issues/1370 is fixed // assert.strictEqual( // "content-length" in resp.header, // false, // "RFC 7230: A server MUST NOT send a Content-Length header field in any response with a status code of 1xx (Informational) or 204 (No Content)" // ); assert.strictEqual( resp.header["access-control-allow-credentials"], "true" ); } finally { await teardown(); } }); it("echos Access-Control-Request-Headers for options request", async () => { await setup(); const origin = "origin"; const acrh = "origin, content-length, x-random"; try { const resp = await request .options("http://localhost:" + port) .set("origin", origin) .set("Access-Control-Request-Headers", acrh) .send(jsonRpcJson); assert.strictEqual(resp.status, 204); assert.strictEqual(resp.header["access-control-allow-headers"], acrh); } finally { await teardown(); } }); }); }); describe("websocket", () => { beforeEach(setup); afterEach(teardown); it("returns the net_version over a websocket", async () => { const ws = new WebSocket("ws://localhost:" + port); const { data }: any = await new Promise(resolve => { ws.on("open", () => { ws.send(JSON.stringify(jsonRpcJson)); }); ws.on("message", (data, isBinary) => resolve({ data, isBinary })); }); const json = JSON.parse(data); assert.strictEqual(json.result, `${networkId}`); }); it("returns the net_version over a websocket as binary", async () => { const ws = new WebSocket("ws://localhost:" + port); const response: any = await new Promise(resolve => { ws.on("open", () => { const strToAB = (str: string) => new Uint8Array(str.split("").map(c => c.charCodeAt(0))).buffer; ws.send(strToAB(JSON.stringify(jsonRpcJson))); }); ws.on("message", resolve); }); assert.strictEqual( response.constructor, Buffer, "response doesn't seem to be a Buffer as expected" ); const json = JSON.parse(response); assert.strictEqual( json.result, `${networkId}`, "Binary data result is not as expected" ); }); it("doesn't crash when sending bad data over http", async () => { await assert.rejects( request.post("http://localhost:" + port).send("This is _not_ pudding."), { message: "Bad Request" } ); const response = await request .post("http://localhost:" + port) .send(jsonRpcJson); const json = JSON.parse(response.text); assert.strictEqual(json.result, `${networkId}`); }); it("doesn't crash when sending bad data over websocket", async () => { const ws = new WebSocket("ws://localhost:" + port); const result = await new Promise<any>(resolve => { ws.on("open", () => { ws.on("message", resolve); ws.send("What is it?"); }); }); const json = JSON.parse(result); assert.strictEqual(json.error.code, -32700); }); it("doesn't crash when the connection is closed while a request is in flight", async () => { const provider = s.provider as EthereumProvider; provider._requestRaw = (async () => { // close our websocket after intercepting the request await s.close(); return { value: Promise.resolve(void 0) }; }) as any; const ws = new WebSocket("ws://localhost:" + port); return new Promise((resolve, reject) => { ws.on("open", () => { // If we get a message that means things didn't get closed as they // should have OR they are closing too late for some reason and // this test isn't testing anything. ws.on("message", () => reject("Got a message when we shouldn't have!") ); // make sure we leave enough time for things to crash if it does end // up crashing. ws.on("close", () => setImmediate(resolve)); // The RPC request method doesn't matter since we're duck punching our // provider.send method anyway. ws.send(JSON.stringify(jsonRpcJson)); }); }); }); it("handles PromiEvent messages", async () => { const provider = s.provider as EthereumProvider; const message = "I hope you get this message"; const oldRequestRaw = provider._requestRaw.bind(provider); provider._requestRaw = (async () => { const promiEvent = new PromiEvent(resolve => { const subId = "0xsubscriptionId"; resolve(subId); setImmediate(() => promiEvent.emit("message", { data: { subscription: subId, result: message } }) ); }); return { value: promiEvent }; }) as any; const ws = new WebSocket("ws://localhost:" + port); const result = await new Promise(resolve => { ws.on("open", () => { ws.on("message", data => { const { result, params } = JSON.parse(data.toString()); // ignore the initial response if (result === "0xsubscriptionId") return; resolve(params.result); }); const subscribeJson: any = { jsonrpc: "2.0", id: "1", method: "eth_subscribe", params: [] }; ws.send(JSON.stringify(subscribeJson)); }); }); assert.strictEqual(result, message); provider._requestRaw = oldRequestRaw; }); it("handles batched json-rpc requests/responses", async () => { const jsonRpcJson: any = [ { jsonrpc: "2.0", id: "1", method: "net_version", params: [] }, { jsonrpc: "2.0", id: "2", method: "eth_chainId", params: [] }, { jsonrpc: "2.0", id: "3", method: "eth_subscribe", // this one works here in WS-land params: ["newHeads"] } ]; const ws = new WebSocket("ws://localhost:" + port); const response: any = await new Promise(resolve => { ws.on("open", () => { ws.send(JSON.stringify(jsonRpcJson)); }); ws.on("message", resolve); }); ws.close(); const json = JSON.parse(response); assert.deepStrictEqual(json, [ { jsonrpc: "2.0", id: "1", result: "1234" }, { jsonrpc: "2.0", id: "2", result: "0x539" }, { jsonrpc: "2.0", id: "3", result: "0x1" } ]); }); it("handles invalid json-rpc JSON", async () => { const ws = new WebSocket("ws://localhost:" + port); const response = await new Promise<any>(resolve => { ws.on("open", () => { ws.send(JSON.stringify(null)); }); ws.on("message", data => { resolve(JSON.parse(data.toString())); }); }); assert.strictEqual(response.error.code, -32700); }); it("doesn't crash when the connection is closed while a subscription is in flight", async () => { const provider = s.provider as EthereumProvider; let promiEvent: PromiEvent<any>; provider._requestRaw = (async () => { promiEvent = new PromiEvent(resolve => { resolve("0xsubscriptionId"); }); return { value: promiEvent }; }) as any; const ws = new WebSocket("ws://localhost:" + port); return new Promise((resolve, reject) => { ws.on("open", () => { // If we get a message that means things didn't get closed as they // should have OR they are closing too late for some reason and // this test isn't testing anything. ws.on("message", data => { if (JSON.parse(data.toString()).result === "0xsubscriptionId") { // close our websocket after intercepting the request s.close(); // then attempt to send a message back right after closing: promiEvent.emit("message", "I hope you don't get this message"); return; } // the above message should never be received reject("Got a subscription message when we shouldn't have!"); }); // make sure we leave enough time for things to crash if it does end // up crashing. ws.on("close", () => setImmediate(resolve)); const subscribeJson: any = { jsonrpc: "2.0", id: "1", method: "eth_subscribe", params: [] }; ws.send(JSON.stringify(subscribeJson)); }); }); }); it("responds with transfer-encoding: chunked responses when bufferification is triggered", async () => { // this test needs to set BUFFERIFY_THRESHOLD before starting the server await teardown(); const originalThreshold = Connector.BUFFERIFY_THRESHOLD; // This will trigger bufferication in the Ethereum connector // for calls to debug_traceTransaction that return structLogs that have a // length greater than BUFFERIFY_THRESHOLD Connector.BUFFERIFY_THRESHOLD = 0; try { await setup(); const [from] = await s.provider.send("eth_accounts"); await s.provider.send("eth_subscribe", ["newHeads"]); const ops = [ { op: "PUSH1", code: "60", data: "00" }, { op: "PUSH1", code: "60", data: "00" }, { op: "RETURN", code: "f3", data: "" } ]; // a silly "contract" we can trace later: PUSH 0, PUSH, 0, RETURN const data = "0x" + ops.map(op => op.code + op.data).join(""); const hash = s.provider.send("eth_sendTransaction", [{ from, data }]); await s.provider.once("message"); // send a `debug_traceTransaction` request to the *server* so we can // test for `transfer-encoding: chunked` and bufferfication. const jsonRpcJson: any = { jsonrpc: "2.0", id: "1", method: "debug_traceTransaction", params: [await hash] }; const ws = new WebSocket("ws://localhost:" + port); ws.binaryType = "fragments"; const response: any = await new Promise(resolve => { ws.on("open", () => { ws.send(Buffer.from(JSON.stringify(jsonRpcJson)), { binary: true }); }); ws.on("message", resolve); }); assert.strictEqual(Array.isArray(response), true); const { result } = JSON.parse(Buffer.concat(response)); assert.strictEqual(result.structLogs.length, ops.length); } finally { Connector.BUFFERIFY_THRESHOLD = originalThreshold; await teardown(); } }); describe("max payload size", () => { let ws: WebSocket; beforeEach(() => { ws = new WebSocket("ws://localhost:" + port); }); afterEach(() => { if (ws) { ws.close(); } }); const canSendPayloadWithoutSocketClose = (payload: Buffer) => { return new Promise<boolean>(resolve => { const handleClose = code => { resolve(false); }; ws.on("open", () => ws.send(payload)); ws.on("close", handleClose); ws.once("message", () => { ws.off("close", handleClose); resolve(true); }); }); }; it("can handle payloads up to max payload size", async () => { // This payload is invalid JSON-RPC, but we are just testing if the // server will receive it _at all_. It _should_ reject it as invalid // data, but *not* close the connection. const largePayload = Buffer.alloc(WS_MAX_PAYLOAD_SIZE); assert.strictEqual( await canSendPayloadWithoutSocketClose(largePayload), true ); }); it("can not send payload greater than max payload size; ws is closed on large payloads", async () => { // This payload is invalid JSON-RPC, but we are just testing if the // server will receive it _at all_. It _should_ close the websocket // connection, not just reject the data. const tooLargePayload = Buffer.alloc(WS_MAX_PAYLOAD_SIZE + 1); assert.strictEqual( await canSendPayloadWithoutSocketClose(tooLargePayload), false ); }); }); // TODO: actually handle backpressure! it.skip("can handle backpressure", async () => { { // create tons of data to force websocket backpressure const huge = {}; for (let i = 0; i < 1e6; i++) huge["prop_" + i] = { i }; (s.provider as EthereumProvider)._requestRaw = (async () => { return { value: Promise.resolve(huge) }; }) as any; } const ws = new WebSocket("ws://localhost:" + port); const oldLog = logger.log; try { let gotBackpressure = false; // duck punch `logger.log` so we can intercept logs logger.log = (message: string) => { if (message.indexOf("WebSocket backpressure: ") === 0) { gotBackpressure = true; } }; return await new Promise((resolve, reject) => { ws.on("open", () => { ws.on("message", _message => { if (gotBackpressure) { resolve(); } else { reject( new Error( "Possible false positive: Didn't detect backpressure" + " before receiving a message. Ensure `s.provider.send` is" + " sending enough data." ) ); } }); // The RPC request method doesn't matter since we're duck punching // our provider.send method anyway. ws.send(JSON.stringify(jsonRpcJson)); }); }); } finally { // put the original logger back so other tests that might rely on it // don't break. logger.log = oldLog; } }).timeout(10000); }); describe("emitter", () => { let server: Server; let didEmitOpen = false; let didEmitClose = false; before(async () => { server = Ganache.server(); server.on("open", () => { didEmitOpen = true; }); server.on("close", () => { didEmitClose = true; }); }); it("emits the open event", async () => { assert.strictEqual(didEmitOpen, false); assert.strictEqual(didEmitClose, false); await server.listen(port); assert.strictEqual(didEmitOpen, true); assert.strictEqual(didEmitClose, false); }); it("emits the close event", async () => { assert.strictEqual(didEmitOpen, true); assert.strictEqual(didEmitClose, false); await server.close(); assert.strictEqual(didEmitOpen, true); assert.strictEqual(didEmitClose, true); }); }); });
the_stack
import grafana from 'grafana_func'; import { State } from './state_class'; import _ from 'lodash'; import { Metric } from 'metric_class'; import { $GF } from 'globals_class'; import chroma from 'chroma-js'; /** * Rule definition * * @export * @class Rule */ export class Rule { data: gf.TIRuleData; shapeMaps: ShapeMap[] = []; textMaps: TextMap[] = []; linkMaps: LinkMap[] = []; eventMaps: EventMap[] = []; valueMaps: ValueMap[] = []; rangeMaps: RangeMap[] = []; id: string; removeClick = 2; states: Map<string, State>; highestLevel: number = -1; highestColor: string = ''; highestFormattedValue: string = ''; highestValue: any = undefined; execTimes: number = 0; /** * Creates an instance of Rule. * @param {string} pattern * @param {TIRuleData} data * @memberof Rule */ constructor(pattern: string, data: gf.TIRuleData) { this.data = data; this.data.pattern = pattern; this.id = $GF.utils.uniqueID(); this.states = new Map(); } /** * Get default data * * @static * @returns {gf.TIRuleData} * @memberof Rule */ static getDefaultData(): gf.TIRuleData { return { order: 1, pattern: '.*', unit: 'short', type: 'number', metricType: 'serie', alias: 'myRule', refId: 'A', column: 'Time', hidden: false, aggregation: 'current', decimals: 2, colors: ['rgba(245, 54, 54, 0.9)', 'rgba(237, 129, 40, 0.89)', 'rgba(50, 172, 45, 0.97)'], reduce: true, dateFormat: 'YYYY-MM-DD HH:mm:ss', thresholds: [50, 80], stringThresholds: ['/.*/', '/.*/'], invert: false, gradient: false, overlayIcon: false, tooltip: false, tooltipLabel: '', tooltipColors: false, tooltipOn: 'a', tpDirection: 'v', tpGraph: false, tpGraphSize: '100%', tpGraphType: 'line', tpGraphLow: null, tpGraphHigh: null, tpGraphScale: 'linear', shapeProp: 'id', shapeRegEx: true, shapeData: [], textProp: 'id', textRegEx: true, textData: [], linkProp: 'id', linkRegEx: true, linkData: [], eventProp: 'id', eventRegEx: false, eventData: [], mappingType: 1, valueData: [], rangeData: [], sanitize: false, }; } /** * return data of rule * * @returns {data} * @memberof Rule */ getData(): gf.TIRuleData { return this.data; } /** * import data in rule * * @returns {this} * @param {data} obj * @memberof Rule */ import(obj: any): this { const trc = $GF.trace.before(this.constructor.name + '.' + 'import()'); if (!!obj.unit) { this.data.unit = obj.unit; } if (!!obj.type) { this.data.type = obj.type; } if (!!obj.metricType) { this.data.metricType = obj.metricType; } if (!!obj.alias) { this.data.alias = obj.alias; } if (!!obj.refId) { this.data.refId = obj.refId; } if (!!obj.column) { this.data.column = obj.column; } if (!!obj.aggregation) { this.data.aggregation = obj.aggregation; } if (!!obj.decimals || obj.decimals === 0) { this.data.decimals = obj.decimals; } if (!!obj.colors) { this.data.colors = obj.colors.slice(0); } if (!!this.data.reduce) { this.data.reduce = true; } // 0.7.0 let colorOn: gf.TColorOnKeys | undefined = undefined; if (!!obj.colorOn) { colorOn = obj.colorOn; } // 0.7.0 let style: gf.TStyleColorKeys | undefined = undefined; if (!!obj.style) { style = obj.style; } // 0.7.0 let link = false; let linkUrl: string | undefined = undefined; let linkParams: boolean | undefined = undefined; if (!!obj.link) { link = obj.link; } if (!!obj.linkUrl) { linkUrl = obj.linkUrl; } if (!!obj.linkParams) { linkParams = obj.linkParams; } // 0.7.0 let linkOn: gf.TLinkOnKeys | undefined = undefined; if (!!obj.linkOn) { linkOn = obj.linkOn; } // 0.7.0 let textOn: gf.TTextOnKeys | undefined = undefined; if (!!obj.textOn) { textOn = obj.textOn; } // 0.7.0 let textReplace: gf.TTextMethodKeys | undefined = undefined; let textPattern: string | undefined = undefined; if (!!obj.textReplace) { textReplace = obj.textReplace; } if (!!obj.textPattern) { textPattern = obj.textPattern; } if (!!obj.pattern) { this.data.pattern = obj.pattern; } if (!!obj.dateFormat) { this.data.dateFormat = obj.dateFormat; } if (!!obj.thresholds) { this.data.thresholds = obj.thresholds.map((x: any) => { let value = x; if (typeof value === 'string') { value = parseFloat(value); } return value; }); // this.data.thresholds = obj.thresholds.slice(0); } if (!!obj.stringThresholds) { this.data.stringThresholds = obj.stringThresholds.slice(0); } if (!!obj.stringWarning) { //this.data.stringWarning = obj.stringWarning; this.data.stringThresholds[1] = obj.stringWarning; } if (!!obj.stringCritical) { //this.data.stringCritical = obj.stringCritical; this.data.stringThresholds[0] = obj.stringCritical; } if (!!obj.invert || obj.invert === false) { this.data.invert = obj.invert; } if (!!obj.gradient || obj.gradient === false) { this.data.gradient = obj.gradient; } if (!!obj.overlayIcon || obj.overlayIcon === false) { this.data.overlayIcon = obj.overlayIcon; } if (!!obj.tooltip || obj.tooltip === false) { this.data.tooltip = obj.tooltip; } if (!!obj.tooltipLabel) { this.data.tooltipLabel = obj.tooltipLabel; } if (!!obj.tooltipColors || obj.tooltipColors === false) { this.data.tooltipColors = obj.tooltipColors; } if (!!obj.tooltipOn) { this.data.tooltipOn = obj.tooltipOn; } if (!!obj.tpDirection) { this.data.tpDirection = obj.tpDirection; } if (!!obj.tpGraph || this.data.tpGraph === false) { this.data.tpGraph = obj.tpGraph; } if (!!obj.tpGraphSize) { this.data.tpGraphSize = obj.tpGraphSize; } if (!!obj.tpGraphType) { this.data.tpGraphType = obj.tpGraphType; } if (!!obj.tpGraphLow || obj.tpGraphLow === 0) { this.data.tpGraphLow = obj.tpGraphLow; } if (!!obj.tpGraphHigh || obj.tpGraphHigh === 0) { this.data.tpGraphHigh = obj.tpGraphHigh; } if (!!obj.tpGraphScale) { this.data.tpGraphScale = obj.tpGraphScale; } let maps: any = []; // SHAPES if (!!obj.shapeProp) { this.data.shapeProp = obj.shapeProp; } if (!!obj.shapeRegEx || obj.shapeRegEx === false) { this.data.shapeRegEx = obj.shapeRegEx; } this.data.shapeData = []; // For 0.2.0 maps = []; if (obj.shapeMaps !== undefined && obj.shapeMaps !== null && obj.shapeMaps.length > 0) { maps = obj.shapeMaps; } else { maps = obj.shapeData; } if (maps !== undefined && maps !== null && maps.length > 0) { maps.forEach((shapeData: gf.TShapeMapData) => { // 0.7.0 if (!!style) { shapeData.style = style; } // 0.7.0 if (!!colorOn) { shapeData.colorOn = colorOn; } this.addShapeMap('').import(shapeData); }); } // TEXT this.data.textProp = obj.textProp || 'id'; if (!!obj.textRegEx || obj.textRegEx === false) { this.data.textRegEx = obj.textRegEx; } this.data.textData = []; // For 0.2.0 maps = []; if (obj.shapeMaps !== undefined && obj.shapeMaps !== null && obj.shapeMaps.length > 0) { maps = obj.textMaps; } else { maps = obj.textData; } if (maps !== undefined && maps != null && maps.length > 0) { maps.forEach((textData: gf.TTextMapData) => { // 0.7.0 if (!!textReplace) { textData.textReplace = textReplace; } if (!!textPattern) { textData.textPattern = textPattern; } if (!!textOn) { textData.textOn = textOn; } this.addTextMap('').import(textData); }); } // LINK this.data.linkProp = obj.linkProp || 'id'; if (!!obj.linkRegEx || obj.linkRegEx === false) { this.data.linkRegEx = obj.linkRegEx; } this.data.linkData = []; if (obj.linkData !== undefined && obj.linkData != null && obj.linkData.length > 0) { obj.linkData.forEach((linkData: gf.TlinkMapData) => { // 0.7.0 if (!!linkUrl && link) { linkData.linkUrl = linkUrl; } if (!!linkParams && link) { linkData.linkParams = linkParams; } if (!!linkOn) { linkData.linkOn = linkOn; } this.addLinkMap('').import(linkData); }); } // EVENT this.data.eventProp = obj.eventProp || 'id'; if (!!obj.eventRegEx || obj.eventRegEx === false) { this.data.eventRegEx = obj.eventRegEx; } this.data.eventData = []; if (obj.eventData !== undefined && obj.eventData != null && obj.eventData.length > 0) { obj.eventData.forEach((eventData: gf.TEventMapData) => { // 0.7.0 this.addEventMap('').import(eventData); }); } this.data.mappingType = obj.mappingType || 1; // VALUES this.data.valueData = []; if (obj.valueData !== undefined && obj.valueData != null && obj.valueData.length > 0) { obj.valueData.forEach((valueData: gf.TValueMapData) => { this.addValueMap('value', 'text').import(valueData); }); } // RANGE this.data.rangeData = []; if (obj.rangeData !== undefined && obj.rangeData != null && obj.rangeData.length > 0) { obj.rangeData.forEach(rangeData => { this.addRangeMap('from', 'to', 'text').import(rangeData); }); } this.data.sanitize = obj.sanitize || false; trc.after(); return this; } clear(): this { return this; } /** * Return uniq id of rule * * @returns * @memberof Rule */ getId(): string { return this.id; } /** * Highlight Cells in rule (mapping color text and link) * * @memberof Rule */ highlightCells() { if (this.states) { this.states.forEach(state => { state.highlightCell(); }); } } /** * Highlight Cells in rule (mapping color text and link) * * @memberof Rule */ unhighlightCells() { if (this.states) { this.states.forEach(state => { state.unhighlightCell(); }); } } /** * Return the order of this rule * Grafana 6+ have a bug when reload dashboad, array are not in order * * @param {number} order * @memberof Rule */ setOrder(order: number) { this.data.order = order; } /** * Return order of rule * * @memberof Rule */ getOrder(): number { return this.data.order; } isHidden(): boolean { return this.data.hidden; } hide(): this { this.data.hidden = true; return this; } show(): this { this.data.hidden = false; return this; } /** * Invert color order * * @returns {this} * @memberof Rule */ invertColorOrder(): this { // const ref = this.data.colors; // const copy = ref[0]; // ref[0] = ref[2]; // ref[2] = copy; this.data.colors.reverse(); // this.data.invert = !this.data.invert; // if (this.data.invert) { // this.data.invert = false; // } else { // this.data.invert = true; // } return this; } /** * Invert threshold * * @returns {this} * @memberof Rule */ invertThesholds(): this { this.invertColorOrder(); this.data.invert = !this.data.invert; return this; } /** * * * @param {number} index * @returns {this} * @memberof Rule */ addColor(index: number): this { const thresholds = this.data.thresholds; const colors = this.data.colors; const colorStart: string = colors[index]; let color: string; let value: any; if (index !== colors.length - 1) { const ratio = 0.5; let colorEnd = colors[index + 1]; try { // color = $GF.utils.getRatioColor(ratio, colorStart, colorEnd); let f = chroma.scale([colorStart, colorEnd]).mode('lrgb'); color = f(ratio).hex(); } catch (error) { $GF.log.error(error); color = colorStart; } if (this.data.type === 'number') { let absoluteDistance = thresholds[index] - thresholds[index - 1]; value = absoluteDistance / 2 + thresholds[index - 1]; } else { value = this.data.stringThresholds[index - 1]; } } else { color = colorStart; } this.data.colors.splice(index + 1, 0, color); if (this.data.type === 'number') { this.data.thresholds.splice(index, 0, value); } else if (this.data.type === 'string') { this.data.stringThresholds.splice(index, 0, value); } return this; } /** * * * @param {number} index * @returns {this} * @memberof Rule */ removeColor(index: number): this { this.data.thresholds.splice(index - 1, 1); this.data.stringThresholds.splice(index - 1, 1); this.data.colors.splice(index, 1); return this; } /** * Return a color * * @param {number} index * @returns {string} html color * @memberof Rule */ getColor(index: number): string { return this.data.colors[index]; } /** * Return Array of html colors * * @returns {string[]} * @memberof Rule */ getColors(): string[] { return this.data.colors; } /** * Return number of colors * * @returns {number} * @memberof Rule */ getColorsCount(): number { return this.data.colors.length; } // // Conditions // /** * Return true or false for condition to display icon warning * * @param {level} level * @returns {boolean} * @memberof Rule */ toIconize(level: number): boolean { if (this.data.overlayIcon === false) { return false; } if (this.data.overlayIcon === true && level >= 1) { return true; } return false; } /** * Return true or false for condition to display tooltip with values * * @param {number} level * @returns * @memberof Rule */ toTooltipize(level: number): boolean { if (this.data.tooltip === false) { return false; } if (this.data.tooltipOn === 'a') { return true; } if (this.data.tooltipOn === 'wc' && level >= 1) { return true; } return false; } // // Series|Tables // /** * Return boolean if metrics is matched by rule * * @param {Metric} metric * @returns {boolean} * @memberof Rule */ matchMetric(metric: Metric): boolean { if (this.data.metricType === 'serie' && metric.type === 'serie') { return $GF.utils.matchString(metric.getName(), this.data.pattern); } if (this.data.metricType === 'table' && metric.type === 'table') { return metric.getName() === this.data.refId; } return false; } // // SHAPE MAPS // /** * Add new shape for rule * * @param {string} pattern * @memberof Rule */ addShapeMap(pattern: string): ShapeMap { const data = ShapeMap.getDefaultData(); const m = new ShapeMap(pattern, data); this.shapeMaps.push(m); this.data.shapeData.push(data); return m; } /** * Remove shape for rule * * @returns {this} * @param {number} index * @memberof Rule */ removeShapeMap(index: number): this { this.data.shapeData.splice(index, 1); this.shapeMaps.splice(index, 1); return this; } /** * Return shape objet in index position * * @param {number} index * @returns {ShapeMap} * @memberof Rule */ getShapeMap(index: number): ShapeMap { return this.shapeMaps[index]; } /** * Return all ShapeMaps * * @returns {Array<ShapeMap>} * @memberof Rule */ getShapeMaps(): ShapeMap[] { return this.shapeMaps; } /** * Return bool if shape name (value|id) is in rule * * @param {string} pattern * @returns {boolean} * @memberof Rule */ matchShape(pattern: string | null): boolean { let found = false; this.shapeMaps.forEach(element => { if (element.match(pattern, this.data.shapeRegEx)) { found = true; } }); return found; } // // TEXT MAPS // addTextMap(pattern: string): TextMap { const data = TextMap.getDefaultData(); const m = new TextMap(pattern, data); this.textMaps.push(m); this.data.textData.push(data); return m; } removeTextMap(index: number) { this.data.textData.splice(index, 1); this.textMaps.splice(index, 1); } getTextMap(index: number): TextMap { return this.textMaps[index]; } getTextMaps(): TextMap[] { return this.textMaps; } matchText(pattern: string | null): boolean { let found = false; this.textMaps.forEach(element => { if (element.match(pattern)) { found = true; } }); return found; } // // Event MAPS // addEventMap(pattern: string): EventMap { const data = EventMap.getDefaultData(); const m = new EventMap(pattern, data); this.eventMaps.push(m); this.data.eventData.push(data); return m; } removeEventMap(index: number) { this.data.eventData.splice(index, 1); this.eventMaps.splice(index, 1); } getEventMap(index: number): EventMap { return this.eventMaps[index]; } getEventMaps(): EventMap[] { return this.eventMaps; } matchEvent(pattern: string | null): boolean { let found = false; this.eventMaps.forEach(element => { if (element.match(pattern)) { found = true; } }); return found; } // // LINK MAPS // addLinkMap(pattern: string): LinkMap { $GF.log.info('Rule.addLinkMap()'); const data = LinkMap.getDefaultData(); const m = new LinkMap(pattern, data); m.import(data); this.linkMaps.push(m); this.data.linkData.push(data); return m; } removeLinkMap(index: number) { this.data.linkData.splice(index, 1); this.linkMaps.splice(index, 1); } getLinkMap(index: number): LinkMap { return this.linkMaps[index]; } getLinkMaps(): LinkMap[] { return this.linkMaps; } matchLink(pattern: string | null): boolean { let found = false; this.linkMaps.forEach(element => { if (element.match(pattern)) { found = true; } }); return found; } // // STRING VALUE MAPS // addValueMap(value: any, text: string): ValueMap { const data: gf.TValueMapData = ValueMap.getDefaultdata(); const m = new ValueMap(value, text, data); this.valueMaps.push(m); this.data.valueData.push(data); return m; } removeValueMap(index) { this.data.valueData.splice(index, 1); this.valueMaps.splice(index, 1); } getValueMap(index): ValueMap { return this.valueMaps[index]; } getValueMaps(): ValueMap[] { return this.valueMaps; } // // STRING RANGE VALUE MAPS // addRangeMap(from, to, text): RangeMap { const data = RangeMap.getDefaultData(); const m = new RangeMap(from, to, text, data); this.rangeMaps.push(m); this.data.rangeData.push(data); return m; } removeRangeMap(index) { this.data.rangeData.splice(index, 1); this.rangeMaps.splice(index, 1); } getRangeMap(index): RangeMap { return this.rangeMaps[index]; } getRangeMaps(): RangeMap[] { return this.rangeMaps; } hideRangeMap(index): this { this.rangeMaps[index].hide(); return this; } showRangeMap(index): this { this.rangeMaps[index].show(); return this; } getExectedTime(): string { return typeof this.execTimes === 'number' ? `${this.execTimes.toFixed(2)} ms` : `${this.execTimes} ms`; } // // Format value // /** * Get color according to value * * @param {number} value * @returns {string} html color * @memberof Rule */ getColorForValue(value: any): string { if (!this.data.gradient || this.data.type !== 'number') { let level = this.getThresholdLevel(value); return this.getColorForLevel(level); } if (this.data.type === 'number') { const thresholds = this.data.thresholds; const colors = this.data.colors; let l = thresholds.length; // No Thresholds if (thresholds === undefined || l === 0) { return colors[0]; } let cursor = 0; for (let index = 0; index < l; index++) { const t = thresholds[index]; if (value < t) { break; } cursor = index; } // value Lower than min level if (cursor === 0 && value <= thresholds[0]) { return colors[0]; } // value upper then max level if (cursor === l - 1) { return colors[cursor + 1]; } // Or let absoluteDistance = thresholds[cursor + 1] - thresholds[cursor]; let valueDistanceFromMin = value - thresholds[cursor]; let ratio = valueDistanceFromMin / absoluteDistance; // let color = $GF.utils.getRatioColor(ratio, colors[cursor + 1], colors[cursor + 2]); let color = colors[cursor + 1]; try { color = chroma .scale([colors[cursor + 1], colors[cursor + 2]]) .mode('lrgb')(ratio) .hex(); } catch (error) { color = colors[cursor + 1]; } return color; } return ''; } /** * Get color according level (-1,0,1,2) * * @param {*} level * @returns * @memberof Rule */ getColorForLevel(level: number): string { const colors = this.data.colors; if (level < 0) { return colors[0]; } let l = level; if (!this.data.invert) { l = this.data.colors.length - 1 - level; } if (colors[l] !== undefined) { return colors[l]; } return colors[0]; } /** * Return Level according to value and rule options * * @param {number} value * @returns 0, 1 or 2 * @memberof Rule */ getThresholdLevel(value: any): number { // NUMBER if (this.data.type === 'number') { let thresholdLevel = 0; let thresholds = this.data.thresholds; if (thresholds === undefined || thresholds.length === 0) { return 0; } let l = thresholds.length; for (let index = 0; index < l; index++) { const t = thresholds[index]; if (value < t) { break; } thresholdLevel = index + 1; } if (!this.data.invert) { thresholdLevel = this.data.colors.length - 1 - thresholdLevel; } return thresholdLevel; } // STRING if (this.data.type === 'string') { let thresholdLevel = 0; const formatedValue = this.getFormattedValue(value); let thresholds = this.data.stringThresholds; if (thresholds === undefined || thresholds.length === 0) { return 0; } let l = thresholds.length; for (let index = 0; index < l; index++) { const t = thresholds[index]; if ($GF.utils.matchString(value, t) || $GF.utils.matchString(formatedValue, t)) { thresholdLevel = index + 1; break; } } if (!this.data.invert) { thresholdLevel = this.data.colors.length - 1 - thresholdLevel; } return thresholdLevel; } return 0; } /** * Get value for this metric * * @param {Metric} metric * @returns {(string | number | null)} * @memberof Rule */ getValueForMetric(metric: Metric): string | number | null { if (this.matchMetric(metric)) { try { const value = metric.getValue(this.data.aggregation, this.data.column); return value; } catch (error) { $GF.log.error('datapoint for metric is null', error); return null; } } return '-'; } /** * Get formatting value according unit * * @param {Metric} metric * @returns {string} * @memberof Rule */ getFormattedValueForMetric(metric: Metric): string { const formattedValue = this.getValueForMetric(metric); return this.getFormattedValue(formattedValue); } /** * Format a one value according rule * * @param {*} value * @returns * @memberof Rule */ getFormattedValue(value: any) { // Number if (this.data.type === 'number') { if (!_.isFinite(value)) { return 'null'; } if (value === null || value === void 0) { return '-'; } let decimals = this.decimalPlaces(value); decimals = typeof this.data.decimals === 'number' ? Math.min(this.data.decimals, decimals) : decimals; return grafana.formatValue(value, this.data.unit, this.data.decimals); } if (this.data.type === 'string') { if (value === null || value === void 0) { value = 'null'; } if (_.isArray(value)) { value = value.join(', '); } const mappingType = this.data.mappingType || 0; if (mappingType === 1 && this.valueMaps) { for (let i = 0; i < this.valueMaps.length; i += 1) { const map = this.valueMaps[i]; if (map.match(value)) { return map.getFormattedText(value); } } return value.toString(); } if (mappingType === 2 && this.rangeMaps) { for (let i = 0; i < this.rangeMaps.length; i += 1) { const map = this.rangeMaps[i]; if (map.match(value)) { return map.getFormattedText(value); } } return value.toString(); } if (value === null || value === void 0) { return 'null'; } } if (this.data.type === 'date') { if (value === undefined || value === null) { return '-'; } if (_.isArray(value)) { value = value[0]; } let d = grafana.getFormatedDate(value, this.data.dateFormat); return d; } return value; } defaultValueFormatter(value: any) { if (value === null || value === void 0 || value === undefined) { return ''; } if (_.isArray(value)) { value = value.join(', '); } if (this.data.sanitize) { return this.$sanitize(value); } return _.escape(value); } $sanitize(value: any) { throw new Error('Method not implemented.'); } decimalPlaces(num) { const match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/); if (!match) { return 0; } return Math.max( 0, // Number of digits right of decimal point. (match[1] ? match[1].length : 0) - // Adjust for scientific notation. (match[2] ? +match[2] : 0) ); } } export class GFMap { data: gf.TGFMapData; id: string; static methods: any[] = []; constructor(pattern, data: gf.TGFMapData) { this.data = data; this.data.pattern = pattern; this.id = $GF.utils.uniqueID(); // this.import(data); } /** * Import data from panel * * @param {*} obj * @returns {this} * @memberof GFMap */ import(obj: any): this { if (!!obj.pattern) { this.data.pattern = obj.pattern; } if (!!obj.hidden) { this.data.hidden = obj.hidden; } return this; } clear(): this { return this; } static getDefaultMethods() { return this.methods; } static getDefaultPlaceHolder(value: string): string | undefined { const elt = this.methods.find(x => x.value === value); if (elt !== undefined) { return elt.placeholder; } return undefined; } static getDefaultValue(value: string): string | undefined { const elt = this.methods.find(x => x.value === value); if (elt !== undefined) { return elt.default; } return undefined; } /** * Return if text match pattern * * @param {(string | null)} text * @returns {boolean} * @memberof GFMap */ match(text: string | null, regex = true): boolean { if (text === undefined || text === null || text.length === 0) { return false; } return $GF.utils.matchString(text, this.data.pattern, regex); } /** * Return uniq ID * * @returns {string} * @memberof GFMap */ getId(): string { return this.id; } /** * Show/enable * * @returns {this} * @memberof GFMap */ show(): this { this.data.hidden = false; return this; } /** * Hide/disable * * @returns {this} * @memberof GFMap */ hide(): this { this.data.hidden = true; return this; } /** * Return if hidden * * @returns {boolean} * @memberof GFMap */ isHidden(): boolean { if (this.data.hidden === undefined) { return false; } return this.data.hidden; } /** * Toggle Visible/Hide * * @returns {boolean} * @memberof GFMap */ toVisible(): boolean { if (this.data.hidden) { return false; } return true; } export(): gf.TGFMapData { return { pattern: this.data.pattern, hidden: this.data.hidden, }; } } /** * ShapeMap class for mapping * @class ShapeMap * @extends GFMap */ export class ShapeMap extends GFMap { data: gf.TShapeMapData; /** * Creates an instance of ShapeMap. * @param {string} pattern * @param {gf.TShapeMapData} data * @memberof ShapeMap */ constructor(pattern: string, data: gf.TShapeMapData) { super(pattern, data); this.data = data; } /** * Return default data * * @static * @returns {gf.TShapeMapData} * @memberof ShapeMap */ static getDefaultData(): gf.TShapeMapData { return { pattern: '', hidden: false, style: 'fillColor', colorOn: 'a', }; } /** * Return true or false for condition to colorize * * @param {number} level * @returns {boolean} * @memberof ShapeMap * 0.7.0 : Moved to shape */ toColorize(level: number): boolean { if (level === -1) { return false; } if (this.data.colorOn === 'n') { return false; } if (this.data.colorOn === 'a') { return true; } if (this.data.colorOn === 'wc' && level >= 1) { return true; } return false; } /** * Import data * * @param {*} obj * @returns {this} * @memberof ShapeMap */ import(obj: any): this { super.import(obj); if (!!obj.style) { this.data.style = obj.style; } if (!!obj.colorOn) { this.data.colorOn = obj.colorOn; } return this; } } /** * TextMap class for mapping * @class TextMap * @extends GFMap */ export class TextMap extends GFMap { data: gf.TTextMapData; constructor(pattern: string, data: gf.TTextMapData) { super(pattern, data); this.data = data; } /** * Return default data * * @static * @returns {gf.TTextMapData} * @memberof TextMap */ static getDefaultData(): gf.TTextMapData { return { pattern: '', hidden: false, textReplace: 'content', textPattern: '/.*/', textOn: 'wmd', }; } /** * Return true or false for condition to change label * * @param {number} level * @returns {boolean} * @memberof TextMap */ toLabelize(level: number): boolean { // if (this.data.textOn === 'wmd' && level > 0) return true; // if (this.data.textOn === 'wmd' && level === -1) return false; if (this.data.textOn === 'wmd') { return true; } if (this.data.textOn === 'n') { return false; } if (this.data.textOn === 'wc' && level >= 1) { return true; } if (this.data.textOn === 'co' && level >= 2) { return true; } return false; } /** * Import data from current or old version * * @param {*} obj * @returns {this} * @memberof TextMap */ import(obj: any): this { super.import(obj); if (!!obj.textReplace) { this.data.textReplace = obj.textReplace; } if (!!obj.textPattern) { this.data.textPattern = obj.textPattern; } if (!!obj.textOn) { this.data.textOn = obj.textOn; } return this; } /** * Replace text according text options * * @param {string} text * @param {string} FormattedValue * @returns * @memberof Rule */ getReplaceText(text: string, FormattedValue: string): string { if (this.data.textReplace === 'content') { return FormattedValue; } if (this.data.textReplace === 'pattern') { const regexVal = $GF.utils.stringToJsRegex(this.data.textPattern); if (text.toString().match(regexVal)) { return text.toString().replace(regexVal, FormattedValue); } return text; } if (this.data.textReplace === 'as') { return `${text} ${FormattedValue}`; } if (this.data.textReplace === 'anl') { return `${text}\n${FormattedValue}`; } return text; } } /** * LinkMap class for mapping * @class LinkMap * @extends GFMap */ export class LinkMap extends GFMap { data: gf.TlinkMapData; constructor(pattern: string, data: gf.TlinkMapData) { super(pattern, data); this.data = data; } static getDefaultData(): gf.TlinkMapData { return { pattern: '', hidden: false, linkUrl: '', linkParams: false, linkOn: 'a', }; } /** * Get defined link * * @returns * @memberof Rule */ getLink() { if (this.data.linkParams) { return this.data.linkUrl + window.location.search; } return this.data.linkUrl; } /** * Import data to Link * * @param {*} obj * @returns {this} * @memberof LinkMap */ import(obj: any): this { super.import(obj); if (!!obj.linkUrl) { this.data.linkUrl = obj.linkUrl; } if (!!obj.linkParams) { this.data.linkParams = obj.linkParams; } if (!!obj.linkOn) { this.data.linkOn = obj.linkOn; } return this; } /** * Return true or false for condition to add/replace link * * @param {number} level * @returns {boolean} * @memberof LinkMap */ toLinkable(level: number): boolean { if (this.data.linkOn === 'a') { return true; } if (this.data.linkOn === 'wc' && level >= 1) { return true; } return false; } } export class EventMap extends GFMap { data: gf.TEventMapData; static methods = $GF.CONSTANTS.EVENTMETHODS; // static shapes: string[] = EventMap.getFormNames(); static shapes: string[] = []; /** * Creates an instance of EventMap. * @param {string} pattern * @param {gf.TEventMapData} data * @memberof EventMap */ constructor(pattern: string, data: gf.TEventMapData) { super(pattern, data); this.data = data; // GFGlobal.loadFile(_GF.CONSTANTS.VAR_STG_SHAPES, _GF.CONSTANTS.CONF_FILE_SHAPES); } /** * Return default data * * @static * @returns {gf.TShapeMapData} * @memberof ShapeMap */ static getDefaultData(): gf.TEventMapData { return { pattern: '', hidden: false, style: 'shape', eventOn: 0, value: '', }; } getPlaceHolder(): string { const ph = EventMap.getDefaultPlaceHolder(this.data.style); return ph !== undefined ? ph : ''; } getTypeahead(): string[] { const self = this; let result = $GF.getFullAvailableVarNames(); const elt: gf.TStyleEventElt | undefined = EventMap.methods.find(x => x.value === self.data.style); if (elt !== undefined && elt.typeahead !== undefined) { result = result.concat(elt.typeahead.split('|')); return result; } if (this.data.style === 'shape') { const shapes = EventMap.getFormNames(); Array.prototype.push.apply(result, shapes); } return result; } getValueByDefault(): string { const vbd = EventMap.getDefaultValue(this.data.style); return vbd !== undefined ? vbd : ''; } static getFormNames(): string[] { // if (EventMap.shapes === undefined) { // EventMap.shapes = []; // } if (EventMap.shapes.length > 0) { return EventMap.shapes; } // _GF.loadLocalFile(_GF.CONSTANTS.VAR_STG_SHAPES, _GF.CONSTANTS.CONF_FILE_SHAPES); // const shapesText: string = _GF.getVar(_GF.CONSTANTS.VAR_STG_SHAPES); const shapesText = $GF.utils.loadFile( $GF.getVar($GF.CONSTANTS.VAR_STG_CTXROOT) + $GF.CONSTANTS.CONF_FILE_SHAPESTXT ); if (shapesText !== undefined) { if (EventMap.shapes.length === 0) { EventMap.shapes = EventMap.shapes.concat(shapesText.split(/\n/)); // _GF.unsetVar(_GF.CONSTANTS.VAR_STG_SHAPES); return EventMap.shapes; } } return EventMap.shapes; } /** * Return true or false for condition to colorize * * @param {number} level * @returns {boolean} * @memberof ShapeMap * 0.7.0 : Moved to shape */ toEventable(level: number): boolean { return this.data.eventOn === -1 || level === this.data.eventOn; } /** * Import data * * @param {*} obj * @returns {this} * @memberof ShapeMap */ import(obj: any): this { super.import(obj); if (!!obj.style) { this.data.style = obj.style; } if (!!obj.eventOn) { this.data.eventOn = obj.eventOn; } if (!!obj.value) { this.data.value = obj.value; } return this; } } /** * TextMap class for Range Value * @class RangeMap */ class RangeMap { data: gf.TRangeMapData; constructor(from: string, to: string, text: string, data: gf.TRangeMapData) { this.data = data; this.data.from = from; this.data.to = to; this.data.text = text; this.data.hidden = false; // this.import(data); } /** * import data from panel * * @param {*} obj * @returns {this} * @memberof RangeMap */ import(obj: any): this { this.data.from = !!obj.from ? obj.from : undefined; this.data.to = !!obj.to ? obj.to : undefined; this.data.text = !!obj.text ? obj.text : undefined; this.data.hidden = !!obj.hidden || obj.hidden === false ? obj.hidden : false; return this; } /** * Get default data * * @static * @returns {gf.TRangeMapData} * @memberof RangeMap */ static getDefaultData(): gf.TRangeMapData { return { from: undefined, to: undefined, text: undefined, hidden: false, }; } /** * Match value * * @param {*} value * @returns {boolean} * @memberof RangeMap */ match(value: any): boolean { if ( (value !== undefined && typeof value === 'string' && value.length > 0) || (value !== undefined && typeof value === 'number') ) { let v: number = Number(value); if ( (this.data.from !== undefined && typeof value === 'string' && this.data.from.length > 0) || (this.data.from !== undefined && typeof value === 'number') ) { let from = Number(this.data.from); if (v >= from) { if ( (this.data.to !== undefined && typeof this.data.to === 'string' && this.data.to.length > 0) || (this.data.from !== undefined && typeof this.data.to === 'number') ) { let to = Number(this.data.to); return v < to; } return true; } return false; } // from is empty here if ( (this.data.to !== undefined && typeof this.data.to === 'string' && this.data.to.length > 0) || (this.data.to !== undefined && typeof this.data.to === 'number') ) { let to = Number(this.data.to); return v < to; } // from and to is empty return true; } return false; } /** * Return Formatted value * * @param {*} value * @returns {(string | null)} * @memberof RangeMap */ getFormattedText(value: any): string | undefined { if (this.match(value)) { return this.data.text; } return value; } /** * Show/enable range * * @memberof RangeMap */ show() { this.data.hidden = false; } /** * Hide/disable range * * @memberof RangeMap */ hide() { this.data.hidden = true; } /** * Is hidden * * @returns * @memberof RangeMap */ isHidden() { return this.data.hidden; } /** * is visible * * @returns * @memberof RangeMap */ toVisible() { if (this.data.hidden) { return false; } return true; } /** * Export current data * * @returns * @memberof RangeMap */ export() { return { from: this.data.from, to: this.data.to, text: this.data.text, hidden: this.data.hidden, }; } } class ValueMap { data: gf.TValueMapData; constructor(value: string, text: string, data: gf.TValueMapData) { this.data = data; this.data.value = value; this.data.text = text; this.data.hidden = false; this.import(data); } /** * Get default data * * @static * @returns * @memberof ValueMap */ static getDefaultdata() { return { value: undefined, text: undefined, hidden: false, }; } /** * import data from panel * * @param {*} obj * @returns {this} * @memberof ValueMap */ import(obj: any): this { this.data.value = obj.value || this.data.value || undefined; this.data.text = obj.text || this.data.text || undefined; this.data.hidden = obj.hidden || this.data.hidden || false; return this; } /** * Match value with datas * * @param {any} value * @returns {boolean} * @memberof ValueMap */ match(value: any): boolean { if (value === null || value === undefined) { if (this.data.value === 'null') { return true; } return false; } if (!_.isString(value) && Number(this.data.value) === Number(value)) { return true; } return $GF.utils.matchString(value.toString(), this.data.value); } /** * Get formatted value * * @param {any} value * @returns * @memberof ValueMap */ getFormattedText(value: any): string { if (value === null || value === undefined) { if (this.data.value === 'null' || this.data.value === 'undefined') { return !!this.data.text ? this.data.text : ''; } } if (this.match(value)) { return !!this.data.text ? this.data.text : ''; } return `${value}`; } /** * Show/enable valuemap * * @memberof ValueMap */ show() { this.data.hidden = false; } /** * Hide/disable valuemap * * @memberof ValueMap */ hide() { this.data.hidden = true; } /** * Is hidden/disable * * @returns * @memberof ValueMap */ isHidden() { return this.data.hidden; } /** * export data * * @returns * @memberof ValueMap */ export() { return { value: this.data.value, text: this.data.text, hidden: this.data.hidden, }; } }
the_stack
import * as THREE from 'three'; import {Action, AnyAction, combineReducers, Reducer} from 'redux'; import {Omit} from 'react-redux'; import {v4} from 'uuid'; import {GroupByFunction} from 'redux-undo'; import {pick} from 'lodash'; import {objectMapReducer} from './genericReducers'; import {FileIndexActionTypes, RemoveFilesActionType, UpdateFileActionType} from './fileIndexReducer'; import { getAbsoluteMiniPosition, getMapCentreOffsets, getRootAttachedMiniId, isMapFoggedAtPosition, MapPaintOperation, MapType, MiniType, MovementPathPoint, ObjectEuler, ObjectVector3, PiecesRosterColumn, PiecesRosterValue, PieceVisibilityEnum, scenarioToJson, ScenarioType, snapMap } from '../util/scenarioUtils'; import {getScenarioFromStore, getUndoableHistoryFromStore, ReduxStoreType} from './mainReducer'; import {buildEuler, buildVector3, eulerToObject, vector3ToObject} from '../util/threeUtils'; import { castMapProperties, castMiniProperties, DriveMetadata, GridType, MapProperties, MiniProperties, ScenarioObjectProperties, TemplateProperties } from '../util/googleDriveUtils'; import {ConnectedUserActionTypes} from './connectedUserReducer'; import {GToveThunk, isScenarioAction, ScenarioAction} from '../util/types'; import {TabletopReducerActionTypes} from './tabletopReducer'; // =========================== Action types and generators export enum ScenarioReducerActionTypes { SET_SCENARIO_ACTION = 'set-scenario-action', APPEND_SCENARIO_ACTION = 'append-scenario-action', SET_SCENARIO_LOCAL_ACTION = 'set-scenario-local-action', UPDATE_MAP_ACTION = 'update-map-action', UPDATE_MINI_ACTION = 'update-mini-action', ADJUST_MINIS_ON_MAP_ACTION = 'adjust-minis-on-map-action', REMOVE_MAP_ACTION = 'remove-map-action', REMOVE_MINI_ACTION = 'remove-mini-action', UPDATE_SNAP_TO_GRID_ACTION = 'update-snap-to-grid-action', REPLACE_METADATA_ACTION = 'replace-metadata-action', REPLACE_MAP_IMAGE_ACTION = 'replace-map-image-action', UPDATE_CONFIRM_MOVES_ACTION = 'update-confirm-moves-action', UPDATE_HEAD_ACTION_IDS = 'update-head-action-ids' } type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>; function populateScenarioAction<T extends ScenarioAction>(action: PartialBy<T, 'actionId'|'headActionIds'|'gmOnly'>, getState: () => ReduxStoreType): T { const scenario = getScenarioFromStore(getState()); const gmOnly = action.gmOnly || false; return Object.assign({}, action, { actionId: v4(), headActionIds: gmOnly ? scenario.headActionIds : scenario.playerHeadActionIds, gmOnly }) as T; } function populateScenarioActionThunk<T extends ScenarioAction>(action: PartialBy<T, 'actionId'|'headActionIds'|'gmOnly'>): GToveThunk<T & ScenarioAction> { return (dispatch, getState) => { const fullAction = populateScenarioAction(action, getState); return dispatch(fullAction); }; } interface SetScenarioAction extends ScenarioAction { type: ScenarioReducerActionTypes.SET_SCENARIO_ACTION; scenario: Partial<ScenarioType> } export function setScenarioAction(scenario: ScenarioType, peerKey: string, gmOnly = false, playersOnly?: boolean): GToveThunk<SetScenarioAction> { return populateScenarioActionThunk({type: ScenarioReducerActionTypes.SET_SCENARIO_ACTION, scenario, peerKey, gmOnly, playersOnly}); } interface AppendScenarioAction extends ScenarioAction { type: ScenarioReducerActionTypes.APPEND_SCENARIO_ACTION; scenario: Partial<ScenarioType> } export function appendScenarioAction(scenario: ScenarioType, peerKey: string, gmOnly = false): GToveThunk<AppendScenarioAction> { return populateScenarioActionThunk({type: ScenarioReducerActionTypes.APPEND_SCENARIO_ACTION, scenario, peerKey, gmOnly}); } export interface SetScenarioLocalAction { type: ScenarioReducerActionTypes.SET_SCENARIO_LOCAL_ACTION; scenario: ScenarioType } export function setScenarioLocalAction(scenario: ScenarioType): SetScenarioLocalAction { return {type: ScenarioReducerActionTypes.SET_SCENARIO_LOCAL_ACTION, scenario}; } interface UpdateSnapToGridActionType extends ScenarioAction { type: ScenarioReducerActionTypes.UPDATE_SNAP_TO_GRID_ACTION; snapToGrid: boolean; } export function updateSnapToGridAction(snapToGrid: boolean): GToveThunk<UpdateSnapToGridActionType> { return populateScenarioActionThunk({type: ScenarioReducerActionTypes.UPDATE_SNAP_TO_GRID_ACTION, snapToGrid, peerKey: 'snapToGrid'}); } interface UpdateConfirmMovesActionType extends ScenarioAction { type: ScenarioReducerActionTypes.UPDATE_CONFIRM_MOVES_ACTION; confirmMoves: boolean; } export function updateConfirmMovesAction(confirmMoves: boolean): GToveThunk<UpdateConfirmMovesActionType> { return populateScenarioActionThunk({type: ScenarioReducerActionTypes.UPDATE_CONFIRM_MOVES_ACTION, confirmMoves, peerKey: 'confirmMoves'}); } // ======================== Map Actions ========================= interface RemoveMapActionType extends ScenarioAction { type: ScenarioReducerActionTypes.REMOVE_MAP_ACTION; mapId: string; } export function removeMapAction(mapId: string): GToveThunk<RemoveMapActionType> { return undoGroupThunk((dispatch: (action: RemoveMapActionType) => void, getState) => { const gmOnly = getGmOnly({getState, mapId}); // Removing a map should reveal any hidden fogged pieces const scenario = getScenarioFromStore(getState()); for (let miniId of Object.keys(scenario.minis)) { const mini = scenario.minis[miniId]; if (mini.onMapId === mapId && mini.visibility === PieceVisibilityEnum.FOGGED && mini.gmOnly) { dispatch(updateMiniGMOnlyAction(miniId, false) as any); } } dispatch(populateScenarioAction({type: ScenarioReducerActionTypes.REMOVE_MAP_ACTION, mapId, peerKey: mapId, gmOnly}, getState)); }); } interface UpdateMapActionType extends ScenarioAction { type: ScenarioReducerActionTypes.UPDATE_MAP_ACTION; mapId: string; map: Partial<MapType>; } export function addMapAction(mapParameter: Partial<MapType>, mapId = v4()): GToveThunk<UpdateMapActionType> { const map = { ...initialMapState, fogOfWar: (mapParameter.metadata && mapParameter.metadata.properties.gridType === GridType.NONE) ? undefined : [], ...mapParameter }; return populateScenarioActionThunk({type: ScenarioReducerActionTypes.UPDATE_MAP_ACTION, mapId, map, peerKey: mapId, gmOnly: map.gmOnly}) } function updateMapAction(mapId: string, map: Partial<MapType>, selectedBy: string | null, extra: string = ''): GToveThunk<UpdateMapActionType> { return (dispatch: (action: UpdateMapActionType) => void, getState) => { let undoGroupId: string | null = null; if (extra === fogOfWarExtra) { // Updating fog of war needs special handling, to potentially reveal fogged minis undoGroupId = v4(); const scenario = getScenarioFromStore(getState()); const oldMap = scenario.maps[mapId]; for (let miniId of Object.keys(scenario.minis)) { const mini = scenario.minis[miniId]; if (mini.onMapId === mapId && mini.visibility === PieceVisibilityEnum.FOGGED) { let rootMiniId = getRootAttachedMiniId(miniId, scenario.minis); const onFog = isMapFoggedAtPosition(oldMap, scenario.minis[rootMiniId].position, map.fogOfWar || null); if (mini.gmOnly !== onFog) { dispatch(undoGroupThunk(updateMiniGMOnlyAction(miniId, onFog), undoGroupId) as any); } } } } dispatch(undoGroupAction(populateScenarioAction({ type: ScenarioReducerActionTypes.UPDATE_MAP_ACTION, mapId, map: {...map, selectedBy}, peerKey: mapId + extra, gmOnly: getGmOnly({getState, mapId}) }, getState), undoGroupId)); }; } export function updateMapPositionAction(mapId: string, position: THREE.Vector3 | ObjectVector3, selectedBy: string | null): GToveThunk<UpdateMapActionType> { return updateMapAction(mapId, {position: vector3ToObject(position)}, selectedBy, 'position'); } export function updateMapRotationAction(mapId: string, rotation: THREE.Euler | ObjectEuler, selectedBy: string | null): GToveThunk<UpdateMapActionType> { return updateMapAction(mapId, {rotation: eulerToObject(rotation)}, selectedBy, 'rotation'); } const fogOfWarExtra = 'fogOfWar'; export function updateMapFogOfWarAction(mapId: string, fogOfWar?: number[]): GToveThunk<UpdateMapActionType> { return updateMapAction(mapId, {fogOfWar}, null, fogOfWarExtra); } export function updateMapCameraFocusPoint(mapId: string, cameraFocusPoint?: ObjectVector3 | THREE.Vector3): GToveThunk<UpdateMapActionType> { const map = {cameraFocusPoint: cameraFocusPoint ? vector3ToObject(cameraFocusPoint) : undefined}; return updateMapAction(mapId, map, null, 'cameraFocus'); } export function updateMapGMOnlyAction(mapId: string, gmOnly: boolean): GToveThunk<UpdateMapActionType | RemoveMapActionType> { return (dispatch, getState) => { const scenario = getScenarioFromStore(getState()); const map = {...scenario.maps[mapId], gmOnly}; if (gmOnly) { // If we've turned on gmOnly, then we need to remove the map from peers, then put it back for GMs dispatch(populateScenarioAction<RemoveMapActionType>({type: ScenarioReducerActionTypes.REMOVE_MAP_ACTION, mapId, peerKey: mapId, gmOnly: false}, getState)); dispatch(populateScenarioAction<UpdateMapActionType>({type: ScenarioReducerActionTypes.UPDATE_MAP_ACTION, mapId, peerKey: mapId, map, gmOnly: true}, getState)); } else { // If we've turned off gmOnly, then peers need a complete copy of the map dispatch(populateScenarioAction<UpdateMapActionType>({type: ScenarioReducerActionTypes.UPDATE_MAP_ACTION, mapId, map, peerKey: mapId, gmOnly: false}, getState)); } }; } interface UpdateMapMetadataLocalActionType { type: ScenarioReducerActionTypes.UPDATE_MAP_ACTION; mapId: string; map: {metadata: DriveMetadata<void, MapProperties>} } export function updateMapMetadataLocalAction(mapId: string, metadata: DriveMetadata<void, MapProperties>): UpdateMapMetadataLocalActionType { return {type: ScenarioReducerActionTypes.UPDATE_MAP_ACTION, mapId, map: {metadata: {...metadata, properties: castMapProperties(metadata.properties)}}}; } export function updateMapPaintLayerAction(mapId: string, layerIndex: number, operationIndex: number, operation: MapPaintOperation): GToveThunk<UpdateMapActionType> { return (dispatch, getState) => { const scenario = getScenarioFromStore(getState()); const prevMap = scenario.maps[mapId]; const paintLayers = [...prevMap.paintLayers]; paintLayers[layerIndex] = prevMap.paintLayers[layerIndex] ? {operations: [...prevMap.paintLayers[layerIndex].operations]} : {operations: []}; paintLayers[layerIndex].operations[operationIndex] = operation; dispatch(populateScenarioAction({ type: ScenarioReducerActionTypes.UPDATE_MAP_ACTION, mapId, map: {paintLayers}, peerKey: operation.operationId + 'paint', gmOnly: getGmOnly({getState, mapId}) }, getState)); }; } export function clearMapPaintLayerAction(mapId: string) { return updateMapAction(mapId, {paintLayers: []}, null, 'paintClear'); } export function updateMapTransparencyAction(mapId: string, transparent: boolean) { return updateMapAction(mapId, {transparent}, null, 'transparent'); } // ======================== Mini Actions ========================= interface RemoveMiniActionType extends ScenarioAction { type: ScenarioReducerActionTypes.REMOVE_MINI_ACTION; miniId: string; positionObj?: ObjectVector3; rotationObj?: ObjectEuler; elevation?: number; } export function removeMiniAction(miniId: string, playersOnly?: boolean): GToveThunk<RemoveMiniActionType> { return (dispatch, getState) => { const scenario = getScenarioFromStore(getState()); const absoluteMiniPosition = getAbsoluteMiniPosition(miniId, scenario.minis); if (!absoluteMiniPosition) { dispatch(populateScenarioAction({type: ScenarioReducerActionTypes.REMOVE_MINI_ACTION, miniId, playersOnly, peerKey: 'remove' + miniId, gmOnly: getGmOnly({getState, miniId})}, getState)); } else { const {positionObj, rotationObj, elevation} = absoluteMiniPosition; dispatch(populateScenarioAction({type: ScenarioReducerActionTypes.REMOVE_MINI_ACTION, miniId, positionObj, rotationObj, elevation, playersOnly, peerKey: 'remove' + miniId, gmOnly: getGmOnly({getState, miniId})}, getState)); } }; } interface UpdateMiniActionType extends ScenarioAction { type: ScenarioReducerActionTypes.UPDATE_MINI_ACTION; miniId: string; mini: Partial<MiniType>; } export function addMiniAction(miniParameter: Partial<MiniType>): GToveThunk<UpdateMiniActionType> { const miniId: string = v4(); const mini = {position: ORIGIN, rotation: ROTATION_NONE, scale: 1.0, elevation: 0.0, gmOnly: true, prone: false, flat: false, piecesRosterValues: {}, piecesRosterGMValues: {}, ...miniParameter}; return populateScenarioActionThunk({type: ScenarioReducerActionTypes.UPDATE_MINI_ACTION, miniId, mini, peerKey: miniId, gmOnly: mini.gmOnly}); } function updateMiniAction(miniId: string, mini: Partial<MiniType> | ((state: ReduxStoreType) => Partial<MiniType>), selectedBy: string | null, extra: string = ''): GToveThunk<UpdateMiniActionType> { return (dispatch, getState) => { const prevState = getState(); const prevScenario = getScenarioFromStore(prevState); const prevMini: undefined | MiniType = prevScenario.minis[miniId]; if (typeof(mini) === 'function') { mini = mini(prevState); } // Changing visibility, position or attachment can affect gmOnly if (mini.visibility || mini.position || extra === attachExtra) { const visibility = mini.visibility || (prevMini && prevMini.visibility); let gmOnly = (visibility === PieceVisibilityEnum.HIDDEN); if (visibility === PieceVisibilityEnum.FOGGED) { const onMapId = mini.onMapId || (prevMini && prevMini.onMapId); let rootMiniId = getRootAttachedMiniId(miniId, prevScenario.minis); const position = rootMiniId === miniId ? (mini.position || (prevMini && prevMini.position)) : prevScenario.minis[rootMiniId].position; gmOnly = onMapId ? isMapFoggedAtPosition(prevScenario.maps[onMapId], position) : false; } if (prevMini && prevMini.gmOnly !== gmOnly) { mini.gmOnly = gmOnly; // also update anything attached to this mini for (let otherMiniId of Object.keys(prevScenario.minis)) { if (otherMiniId !== miniId && prevScenario.minis[otherMiniId].visibility === PieceVisibilityEnum.FOGGED && getRootAttachedMiniId(otherMiniId, prevScenario.minis) === miniId) { dispatch(updateMiniGMOnlyAction(otherMiniId, gmOnly) as any); } } } } // Changing attachMiniId also affects movementPath const updated = {...prevMini, ...mini}; if (prevMini && updated.attachMiniId !== prevMini.attachMiniId) { mini = {...mini, movementPath: !prevScenario.confirmMoves ? undefined : [getCurrentPositionWaypoint(prevMini, mini)]}; } // Changing gmOnly requires special handling if (prevMini) { if (!prevMini.gmOnly && mini.gmOnly === true) { // If we've turned on gmOnly, then we need to remove the mini from players dispatch(removeMiniAction(miniId, true) as any); } else if (prevMini.gmOnly && mini.gmOnly === false) { // If we've turned off gmOnly, then players need a complete copy of the mini dispatch(populateScenarioAction<UpdateMiniActionType>({type: ScenarioReducerActionTypes.UPDATE_MINI_ACTION, miniId, peerKey: 'add' + miniId, mini: {...prevMini, gmOnly: false}, playersOnly: true}, getState)); } } // Dispatch the update! dispatch(populateScenarioAction({ type: ScenarioReducerActionTypes.UPDATE_MINI_ACTION, miniId, mini: {...mini, selectedBy}, peerKey: miniId + extra, gmOnly: (mini.gmOnly !== undefined ? mini.gmOnly : prevMini.gmOnly) || (mini.piecesRosterGMValues !== undefined || mini.gmNoteMarkdown !== undefined) }, getState)); }; } export function updateMiniNameAction(miniId: string, name: string): GToveThunk<UpdateMiniActionType> { return updateMiniAction(miniId, {name}, null, 'name'); } export function updateMiniPositionAction(miniId: string, position: THREE.Vector3 | ObjectVector3, selectedBy: string | null, onMapId: string | undefined): GToveThunk<UpdateMiniActionType> { return updateMiniAction(miniId, {position: vector3ToObject(position), onMapId}, selectedBy, 'position'); } export function updateMiniRotationAction(miniId: string, rotation: THREE.Euler | ObjectEuler, selectedBy: string | null): GToveThunk<UpdateMiniActionType> { return updateMiniAction(miniId, {rotation: eulerToObject(rotation)}, selectedBy, 'rotation'); } export function updateMiniScaleAction(miniId: string, scale: number, selectedBy: string | null): GToveThunk<UpdateMiniActionType> { return updateMiniAction(miniId, {scale}, selectedBy, 'scale'); } export function updateMiniElevationAction(miniId: string, elevation: number, selectedBy: string | null): GToveThunk<UpdateMiniActionType> { return updateMiniAction(miniId, {elevation}, selectedBy, 'elevation'); } export function updateMiniLockedAction(miniId: string, locked: boolean): GToveThunk<UpdateMiniActionType> { return updateMiniAction(miniId, {locked}, null, 'locked'); } export function updateMiniProneAction(miniId: string, prone: boolean): GToveThunk<UpdateMiniActionType> { return updateMiniAction(miniId, {prone}, null, 'prone'); } export function updateMiniFlatAction(miniId: string, flat: boolean): GToveThunk<UpdateMiniActionType> { return updateMiniAction(miniId, {flat}, null, 'flat'); } export function updateMiniHideBaseAction(miniId: string, hideBase: boolean): GToveThunk<UpdateMiniActionType> { return updateMiniAction(miniId, {hideBase}, null, 'hideBase'); } export function updateMiniBaseColourAction(miniId: string, baseColour: number): GToveThunk<UpdateMiniActionType> { return updateMiniAction(miniId, {baseColour}, null, 'baseColour'); } const attachExtra = 'attach'; export function updateAttachMinisAction(miniId: string, attachMiniId: string | undefined, position: ObjectVector3, rotation: ObjectEuler, elevation: number): GToveThunk<UpdateMiniActionType> { return updateMiniAction(miniId, {attachMiniId, position, rotation, elevation}, null, attachExtra); } export function confirmMiniMoveAction(miniId: string): GToveThunk<UpdateMiniActionType> { return updateMiniAction(miniId, (state) => ({movementPath: [getCurrentPositionWaypoint(getScenarioFromStore(state).minis[miniId])]}), null, 'movementPath'); } export function addMiniWaypointAction(miniId: string): GToveThunk<UpdateMiniActionType> { return updateMiniAction(miniId, (state) => { const mini = getScenarioFromStore(state).minis[miniId]; return (mini.movementPath) ? {movementPath: [...mini.movementPath, getCurrentPositionWaypoint(mini)]} : {} }, null, 'movementPath'); } export function removeMiniWaypointAction(miniId: string): GToveThunk<UpdateMiniActionType> { return updateMiniAction(miniId, (state) => { const mini = getScenarioFromStore(state).minis[miniId]; return (mini.movementPath) ? {movementPath: mini.movementPath.slice(0, mini.movementPath.length - 1)} : {} }, null, 'movementPath'); } export function cancelMiniMoveAction(miniId: string): GToveThunk<UpdateMiniActionType> { return updateMiniAction(miniId, (state) => { const mini = getScenarioFromStore(state).minis[miniId]; return (mini.movementPath) ? {position: mini.movementPath[0], elevation: mini.movementPath[0].elevation || 0, movementPath: [mini.movementPath[0]]} : {} }, null, 'position+movementPath'); } export function updateMiniVisibilityAction(miniId: string, visibility: PieceVisibilityEnum): GToveThunk<UpdateMiniActionType> { return updateMiniAction(miniId, {visibility}, null, 'visibility'); } export function updateMiniGMOnlyAction(miniId: string, gmOnly: boolean): GToveThunk<UpdateMiniActionType> { return updateMiniAction(miniId, {gmOnly}, null, 'gmOnly'); } export function updateMiniRosterValueAction(miniId: string, column: PiecesRosterColumn, value?: PiecesRosterValue) { return updateMiniAction(miniId, (state) => { const mini = getScenarioFromStore(state).minis[miniId]; return column.gmOnly ? {piecesRosterGMValues: {...mini.piecesRosterGMValues, [column.id]: value}} : {piecesRosterValues: {...mini.piecesRosterValues, [column.id]: value}}; }, null, 'rosterValue') } export function updateMiniRosterSimpleAction(miniId: string, piecesRosterSimple: boolean) { return updateMiniAction(miniId, {piecesRosterSimple}, null, 'piecesRosterSimple'); } export function updateMiniNoteMarkdownAction(miniId: string, gmNoteMarkdown?: string) { return updateMiniAction(miniId, {gmNoteMarkdown}, null, 'gmNoteMarkdown'); } interface UpdateMinisOnMapActionType { type: ScenarioReducerActionTypes.ADJUST_MINIS_ON_MAP_ACTION; mapId: string; gmOnly: boolean; oldCentre: ObjectVector3; newCentre: ObjectVector3; deltaPosition?: THREE.Vector3; deltaRotation?: number; } function updateMinisOnMapAction(mapId: string, gmOnly: boolean, oldCentre: ObjectVector3, newCentre: ObjectVector3, deltaPosition?: THREE.Vector3, deltaRotation?: number): UpdateMinisOnMapActionType { return {type: ScenarioReducerActionTypes.ADJUST_MINIS_ON_MAP_ACTION, mapId, gmOnly, oldCentre, newCentre, deltaPosition, deltaRotation}; } interface UpdateMiniMetadataLocalActionType { type: ScenarioReducerActionTypes.UPDATE_MINI_ACTION; miniId: string; mini: {metadata: DriveMetadata<void, MiniProperties>} } export function updateMiniMetadataLocalAction(miniId: string, metadata: DriveMetadata<void, MiniProperties>): UpdateMiniMetadataLocalActionType { return {type: ScenarioReducerActionTypes.UPDATE_MINI_ACTION, miniId, mini: {metadata: {...metadata, properties: castMiniProperties(metadata.properties)}}}; } interface ReplaceMetadataAction extends ScenarioAction { type: ScenarioReducerActionTypes.REPLACE_METADATA_ACTION; oldMetadataId: string; newMetadataId: string; } export function replaceMetadataAction(oldMetadataId: string, newMetadataId: string, gmOnly: boolean): GToveThunk<ReplaceMetadataAction> { return populateScenarioActionThunk({type: ScenarioReducerActionTypes.REPLACE_METADATA_ACTION, oldMetadataId, newMetadataId, peerKey: 'replaceMetadata' + oldMetadataId, gmOnly}); } interface ReplaceMapImageAction extends ScenarioAction { type: ScenarioReducerActionTypes.REPLACE_MAP_IMAGE_ACTION; mapId: string; newMetadataId: string; gmOnly: boolean; } export function replaceMapImageAction(mapId: string, newMetadataId: string, gmOnly: boolean): GToveThunk<ReplaceMapImageAction> { return populateScenarioActionThunk({type: ScenarioReducerActionTypes.REPLACE_MAP_IMAGE_ACTION, mapId, newMetadataId, peerKey: 'replaceMap' + mapId, gmOnly}); } interface UpdateHeadActionIdsAction extends Action { type: ScenarioReducerActionTypes.UPDATE_HEAD_ACTION_IDS; subtractActionIds: string[]; addActionId: string; gmOnly: boolean; } export function updateHeadActionIdsAction(action: ScenarioAction): UpdateHeadActionIdsAction { return { type: ScenarioReducerActionTypes.UPDATE_HEAD_ACTION_IDS, subtractActionIds: action.headActionIds, addActionId: action.actionId, gmOnly: action.gmOnly }; } export type ScenarioReducerActionType = UpdateSnapToGridActionType | UpdateConfirmMovesActionType | RemoveMapActionType | UpdateMapActionType | RemoveMiniActionType | UpdateMiniActionType; // =========================== Utility functions function getCurrentPositionWaypoint(state: MiniType, updated?: Partial<MiniType>): MovementPathPoint { const position = (updated && updated.position) || state.position; const elevation = (updated && updated.elevation) || state.elevation; const onMapId = (updated && updated.onMapId) || state.onMapId; return {...position, onMapId, elevation}; } function buildUpdatedHeadActionIds(headActionIds: string[], subtractActions: string[], addAction: string) { const subtracted = headActionIds .filter((actionId) => (subtractActions.indexOf(actionId) < 0)); return subtracted.concat(addAction).sort(); } // =========================== Reducers const ORIGIN = {x: 0, y: 0, z: 0}; const ROTATION_NONE = {x: 0, y: 0, z: 0, order: 'XYZ'}; const initialMapState: MapType = { position: ORIGIN, rotation: ROTATION_NONE, gmOnly: true, name: 'New Map', selectedBy: null, paintLayers: [], transparent: false, metadata: undefined as any }; function snapToGridReducer(state: boolean = false, action: ScenarioReducerActionType) { switch (action.type) { case ScenarioReducerActionTypes.UPDATE_SNAP_TO_GRID_ACTION: return action.snapToGrid; default: return state; } } function confirmMovesReducer(state: boolean = false, action: UpdateConfirmMovesActionType) { switch (action.type) { case ScenarioReducerActionTypes.UPDATE_CONFIRM_MOVES_ACTION: return action.confirmMoves; default: return state; } } function singleMapReducer(state: MapType, action: UpdateMapActionType) { switch (action.type) { case ScenarioReducerActionTypes.UPDATE_MAP_ACTION: return {...state, ...action.map}; default: return state; } } const allMapsReducer = objectMapReducer<MapType>('mapId', singleMapReducer as Reducer<MapType>, {deleteActionType: ScenarioReducerActionTypes.REMOVE_MAP_ACTION}); function allMapsFileUpdateReducer(state: {[key: string]: MapType} = {}, action: AnyAction) { switch (action.type) { case ConnectedUserActionTypes.REMOVE_CONNECTED_USER: // Unselect any maps selected by removed peerId return Object.keys(state).reduce<{[key: string]: MapType} | undefined>((all, id) => { if (state[id].selectedBy === action.peerId) { all = all || {...state}; all[id] = {...state[id], selectedBy: null}; } return all; }, undefined) || state; case FileIndexActionTypes.UPDATE_FILE_ACTION: const updateFile = action as UpdateFileActionType<void, MapProperties>; return updateMetadata(state, updateFile.metadata.id, updateFile.metadata, true, castMapProperties); case ScenarioReducerActionTypes.REPLACE_METADATA_ACTION: const replaceMetadata = action as ReplaceMetadataAction; return updateMetadata(state, replaceMetadata.oldMetadataId, {id: replaceMetadata.newMetadataId}, false, castMapProperties); case ScenarioReducerActionTypes.REPLACE_MAP_IMAGE_ACTION: const replaceMapImage = action as ReplaceMapImageAction; return { ...state, [replaceMapImage.mapId]: { ...state[replaceMapImage.mapId], metadata: {id: replaceMapImage.newMetadataId} as any } }; case FileIndexActionTypes.REMOVE_FILE_ACTION: return removeObjectsReferringToMetadata(state, action as RemoveFilesActionType); default: return allMapsReducer(state, action); } } function validateMiniState(fromAction: Partial<MiniType>, state?: MiniType): boolean { // Verify that the combined state has everything we need to render the mini return ( ((state && state.position) || fromAction.position) && ((state && state.rotation) || fromAction.rotation) && ((state && state.metadata) || fromAction.metadata) && ((state && !isNaN(state.elevation)) || fromAction.elevation !== undefined) ) || false; } const singleMiniReducer: Reducer<MiniType> = (state, action) => { switch (action.type) { case ScenarioReducerActionTypes.UPDATE_MINI_ACTION: if (validateMiniState(action.mini, state)) { // Avoid race condition where minis can be partially created return {...state, ...action.mini}; } else { return state; } case ScenarioReducerActionTypes.REMOVE_MINI_ACTION: if (state && state.attachMiniId === action.miniId) { const remove = action as RemoveMiniActionType; // Since mini is being detached, calculate its new absolute position based on the position of the one being removed, if available. const position = (remove.positionObj && remove.rotationObj) ? vector3ToObject(buildVector3(state.position).applyEuler(buildEuler(remove.rotationObj)).add(remove.positionObj as THREE.Vector3)) : state.position; const rotation = remove.rotationObj ? {x: state.rotation.x + remove.rotationObj.x, y: state.rotation.y + remove.rotationObj.y, z: state.rotation.z + remove.rotationObj.z, order: state.rotation.order} : state.rotation; const elevation = state.elevation + (remove.elevation || 0); return { ...state, attachMiniId: undefined, position, rotation, elevation }; } else { return state; } default: return state; } }; const allMinisReducer = objectMapReducer<MiniType>('miniId', singleMiniReducer, {deleteActionType: ScenarioReducerActionTypes.REMOVE_MINI_ACTION, reduceDeleteActionOnAll: true}); function updateAllKeys<T>(state: {[key: string]: T}, action: AnyAction, update: (item: T, action: AnyAction) => T | undefined): {[key: string]: T} { return Object.keys(state).reduce<{[key: string]: T} | undefined>((all, id) => { const updatedItem = update(state[id], action); if (updatedItem) { all = all || {...state}; all[id] = updatedItem; } return all; }, undefined) || state; } const allMinisBatchUpdateReducer: Reducer<{[key: string]: MiniType}> = (state = {}, action) => { switch (action.type) { case ConnectedUserActionTypes.REMOVE_CONNECTED_USER: // Unselect any minis selected by removed peerId return updateAllKeys(state, action, (mini, action) => ( (mini.selectedBy === action.peerId) ? {...mini, selectedBy: null} : undefined )); case FileIndexActionTypes.UPDATE_FILE_ACTION: const updateFile = action as UpdateFileActionType<void, MiniProperties>; return updateMetadata(state, updateFile.metadata.id, updateFile.metadata, true, castMiniProperties); case ScenarioReducerActionTypes.REPLACE_METADATA_ACTION: const replaceMetadata = action as ReplaceMetadataAction; return updateMetadata(state, replaceMetadata.oldMetadataId, {id: replaceMetadata.newMetadataId}, false, castMiniProperties); case FileIndexActionTypes.REMOVE_FILE_ACTION: return removeObjectsReferringToMetadata(state, action as RemoveFilesActionType); case ScenarioReducerActionTypes.UPDATE_CONFIRM_MOVES_ACTION: return Object.keys(state).reduce((nextState, miniId) => { const miniState = state[miniId]; nextState[miniId] = {...miniState, movementPath: action.confirmMoves ? [getCurrentPositionWaypoint(miniState)] : undefined}; return nextState; }, {}); case ScenarioReducerActionTypes.ADJUST_MINIS_ON_MAP_ACTION: return Object.keys(state).reduce<undefined | {[key: string]: MiniType}>((nextState, miniId) => { const miniState = state[miniId]; if (miniState.onMapId === action.mapId && (miniState.gmOnly || !action.gmOnly) && !miniState.attachMiniId) { nextState = nextState || {...state}; const position = buildVector3(miniState.position); if (action.deltaRotation) { position.sub(action.oldCentre).applyEuler(new THREE.Euler(0, action.deltaRotation, 0)).add(action.newCentre); } if (action.deltaPosition) { position.add(action.deltaPosition); } nextState[miniId] = { ...miniState, position: vector3ToObject(position), rotation: action.deltaRotation ? {...miniState.rotation, y: miniState.rotation.y + action.deltaRotation} : miniState.rotation }; } return nextState; }, undefined) || state; case TabletopReducerActionTypes.UPDATE_TABLETOP_ACTION: // If the pieces roster columns are updated, clean up piecesRosterValues and piecesRosterGMValues to contain // only values for columns that still exist. Also, data may need to move from player to GM or vice versa. const piecesRosterColumns: PiecesRosterColumn[] = action.tabletop.piecesRosterColumns; if (piecesRosterColumns) { const playerColumnIds = piecesRosterColumns.filter((column) => (!column.gmOnly)).map((column) => (column.id)); const gmColumnIds = piecesRosterColumns.filter((column) => (column.gmOnly)).map((column) => (column.id)); return Object.keys(state).reduce((all, miniId) => { const combinedValues = {...state[miniId].piecesRosterValues, ...state[miniId].piecesRosterGMValues}; all[miniId] = { ...state[miniId], piecesRosterValues: pick(combinedValues, playerColumnIds), piecesRosterGMValues: pick(combinedValues, gmColumnIds) }; return all; }, {}); } return state; default: return allMinisReducer(state, action); } }; const headActionIdReducer: Reducer<string[]> = (state = [], action) => { if (action.type === ScenarioReducerActionTypes.UPDATE_HEAD_ACTION_IDS) { return buildUpdatedHeadActionIds(state, action.subtractActionIds, action.addActionId); } else { return state; } }; const playerHeadActionIdReducer: Reducer<string[]> = (state = [], action) => { if (action.type === ScenarioReducerActionTypes.UPDATE_HEAD_ACTION_IDS && !action.gmOnly) { return buildUpdatedHeadActionIds(state, action.subtractActionIds, action.addActionId); } else { return state; } }; const scenarioReducer = combineReducers<ScenarioType>({ snapToGrid: snapToGridReducer, confirmMoves: confirmMovesReducer, startCameraAtOrigin: (state = false) => (state), maps: allMapsFileUpdateReducer, minis: allMinisBatchUpdateReducer, headActionIds: headActionIdReducer, playerHeadActionIds: playerHeadActionIdReducer }); export const settableScenarioReducer: Reducer<ScenarioType> = (state, action) => { switch (action.type) { case ScenarioReducerActionTypes.SET_SCENARIO_ACTION: case ScenarioReducerActionTypes.SET_SCENARIO_LOCAL_ACTION: return scenarioReducer(action.scenario, action); case ScenarioReducerActionTypes.APPEND_SCENARIO_ACTION: return scenarioReducer({ ...state, maps: {...(state && state.maps), ...action.scenario.maps}, minis: {...(state && state.minis), ...action.scenario.minis} } as any, action); case ScenarioReducerActionTypes.UPDATE_MAP_ACTION: // This is a hack - reduce a fake action which will adjust the positions/rotations of minis on a map whose // position/rotation changes. The allMinisBatchUpdateReducer function can't just use the UPDATE_MAP_ACTION // directly, since adjusting the minis on the map requires information that isn't available down in the // minis state. if ((action.map.position || action.map.rotation) && state && state.maps[action.mapId]) { const oldMap = state.maps[action.mapId]; const {positionObj: oldPosition, rotationObj: oldRotation} = snapMap(state.snapToGrid, oldMap.metadata.properties, oldMap.position, oldMap.rotation); const newState = scenarioReducer(state, action); const newMap = newState.maps[action.mapId]; const {positionObj: newPosition, rotationObj: newRotation} = snapMap(newState.snapToGrid, newMap.metadata.properties, newMap.position, newMap.rotation); const deltaPosition = action.map.position ? buildVector3(newPosition).sub(oldPosition as THREE.Vector3) : undefined; const deltaRotation = action.map.rotation ? newRotation.y - oldRotation.y : undefined; const {mapDX, mapDZ} = getMapCentreOffsets(state.snapToGrid, oldMap.metadata.properties); const oldCos = Math.cos(+oldRotation.y); const oldSin = Math.sin(+oldRotation.y); const oldCentre = {...oldPosition, x: oldPosition.x - oldCos * mapDX - oldSin * mapDZ, z: oldPosition.z - oldCos * mapDZ + oldSin * mapDX}; const newCos = Math.cos(+newRotation.y); const newSin = Math.sin(+newRotation.y); const newCentre = {...newPosition, x: newPosition.x - newCos * mapDX - newSin * mapDZ, z: newPosition.z - newCos * mapDZ + newSin * mapDX}; const fakeAction = updateMinisOnMapAction(action.mapId, oldMap.gmOnly, oldCentre, newCentre, deltaPosition, deltaRotation); return scenarioReducer(scenarioReducer(state, fakeAction), action); } return scenarioReducer(state, action); default: return scenarioReducer(state, action); } }; export default settableScenarioReducer; // =========================== Utility interface GetGmOnlyParams { getState: () => ReduxStoreType; mapId?: string | null; miniId?: string | null; } function getGmOnly({getState, mapId = null, miniId = null}: GetGmOnlyParams): boolean { const scenario = getScenarioFromStore(getState()); if (mapId) { return scenario.maps[mapId].gmOnly; } else if (miniId) { return scenario.minis[miniId].gmOnly; } else { return false; } } function updateMetadata(state: {[key: string]: MapType}, metadataId: string, metadata: Partial<DriveMetadata<void, MapProperties>>, merge: boolean, convert: (properties: MapProperties) => MapProperties): {[key: string]: MapType}; function updateMetadata(state: {[key: string]: MiniType}, metadataId: string, metadata: Partial<DriveMetadata<void, MiniProperties | TemplateProperties>>, merge: boolean, convert: (properties: MiniProperties | TemplateProperties) => MiniProperties | TemplateProperties): {[key: string]: MiniType}; function updateMetadata<T extends MapType | MiniType>(state: {[key: string]: T}, metadataId: string, metadata: Partial<DriveMetadata<void, ScenarioObjectProperties>>, merge: boolean, convert: (properties: any) => any): {[key: string]: T} { // Have to search for matching metadata in all objects in state. return Object.keys(state).reduce((result: {[key: string]: T} | undefined, id) => { if (state[id].metadata && state[id].metadata.id === metadataId) { result = result || {...state}; result[id] = Object.assign({}, result[id], {metadata: {...(merge && result[id].metadata), ...metadata, properties: convert(metadata.properties)}}); } return result; }, undefined) || state; } const removeObjectsReferringToMetadata = <T extends MapType | MiniType>(state: {[key: string]: T}, action: RemoveFilesActionType): {[key: string]: T} => { // Remove any objects that reference the metadata return Object.keys(state).reduce((result: {[key: string]: T} | undefined, id) => { if (state[id].metadata && state[id].metadata.id === action.file.id) { result = result || {...state}; delete(result[id]); } return result; }, undefined) || state; }; // ================== Utility functions to assist with undo/redo functionality ================== export const UNDO_ACTION_TYPE = 'gtove-undo'; export const REDO_ACTION_TYPE = 'gtove-redo'; export const SEPARATE_UNDO_GROUP_ACTION_TYPE = 'separate-undo-group-action-type'; export interface UndoRedoAction extends ScenarioAction { } export function undoAction(): GToveThunk<UndoRedoAction> { return (dispatch, getState) => { const history = getUndoableHistoryFromStore(getState()); if (history.past.length > 0) { const toScenario = history.past[history.past.length - 1].scenario; if (toScenario) { dispatch(populateScenarioAction<UndoRedoAction>({type: UNDO_ACTION_TYPE, peerKey: v4()}, getState)); const [, playerScenario] = scenarioToJson(toScenario); dispatch(setScenarioAction(playerScenario, 'undo', false, true) as any); } } }; } export function redoAction(): GToveThunk<UndoRedoAction> { return (dispatch, getState) => { const history = getUndoableHistoryFromStore(getState()); if (history.future.length > 0) { const toScenario = history.future[0].scenario; if (toScenario) { dispatch(populateScenarioAction<UndoRedoAction>({type: REDO_ACTION_TYPE, peerKey: v4()}, getState)); const [, playerScenario] = scenarioToJson(toScenario); dispatch(setScenarioAction(playerScenario, 'redo', false, true) as any); } } }; } interface SeparateUndoGroupActionType extends Action { } export function separateUndoGroupAction(): SeparateUndoGroupActionType { return {type: SEPARATE_UNDO_GROUP_ACTION_TYPE}; } export function undoGroupAction<A extends Action>(action: A, undoGroupId: string | null): A { return {...action, undoGroupId}; } export function undoGroupThunk<A extends Action>(thunk: GToveThunk<A>, undoGroupId = v4()): GToveThunk<A> { return (baseDispatch: (action: A) => A, getState: () => ReduxStoreType) => { const wrappedDispatch = (action: A) => { if (typeof(action) === 'function') { return undoGroupThunk(action, undoGroupId)(baseDispatch as any, getState); } else { baseDispatch({...action, undoGroupId}); return action; } }; return thunk(wrappedDispatch as any, getState); }; } export function undoGroupActionList<T = Action<string> | GToveThunk<Action<string>>>(actions: T[], undoGroupId?: string) { return !undoGroupId ? actions : actions.map((action: any) => ( typeof(action) === 'function' ? undoGroupThunk(action, undoGroupId) : undoGroupAction(action, undoGroupId) )); } export const scenarioUndoGroupBy: GroupByFunction = (action, state, history) => ( action.undoGroupId ? action.undoGroupId : action.peerKey ); export const scenarioUndoFilter = (action: AnyAction) => { switch (action.type) { case TabletopReducerActionTypes.UPDATE_TABLETOP_ACTION: // Tabletop update actions are "scenario actions", but tabletop is not in undoableState return false; case ScenarioReducerActionTypes.SET_SCENARIO_LOCAL_ACTION: return true; default: return isScenarioAction(action) && action.peerKey !== undefined; } };
the_stack
import { EventEmitter } from "events"; import { combine } from "pvtsutils"; import { INFO_RATCHET, INFO_TEXT, MAX_RATCHET_STACK_SIZE } from "./const"; import { Curve, ECPublicKey, IECKeyPair, Secret } from "./crypto"; import { Identity } from "./data"; import { RemoteIdentity } from "./data/remote_identity"; import { MessageSignedProtocol, PreKeyBundleProtocol, PreKeyMessageProtocol } from "./protocol"; import { Stack } from "./stack"; import { ReceivingRatchet, SendingRatchet } from "./sym_ratchet"; import { IJsonReceivingRatchet, IJsonSymmetricRatchet } from "./sym_ratchet"; import { IJsonSerializable } from "./type"; import { ECDHPrivateKey, HMACCryptoKey } from "./type"; /** * Authentication. Calculates rootKey for DH ratchet * * https://whispersystems.org/docs/specifications/x3dh/#sending-the-initial-message * * @static * @param {boolean} flag Sets order for auth mechanism. * - If `true` then DH1 || DH2, otherwise DH2 || DH1 * @param {Identity} IKA * @param {IECKeyPair} EKA * @param {RemoteIdentity} IKB Bob's identity key IKB * @param {ECPublicKey} SPKB Bob's signed prekey SPKB * @param {ECPublicKey} [OPKB] Bob's one-time prekey OPKB. Optionally * */ async function authenticateA( IKa: Identity, EKa: IECKeyPair, IKb: ECPublicKey, SPKb: ECPublicKey, OPKb?: ECPublicKey, ) { /** * If the bundle does not contain a one-time PreKey * * DH1 = DH(IKa, SPKb) * DH2 = DH(EKa, IKb) * DH3 = DH(EKa, SPKb) * SK = KDF(DH1 || DH2 || DH3) */ const DH1 = await Curve.deriveBytes(IKa.exchangeKey.privateKey, SPKb); const DH2 = await Curve.deriveBytes(EKa.privateKey, IKb); const DH3 = await Curve.deriveBytes(EKa.privateKey, SPKb); let DH4 = new ArrayBuffer(0); if (OPKb) { /** * If the bundle does contain a one-time PreKey, * the calculation is modified to include an additional DH * * DH4 = DH(EKA, OPKB) * SK = KDF(DH1 || DH2 || DH3 || DH4) */ DH4 = await Curve.deriveBytes(EKa.privateKey, OPKb); } const _F = new Uint8Array(32); for (let i = 0; i < _F.length; i++) { _F[i] = 0xff; } const F = _F.buffer as ArrayBuffer; const KM = combine(F, DH1, DH2, DH3, DH4); // TODO: F || KM, where F = 0xFF * N const keys = await Secret.HKDF(KM, 1, void 0, INFO_TEXT); return await Secret.importHMAC(keys[0]); } async function authenticateB( IKb: Identity, SPKb: IECKeyPair, IKa: ECPublicKey, EKa: ECPublicKey, OPKb?: ECDHPrivateKey, ) { /** * If the bundle does not contain a one-time PreKey * * DH1 = DH(IKa, SPKb) * DH2 = DH(EKa, IKb) * DH3 = DH(EKa, SPKb) * SK = KDF(DH1 || DH2 || DH3) */ const DH1 = await Curve.deriveBytes(SPKb.privateKey, IKa); const DH2 = await Curve.deriveBytes(IKb.exchangeKey.privateKey, EKa); const DH3 = await Curve.deriveBytes(SPKb.privateKey, EKa); let DH4 = new ArrayBuffer(0); if (OPKb) { /** * If the bundle does contain a one-time PreKey, * the calculation is modified to include an additional DH * * DH4 = DH(EKA, OPKB) * SK = KDF(DH1 || DH2 || DH3 || DH4) */ DH4 = await Curve.deriveBytes(OPKb, EKa); } const _F = new Uint8Array(32); for (let i = 0; i < _F.length; i++) { _F[i] = 0xff; } const F = _F.buffer as ArrayBuffer; const KM = combine(F, DH1, DH2, DH3, DH4); // TODO: F || KM, where F = 0xFF * N const keys = await Secret.HKDF(KM, 1, void 0, INFO_TEXT); return await Secret.importHMAC(keys[0]); } export interface IJsonAsymmetricRatchet { remoteIdentity: string; ratchetKey: CryptoKeyPair; counter: number; rootKey: CryptoKey; steps: IJsonDHRatchetStep[]; } export interface IAsymmetricRatchetOptions { exportableKeys?: boolean; } /** * Implementation Diffie-Hellman ratchet * https://whispersystems.org/docs/specifications/doubleratchet/#diffie-hellman-ratchet * * @export * @class AsymmetricRatchet */ export class AsymmetricRatchet extends EventEmitter implements IJsonSerializable { /** * Creates new ratchet for given identity from PreKeyBundle or PreKey messages * * @static * @param {Identity} identity * @param {(PreKeyBundleProtocol | PreKeyMessageProtocol)} protocol * @returns * * @memberOf AsymmetricRatchet */ public static async create( identity: Identity, protocol: PreKeyBundleProtocol | PreKeyMessageProtocol, options: IAsymmetricRatchetOptions = {}) { let rootKey: HMACCryptoKey; const ratchet = new AsymmetricRatchet(options); if (protocol instanceof PreKeyBundleProtocol) { // PreKey Bundle // verify remote identity key if (!await protocol.identity.verify()) { throw new Error("Error: Remote client's identity key is invalid."); } // verify remote signed prekey if (!await protocol.preKeySigned.verify(protocol.identity.signingKey)) { throw new Error("Error: Remote client's signed prekey is invalid."); } ratchet.currentRatchetKey = await ratchet.generateRatchetKey(); ratchet.currentStep.remoteRatchetKey = protocol.preKeySigned.key; ratchet.remoteIdentity = RemoteIdentity.fill(protocol.identity); ratchet.remoteIdentity.id = protocol.registrationId; ratchet.remotePreKeyId = protocol.preKey.id; ratchet.remotePreKeySignedId = protocol.preKeySigned.id; rootKey = await authenticateA( identity, ratchet.currentRatchetKey, protocol.identity.exchangeKey, protocol.preKeySigned.key, protocol.preKey.key); } else { // PreKey Message // verify remote identity if (!await protocol.identity.verify()) { throw new Error("Error: Remote client's identity key is invalid."); // INFO: We can move THROW to verify function. Cause verification is critical. } // get signed prekey for identity const signedPreKey = identity.signedPreKeys[protocol.preKeySignedId]; if (!signedPreKey) { throw new Error(`Error: PreKey with id ${protocol.preKeySignedId} not found`); } // get one-time prekey let preKey: IECKeyPair | undefined; if (protocol.preKeyId !== void 0) { preKey = identity.preKeys[protocol.preKeyId]; } ratchet.remoteIdentity = RemoteIdentity.fill(protocol.identity); ratchet.currentRatchetKey = signedPreKey; rootKey = await authenticateB( identity, ratchet.currentRatchetKey, protocol.identity.exchangeKey, protocol.signedMessage.message.senderRatchetKey, preKey && preKey.privateKey, ); } // console.info(`${this.name}:Create Diffie-Hellman ratchet for ${identity.id}`); ratchet.identity = identity; ratchet.id = identity.id; ratchet.rootKey = rootKey; return ratchet; } public static async fromJSON(identity: Identity, remote: RemoteIdentity, obj: IJsonAsymmetricRatchet) { const res = new AsymmetricRatchet(); res.identity = identity; res.remoteIdentity = remote; await res.fromJSON(obj); return res; } public id: number; public rootKey: HMACCryptoKey; public identity: Identity; public remoteIdentity: RemoteIdentity; public remotePreKeyId?: number; public remotePreKeySignedId: number; public counter = 0; public currentStep = new DHRatchetStep(); public currentRatchetKey: IECKeyPair; protected steps = new DHRatchetStepStack(MAX_RATCHET_STACK_SIZE); protected promises: { [key: string]: Promise<any> } = {}; protected constructor(public options: IAsymmetricRatchetOptions = {}) { super(); } public on(event: "update", listener: () => void): this; public on(event: string | symbol, listener: (...args: any[]) => void) { return super.on(event, listener); } public once(event: "update", listener: () => void): this; public once(event: string | symbol, listener: (...args: any[]) => void) { return super.once(event, listener); } /** * Verifies and decrypts data from SignedMessage * * @param {MessageSignedProtocol} protocol * @returns * * @memberOf AsymmetricRatchet */ public async decrypt(protocol: MessageSignedProtocol) { // console.info(`${this.constructor.name}:Decrypts message`); return this.queuePromise("encrypt", async () => { const remoteRatchetKey = protocol.message.senderRatchetKey; const message = protocol.message; if (protocol.message.previousCounter < this.counter - MAX_RATCHET_STACK_SIZE) { throw new Error("Error: Too old message"); } let step = this.steps.getStep(remoteRatchetKey); if (!step) { // We ve got new ratchet key, creating new ReceivingChain const ratchetStep = new DHRatchetStep(); ratchetStep.remoteRatchetKey = remoteRatchetKey; this.steps.push(ratchetStep); this.currentStep = ratchetStep; step = ratchetStep; } if (!step.receivingChain) { // got 1 message for current ratchet step, have to create ReceiverRatchet step.receivingChain = await this.createChain( this.currentRatchetKey.privateKey, remoteRatchetKey, ReceivingRatchet, ); } const decryptedMessage = await step.receivingChain.decrypt(message.cipherText, message.counter); this.update(); // verifying message signature protocol.senderKey = this.remoteIdentity.signingKey; protocol.receiverKey = this.identity.signingKey.publicKey; if (!await protocol.verify(decryptedMessage.hmacKey)) { throw new Error("Error: The Message did not successfully verify!"); } return decryptedMessage.cipherText; }); } /** * Encrypts message * * @param {ArrayBuffer} message * @returns * * @memberOf AsymmetricRatchet */ public async encrypt(message: ArrayBuffer) { // console.info(`${this.constructor.name}:Encrypts message`); return this.queuePromise("encrypt", async () => { if (this.currentStep.receivingChain && !this.currentStep.sendingChain) { // close ratchet step this.counter++; this.currentRatchetKey = await this.generateRatchetKey(); } // if false then no incoming message with new ratchet key, using old DH ratchet if (!this.currentStep.sendingChain) { if (!this.currentStep.remoteRatchetKey) { throw new Error("currentStep has empty remoteRatchetKey"); } this.currentStep.sendingChain = await this.createChain( this.currentRatchetKey.privateKey, this.currentStep.remoteRatchetKey, SendingRatchet, ); } const encryptedMessage = await this.currentStep.sendingChain.encrypt(message); this.update(); let preKeyMessage: PreKeyMessageProtocol | undefined; if (this.steps.length === 0 && !this.currentStep.receivingChain && this.currentStep.sendingChain.counter === 1 ) { // we send first message, MUST be PreKey message, otherwise SignedMessage preKeyMessage = new PreKeyMessageProtocol(); preKeyMessage.registrationId = this.identity.id; preKeyMessage.preKeyId = this.remotePreKeyId; preKeyMessage.preKeySignedId = this.remotePreKeySignedId; preKeyMessage.baseKey = this.currentRatchetKey.publicKey; await preKeyMessage.identity.fill(this.identity); } const signedMessage = new MessageSignedProtocol(); signedMessage.receiverKey = this.remoteIdentity.signingKey; signedMessage.senderKey = this.identity.signingKey.publicKey; // message signedMessage.message.cipherText = encryptedMessage.cipherText; signedMessage.message.counter = this.currentStep.sendingChain.counter - 1; signedMessage.message.previousCounter = this.counter; signedMessage.message.senderRatchetKey = this.currentRatchetKey.publicKey; await signedMessage.sign(encryptedMessage.hmacKey); if (preKeyMessage) { preKeyMessage.signedMessage = signedMessage; return preKeyMessage; } else { return signedMessage; } }); } public async hasRatchetKey(key: CryptoKey | ECPublicKey) { let ecKey: ECPublicKey; if (!(key instanceof ECPublicKey)) { ecKey = await ECPublicKey.create(key); } else { ecKey = key; } for (const item of this.steps.items) { if (await item.remoteRatchetKey!.isEqual(ecKey)) { return true; } } return false; } public async toJSON() { return { counter: this.counter, ratchetKey: await Curve.ecKeyPairToJson(this.currentRatchetKey), remoteIdentity: await this.remoteIdentity.signingKey.thumbprint(), rootKey: this.rootKey, steps: await this.steps.toJSON(), } as IJsonAsymmetricRatchet; } public async fromJSON(obj: IJsonAsymmetricRatchet) { this.currentRatchetKey = await Curve.ecKeyPairFromJson(obj.ratchetKey); this.counter = obj.counter; this.rootKey = obj.rootKey; for (const step of obj.steps) { this.currentStep = await DHRatchetStep.fromJSON(step); this.steps.push(this.currentStep); } } protected update() { this.emit("update"); } /** * Generate new ratchet key * * @protected * @returns * * @memberOf AsymmetricRatchet */ protected generateRatchetKey() { return Curve.generateKeyPair("ECDH", !!this.options.exportableKeys); } /** * Creates new symmetric ratchet * * @protected * @param {ECDHPrivateKey} ourRatchetKey * @param {ECPublicKey} theirRatchetKey * @param {typeof ReceivingRatchet} ratchetClass * @returns {Promise<ReceivingRatchet>} * * @memberOf AsymmetricRatchet */ // tslint:disable-next-line:max-line-length protected async createChain(ourRatchetKey: ECDHPrivateKey, theirRatchetKey: ECPublicKey, ratchetClass: typeof ReceivingRatchet): Promise<ReceivingRatchet>; // tslint:disable-next-line:max-line-length protected async createChain(ourRatchetKey: ECDHPrivateKey, theirRatchetKey: ECPublicKey, ratchetClass: typeof SendingRatchet): Promise<SendingRatchet>; // tslint:disable-next-line:max-line-length protected async createChain(ourRatchetKey: ECDHPrivateKey, theirRatchetKey: ECPublicKey, ratchetClass: typeof ReceivingRatchet | typeof SendingRatchet) { // console.info(`${this.constructor.name}:${this.id}:Creating new ${ratchetClass.name}`); const derivedBytes = await Curve.deriveBytes(ourRatchetKey, theirRatchetKey); const keys = await Secret.HKDF(derivedBytes, 2, this.rootKey, INFO_RATCHET); const rootKey = await Secret.importHMAC(keys[0]); const chainKey = await Secret.importHMAC(keys[1]); const chain = new ratchetClass(chainKey); this.rootKey = rootKey; // update rootKey return chain; } protected queuePromise<T>(key: string, fn: () => Promise<T>): Promise<T> { const prev = this.promises[key] || Promise.resolve(); const cur = this.promises[key] = prev.then(fn, fn); cur.then(() => { if (this.promises[key] === cur) { delete this.promises[key]; } }); return cur; } } export interface IJsonDHRatchetStep { remoteRatchetKey?: CryptoKey; sendingChain?: IJsonSymmetricRatchet; receivingChain?: IJsonReceivingRatchet; } /** * Implementation of step of the Diffie-Hellman ratchet * * @export * @class DHRatchetStep */ export class DHRatchetStep implements IJsonSerializable { public static async fromJSON(obj: IJsonDHRatchetStep) { const res = new this(); await res.fromJSON(obj); return res; } /** * Remote client's ratchet key * * @type {ECPublicKey} * @memberOf DHRatchetStep */ public remoteRatchetKey?: ECPublicKey; /** * Sending chain * * @type {SendingRatchet} * @memberOf DHRatchetStep */ public sendingChain?: SendingRatchet; /** * Receiving chain * * @type {ReceivingRatchet} * @memberOf DHRatchetStep */ public receivingChain?: ReceivingRatchet; public async toJSON() { const res: IJsonDHRatchetStep = {}; if (this.remoteRatchetKey) { res.remoteRatchetKey = this.remoteRatchetKey.key; } if (this.sendingChain) { res.sendingChain = await this.sendingChain.toJSON(); } if (this.receivingChain) { res.receivingChain = await this.receivingChain.toJSON(); } return res; } public async fromJSON(obj: IJsonDHRatchetStep) { if (obj.remoteRatchetKey) { this.remoteRatchetKey = await ECPublicKey.create(obj.remoteRatchetKey); } if (obj.sendingChain) { this.sendingChain = await SendingRatchet.fromJSON(obj.sendingChain); } if (obj.receivingChain) { this.receivingChain = await ReceivingRatchet.fromJSON(obj.receivingChain); } } } /** * Implements collection of DHRatchetStep * * @export * @class DHRatchetStepStack * @extends {Stack<DHRatchetStep>} */ export class DHRatchetStepStack extends Stack<DHRatchetStep> { /** * Returns DHRatchetStep by given remote client's ratchet key * @param {ECPublicKey} remoteRatchetKey remote client's ratchet key * @returns * * @memberOf DHRatchetStepStack */ public getStep(remoteRatchetKey: ECPublicKey) { let found: DHRatchetStep | undefined; this.items.some((step) => { if (step.remoteRatchetKey!.id === remoteRatchetKey.id) { found = step; } return !!found; }); return found; } }
the_stack
import type { Readable } from 'readable-stream' import type { Authenticator, HttpMethod, ITransportSettings, SDKResponse, Values, } from './transport' import { agentPrefix, sdkOk } from './transport' import type { IAuthSession } from './authSession' /** * Creates an "sdk" to be used with the TypeScript SDK's funcs.ts file * @param authSession authentication session * @param apiVersion version of API to use (e.g. "3.1" or "4.0") * @param sdkVersion Looker release version (e.g. "21.4") */ export const functionalSdk = ( authSession: IAuthSession, apiVersion: string, sdkVersion: string ) => { const sdk = new APIMethods(authSession, sdkVersion) sdk.apiVersion = apiVersion sdk.apiPath = authSession.settings.base_url === '' ? '' : authSession.settings.base_url + '/api/' + apiVersion return sdk } export interface IAPIMethods { authSession: IAuthSession sdkVersion: string apiPath: string apiVersion: string /** A helper method for simplifying error handling of SDK responses. * * Pass in a promise returned by any SDK method, and it will return a promise * that rejects if the `SDKResponse` is not `ok`. This will swallow the type * information in the error case, but allows you to route all the error cases * into a single promise rejection. * * The promise will have an `Error` rejection reason with a string `message`. * If the server error contains a `message` field, it will be provided, otherwise a * generic message will occur. * * ```ts * const sdk = LookerSDK({...}) * let look * try { * look = await sdk.ok(sdk.create_look({...})) * // do something with look * } * catch(e) { * // handle error case * } * ``` */ ok<TSuccess, TError>( promise: Promise<SDKResponse<TSuccess, TError>> ): Promise<TSuccess> /** * Determine whether the url should be an API path, relative from base_url, or is already fully specified override * @param path Request path * @param options Transport settings * @param authenticator optional callback * @returns the fully specified request path including any query string parameters */ makePath( path: string, options: Partial<ITransportSettings>, authenticator?: Authenticator ): string /** * * A helper method to add authentication to an API request for deserialization * * @param {HttpMethod} method type of HTTP method * @param {string} path API endpoint path * @param {any} queryParams Optional query params collection for request * @param {any} body Optional body for request * @param {Partial<ITransportSettings>} options Optional overrides like timeout and verify_ssl */ authRequest<TSuccess, TError>( method: HttpMethod, path: string, queryParams?: Values, body?: any, options?: Partial<ITransportSettings> ): Promise<SDKResponse<TSuccess, TError>> /** * A helper method to add authentication to an API request for streaming * @param {(readable: Readable) => Promise<T>} callback * @param {HttpMethod} method * @param {string} path * @param queryParams * @param body * @param {Partial<ITransportSettings>} options * @returns {Promise<T>} */ authStream<T>( callback: (readable: Readable) => Promise<T>, method: HttpMethod, path: string, queryParams?: Values, body?: any, options?: Partial<ITransportSettings> ): Promise<T> /** Make a GET request */ get<TSuccess, TError>( path: string, queryParams?: Values, body?: any, options?: Partial<ITransportSettings> ): Promise<SDKResponse<TSuccess, TError>> /** Make a HEAD request */ head<TSuccess, TError>( path: string, queryParams?: Values, body?: any, options?: Partial<ITransportSettings> ): Promise<SDKResponse<TSuccess, TError>> /** Make a DELETE request */ delete<TSuccess, TError>( path: string, queryParams?: Values, body?: any, options?: Partial<ITransportSettings> ): Promise<SDKResponse<TSuccess, TError>> /** Make a POST request */ post<TSuccess, TError>( path: string, queryParams?: Values, body?: any, options?: Partial<ITransportSettings> ): Promise<SDKResponse<TSuccess, TError>> /** Make a PUT request */ put<TSuccess, TError>( path: string, queryParams?: Values, body?: any, options?: Partial<ITransportSettings> ): Promise<SDKResponse<TSuccess, TError>> /** Make a PATCH request */ patch<TSuccess, TError>( path: string, queryParams?: Values, body?: any, options?: Partial<ITransportSettings> ): Promise<SDKResponse<TSuccess, TError>> } export class APIMethods implements IAPIMethods { private _apiPath = '' private _apiVersion = '' /** * Initialize the APIMethods wrapper * @param authSession authentication management session * @param sdkVersion version of the SDK for agent tagging */ constructor(public authSession: IAuthSession, public sdkVersion: string) { if ( !('agentTag' in authSession.settings && authSession.settings.agentTag) ) { // Initialize agentTag if it's not already explicitly set authSession.settings.agentTag = `${agentPrefix} ${sdkVersion}` } } get apiPath() { return this._apiPath } set apiPath(value: string) { if (this._apiPath) { throw new Error( `API Path is set to "${this._apiPath}" and cannot be reassigned` ) } this._apiPath = value } get apiVersion() { return this._apiVersion } set apiVersion(value: string) { // API version can only be set once for the instance if (this._apiVersion) { throw new Error( `API Version is set to "${this._apiVersion}" and cannot be reassigned` ) } this._apiVersion = value } /** A helper method for constructing with a type as a param * * Example: * APIMethods.create(Looker40SDK, authSession) * * @param type * @param authSession */ static create<T extends APIMethods>( type: new (authSession: IAuthSession) => T, authSession: IAuthSession ): T { // eslint-disable-next-line new-cap return new type(authSession) } /** A helper method for simplifying error handling of SDK responses. * * Pass in a promise returned by any SDK method, and it will return a promise * that rejects if the `SDKResponse` is not `ok`. This will swallow the type * information in the error case, but allows you to route all the error cases * into a single promise rejection. * * The promise will have an `Error` rejection reason with a string `message`. * If the server error contains a `message` field, it will be provided, otherwise a * generic message will occur. * * ```ts * const sdk = LookerSDK({...}) * let look * try { * look = await sdk.ok(sdk.create_look({...})) * // do something with look * } * catch(e) { * // handle error case * } * ``` */ async ok<TSuccess, TError>(promise: Promise<SDKResponse<TSuccess, TError>>) { return sdkOk<TSuccess, TError>(promise) } /** * Determine whether the url should be an API path, relative from base_url, or is already fully specified override * @param path Request path * @param options Transport settings * @param authenticator optional callback * @returns the fully specified request path including any query string parameters */ makePath( path: string, options: Partial<ITransportSettings>, authenticator?: Authenticator ) { if (path.match(/^(http:\/\/|https:\/\/)/gi)) return path // is this an API-versioned call? const base = authenticator ? this.apiPath : options.base_url return `${base}${path}` // path was relative } /** * * A helper method to add authentication to an API request for deserialization * * @param {HttpMethod} method type of HTTP method * @param {string} path API endpoint path * @param {any} queryParams Optional query params collection for request * @param {any} body Optional body for request * @param {Partial<ITransportSettings>} options Optional overrides like timeout and verify_ssl */ async authRequest<TSuccess, TError>( method: HttpMethod, path: string, queryParams?: Values, body?: any, options?: Partial<ITransportSettings> ): Promise<SDKResponse<TSuccess, TError>> { options = { ...this.authSession.settings, ...options } const authenticator = (init: any) => { return this.authSession.authenticate(init) } path = this.makePath(path, options, authenticator) return this.authSession.transport.request<TSuccess, TError>( method, path, queryParams, body, authenticator, options ) } /** * A helper method to add authentication to an API request for streaming * @param {(readable: Readable) => Promise<T>} callback * @param {HttpMethod} method * @param {string} path * @param queryParams * @param body * @param {Partial<ITransportSettings>} options * @returns {Promise<T>} */ async authStream<T>( callback: (readable: Readable) => Promise<T>, method: HttpMethod, path: string, queryParams?: Values, body?: any, options?: Partial<ITransportSettings> ): Promise<T> { options = { ...this.authSession.settings, ...options } const authenticator = (init: any) => { return this.authSession.authenticate(init) } path = this.makePath(path, options, authenticator) return this.authSession.transport.stream<T>( callback, method, path, queryParams, body, (init: any) => { return this.authSession.authenticate(init) }, options ) } // // dynamically evaluate a template string // macro(template: string, vars: any) { // // replace {foo} from spec path with ${foo} for template string // template = template.replace(/{/gi, '${') // return new Function('return `+ template +`;').call(vars) // } // // pathify(path: string, pathParams?: any) { // if (!pathParams) return path // if (path.indexOf('{') < 0) return path // return this.macro(path, pathParams) // } /** Make a GET request */ async get<TSuccess, TError>( path: string, queryParams?: Values, body?: any, options?: Partial<ITransportSettings> ): Promise<SDKResponse<TSuccess, TError>> { return this.authRequest<TSuccess, TError>( 'GET', path, queryParams, body, options ) } /** Make a HEAD request */ async head<TSuccess, TError>( path: string, queryParams?: Values, body?: any, options?: Partial<ITransportSettings> ): Promise<SDKResponse<TSuccess, TError>> { return this.authRequest<TSuccess, TError>( 'HEAD', path, queryParams, body, options ) } /** Make a DELETE request */ async delete<TSuccess, TError>( path: string, queryParams?: Values, body?: any, options?: Partial<ITransportSettings> ): Promise<SDKResponse<TSuccess, TError>> { return this.authRequest<TSuccess, TError>( 'DELETE', path, queryParams, body, options ) } /** Make a POST request */ async post<TSuccess, TError>( path: string, queryParams?: Values, body?: any, options?: Partial<ITransportSettings> ): Promise<SDKResponse<TSuccess, TError>> { return this.authRequest<TSuccess, TError>( 'POST', path, queryParams, body, options ) } /** Make a PUT request */ async put<TSuccess, TError>( path: string, queryParams?: Values, body?: any, options?: Partial<ITransportSettings> ): Promise<SDKResponse<TSuccess, TError>> { return this.authRequest<TSuccess, TError>( 'PUT', path, queryParams, body, options ) } /** Make a PATCH request */ async patch<TSuccess, TError>( path: string, queryParams?: Values, body?: any, options?: Partial<ITransportSettings> ): Promise<SDKResponse<TSuccess, TError>> { return this.authRequest<TSuccess, TError>( 'PATCH', path, queryParams, body, options ) } }
the_stack
export declare interface CSSStyleProps { /** * "flex-start" | "flex-end" | "center" | "space-between" | "space-around" | "stretch" */ "align-content"?: string; /** * "flex-start" | "flex-end" | "center" | "baseline" | "stretch" */ "align-items"?: string; /** * "auto" | "flex-start" | "flex-end" | "center" | "baseline" | "stretch" */ "align-self"?: string; "alignment-baseline"?: string; "animation"?: string; "animation-delay"?: string; /** * "normal" | "reverse" | "alternate" | "alternate-reverse" */ "animation-direction"?: string; "animation-duration"?: string; /** * "none" | "forwards" | "backwards" | "both" */ "animation-fill-mode"?: string; "animation-iteration-count"?: string | number; "animation-name"?: string; /** * "running" | "paused" */ "animation-play-state"?: string; "animation-timing-function"?: string; /** * "visible" | "hidden" */ "backface-visibility"?: string; "background"?: string; "background-attachment"?: string; /** * "border-box" | "padding-box" | "content-box" */ "background-clip"?: string; "background-color"?: string; "background-image"?: string; /** * "border-box" | "padding-box" | "content-box" */ "background-origin"?: string; "background-position"?: string; "background-position-x"?: string; "background-position-y"?: string; "background-repeat"?: string; "background-size"?: string; "baseline-shift"?: string; "border"?: number | string; "border-bottom"?: number | string; "border-bottom-color"?: string; "border-bottom-left-radius"?: number | string; "border-bottom-right-radius"?: number | string; "border-bottom-style"?: string; "border-bottom-width"?: number | string; /** * "collapse" | "separate" */ "border-collapse"?: string; "border-color"?: string; "border-image"?: string; "border-image-outset"?: string; "border-image-repeat"?: string; "border-image-slice"?: string; "border-image-source"?: string; "border-image-width"?: number | string; "border-left"?: number | string; "border-left-color"?: string; "border-left-style"?: string; "border-left-width"?: number | string; "border-radius"?: number | string; "border-right"?: number | string; "border-right-color"?: number | string; "border-right-style"?: number | string; "border-right-width"?: number | string; "border-spacing"?: number | string; "border-style"?: string; "border-top"?: number | string; "border-top-color"?: string; "border-top-left-radius"?: number | string; "border-top-right-radius"?: number | string; "border-top-style"?: string; "border-top-width"?: number | string; "border-width"?: number | string; "bottom"?: number | string; /** * "slice" | "clone" */ "box-decoration-break"?: string; "box-shadow"?: string; /** * "content-box" | "border-box" */ "box-sizing"?: string; "break-after"?: string; "break-before"?: string; "break-inside"?: string; "caption-side"?: string; /** * "none" | "left" | "right" | "both" | "inline-start" | "inline-end" */ "clear"?: string; "clip"?: string; "clip-path"?: string; "clip-rule"?: string; "color"?: string; "color-interpolation-filters"?: string; "column-count"?: number | string; "column-fill"?: string; "column-gap"?: any; "column-rule"?: string; "column-rule-color"?: any; "column-rule-style"?: string; "column-rule-width"?: number | string; "column-span"?: string; "column-width"?: number | string; "columns"?: number | string; "content"?: string; "counter-increment"?: string; "counter-reset"?: string; "cursor"?: string; /** * "ltr" | "rtl" */ "direction"?: string; /** * "none" | "inline" | "block" | "list-item" | "inline-list-item" | "inline-block" | "inline-table" | * "table" | "table-cell" | "table-column" | "table-column-group" | "table-footer-group" | "table-header-group" | * "table-row" | "table-row-group" | "flex" | "inline-flex" | "grid" | "inline-grid" | "run-in" | "ruby" | * "ruby-base" | "ruby-text" | "ruby-base-container" | "ruby-text-container" | "contents" */ "display"?: string; "dominant-baseline"?: string; "empty-cells"?: string; "enable-background"?: string; "fill"?: string; "fill-opacity"?: string; "fill-rule"?: string; "filter"?: string; "flex"?: string; "flex-basis"?: string; /** * "row" | "row-reverse" | "column" | "column-reverse" */ "flex-direction"?: string; "flex-flow"?: string; "flex-grow"?: number | string; "flex-shrink"?: number | string; /** * "nowrap" | "wrap" | "wrap-reverse" */ "flex-wrap"?: string; /** * "left" | "right" | "none" | "inline-start" | "inline-end" */ "float"?: string; "flood-color"?: string; "flood-opacity"?: number | string; "font"?: string; "font-family"?: string; "font-feature-settings"?: string; "font-size"?: number | string; "font-size-adjust"?: string; /** * "normal" | "ultra-condensed" | "extra-condensed" | "condensed" | "semi-condensed" | * "semi-expanded" | "expanded" | "extra-expanded" | "ultra-expanded" */ "font-stretch"?: string; "font-style"?: string; "font-variant"?: string; "font-weight"?: number | string; "glyph-orientation-horizontal"?: string; "glyph-orientation-vertical"?: string; "height"?: number | string; /** * "auto" | "normal" | "active" | "inactive" | "disabled" */ "ime-mode"?: string; /** * "auto" | "isolate" */ "isolation"?: string; /** * "flex-start" | "flex-end" | "center" | "space-between" | "space-around" */ "justify-content"?: string; "kerning"?: string; "left"?: number | string; "letter-spacing"?: number | string; "lighting-color"?: string; /** * "auto" | "loose" | "normal" | "strict" */ "line-break"?: string; "line-height"?: number | string; "list-style"?: string; "list-style-image"?: string; "list-style-position"?: string; "list-style-type"?: string; "margin"?: number | string; "margin-bottom"?: number | string; "margin-left"?: number | string; "margin-right"?: number | string; "margin-top"?: number | string; "marker"?: string; "marker-end"?: string; "marker-mid"?: string; "marker-start"?: string; "mask"?: string; "max-height"?: number | string; "max-width"?: number | string; "min-height"?: number | string; "min-width"?: number | string; "-ms-content-zoom-chaining"?: string; "-ms-content-zoom-limit"?: string; "-ms-content-zoom-limit-max"?: any; "-ms-content-zoom-limit-min"?: any; "-ms-content-zoom-snap"?: string; "-ms-content-zoom-snap-points"?: string; "-ms-content-zoom-snap-type"?: string; "-ms-content-zooming"?: string; "-ms-flow-from"?: string; "-ms-flow-into"?: string; "-ms-font-feature-settings"?: string; "-ms-grid-column"?: any; "-ms-grid-column-align"?: string; "-ms-grid-column-span"?: any; "-ms-grid-columns"?: string; "-ms-grid-row"?: any; "-ms-grid-row-align"?: string; "-ms-grid-row-span"?: any; "-ms-grid-rows"?: string; "-ms-high-contrast-adjust"?: string; "-ms-hyphenate-limit-chars"?: string; "-ms-hyphenate-limit-lines"?: any; "-ms-hyphenate-limit-zone"?: any; "-ms-hyphens"?: string; "-ms-ime-align"?: string; "-ms-overflow-style"?: string; "-ms-scroll-chaining"?: string; "-ms-scroll-limit"?: string; "-ms-scroll-limit-x-max"?: any; "-ms-scroll-limit-x-min"?: any; "-ms-scroll-limit-y-max"?: any; "-ms-scroll-limit-y-min"?: any; "-ms-scroll-rails"?: string; "-ms-scroll-snap-points-x"?: string; "-ms-scroll-snap-points-y"?: string; "-ms-scroll-snap-type"?: string; "-ms-scroll-snap-x"?: string; "-ms-scroll-snap-y"?: string; "-ms-scroll-translation"?: string; "-ms-text-combine-horizontal"?: string; "-ms-text-size-adjust"?: any; "-ms-touch-action"?: string; "-ms-touch-select"?: string; /** * "none" | "auto" | "text" | "all" */ "-ms-user-select"?: string; "-ms-wrap-flow"?: string; "-ms-wrap-margin"?: any; "-ms-wrap-through"?: string; /** * "fill" | "contain" | "cover" | "none" | "scale-down" */ "object-fit"?: string; "opacity"?: number | string; "order"?: number | string; /** * "auto" | "portrait" | "landscape" */ "orientation"?: string; "orphans"?: string; "outline"?: string; "outline-color"?: string; "outline-style"?: string; "outline-width"?: number | string; /** * "visible" | "hidden" | "scroll" | "auto" */ "overflow"?: string; /** * "normal" | "break-word" */ "overflow-wrap"?: string; /** * "visible" | "hidden" | "scroll" | "auto" */ "overflow-x"?: string; /** * "visible" | "hidden" | "scroll" | "auto" */ "overflow-y"?: string; "padding"?: number | string; "padding-bottom"?: number | string; "padding-left"?: number | string; "padding-right"?: number | string; "padding-top"?: number | string; "page-break-after"?: string; "page-break-before"?: string; "page-break-inside"?: string; "perspective"?: number | string; "perspective-origin"?: string; /** * "auto" | "none" | "visiblePainted" | "visibleFill" | "visibleStroke" | "visible" | "painted" | * "fill" | "stroke" | "all" | "inherit" */ "pointer-events"?: string; /** * "static" | "relative" | "absolute" | "sticky" | "fixed" */ "position"?: string; "quotes"?: string; /** * "none" | "both" | "horizontal" | "vertical" */ "resize"?: string; "right"?: number | string; "ruby-align"?: string; "ruby-overhang"?: string; "ruby-position"?: string; "stop-color"?: string; "stop-opacity"?: number | string; "stroke"?: string; "stroke-dasharray"?: string; "stroke-dashoffset"?: number | string; "stroke-linecap"?: string; "stroke-linejoin"?: string; "stroke-miterlimit"?: string; "stroke-opacity"?: number | string; "stroke-width"?: number | string; "tab-size"?: number | string; /** * "auto" | "fixed" */ "table-layout"?: string; /** * "start" | "end" | "left" | "right" | "center" | "justify" | "match-parent" */ "text-align"?: string; /** * "auto" | "start" | "end" | "left" | "right" | "center" | "justify" */ "text-align-last"?: string; "text-anchor"?: string; "text-decoration"?: string; /** * "solid" | "double" | "dotted" | "dashed" | "wavy" */ "text-decoration-style"?: string; "text-indent"?: number | string; "text-justify"?: string; "text-kashida"?: string; "text-kashida-space"?: string; /** * "mixed" | "upright" | "sideways" */ "text-orientation"?: string; "text-overflow"?: string; "text-shadow"?: string; "text-transform"?: string; "text-underline-position"?: string; "top"?: number | string; "touch-action"?: string; "transform"?: string; /** * "mixed" | "upright" | "sideways" */ "transform-box"?: string; "transform-origin"?: string; "transform-style"?: string; "transition"?: string; "transition-delay"?: number | string; "transition-duration"?: number | string; "transition-property"?: string; "transition-timing-function"?: string; "unicode-bidi"?: string; /** * "none" | "auto" | "text" | "all" */ "user-select"?: string; "vertical-align"?: string; /** * "visible" | "hidden" | "collapse" */ "visibility"?: string; "-webkit-align-content"?: string; "-webkit-align-items"?: string; "-webkit-align-self"?: string; "-webkit-animation"?: string; "-webkit-animation-delay"?: string; "-webkit-animation-direction"?: string; "-webkit-animation-duration"?: string; "-webkit-animation-fill-mode"?: string; "-webkit-animation-iteration-count"?: string; "-webkit-animation-name"?: string; "-webkit-animation-play-state"?: string; "-webkit-animation-timing-function"?: string; "-webkit-appearance"?: string; "-webkit-backface-visibility"?: string; "-webkit-background-clip"?: string; "-webkit-background-origin"?: string; "-webkit-background-size"?: string; "-webkit-border-bottom-left-radius"?: string; "-webkit-border-bottom-right-radius"?: string; "-webkit-border-image"?: string; "-webkit-border-radius"?: string; "-webkit-border-top-left-radius"?: string; "-webkit-border-top-right-radius"?: string; "-webkit-box-align"?: string; "-webkit-box-direction"?: string; "-webkit-box-flex"?: string; "-webkit-box-ordinal-group"?: string; "-webkit-box-orient"?: string; "-webkit-box-pack"?: string; "-webkit-box-sizing"?: string; "-webkit-column-break-after"?: string; "-webkit-column-break-before"?: string; "-webkit-column-break-inside"?: string; "-webkit-column-count"?: any; "-webkit-column-gap"?: any; "-webkit-column-rule"?: string; "-webkit-column-rule-color"?: any; "-webkit-column-rule-style"?: string; "-webkit-column-rule-width"?: any; "-webkit-column-span"?: string; "-webkit-column-width"?: any; "-webkit-columns"?: string; "-webkit-filter"?: string; "-webkit-flex"?: string; "-webkit-flex-basis"?: string; "-webkit-flex-direction"?: string; "-webkit-flex-flow"?: string; "-webkit-flex-grow"?: string; "-webkit-flex-shrink"?: string; "-webkit-flex-wrap"?: string; "-webkit-justify-content"?: string; "-webkit-order"?: string; "-webkit-perspective"?: string; "-webkit-perspective-origin"?: string; "-webkit-tap-highlight-color"?: string; "-webkit-text-fill-color"?: string; "-webkit-textSize-adjust"?: any; "-webkit-transform"?: string; "-webkit-transform-origin"?: string; "-webkit-transform-style"?: string; "-webkit-transition"?: string; "-webkit-transition-delay"?: string; "-webkit-transition-duration"?: string; "-webkit-transition-property"?: string; "-webkit-transition-timing-function"?: string; "-webkit-user-modify"?: string; /** * "none" | "auto" | "text" | "all" */ "-webkit-user-select"?: string; "-webkit-writing-mode"?: string; /** * "normal" | "pre" | "nowrap" | "pre-wrap" | "pre-line" */ "white-space"?: string; "widows"?: number | string; "width"?: number | string; /** * "normal" | "break-all" | "keep-all" */ "word-break"?: string; "word-spacing"?: number | string; /** * "normal" | "break-word" */ "word-wrap"?: string; "writing-mode"?: string; "z-index"?: number | string; "zoom"?: string; [key: string]: any; }
the_stack
import * as React from "react"; import { BaseContainer } from "../../../BaseContainer"; import classnames from "classnames"; import { SubscriptionContentsState } from "./SubscriptionContentsStore"; import { SubscriptionContent, SubscriptionContentIdentifier } from "../../../../../domain/Subscriptions/SubscriptionContent/SubscriptionContent"; import { DefaultButton, Image, ImageFit, Link, Toggle } from "office-ui-fabric-react"; import { FocusContentUseCase } from "./use-case/FocusContentUseCase"; import { ProgressColorBar } from "../../../../project/ProgressColorBar/ProgressColorBar"; import { Subscription } from "../../../../../domain/Subscriptions/Subscription"; import { Time } from "../../../../ui-kit/Time/Time"; import { TurnOffContentsFilterUseCase, TurnOnContentsFilterUseCase } from "./use-case/ToggleFilterContents"; import { createFetchMoreSubscriptContentsUseCase } from "../../../../../use-case/subscription/FetchMoreSubscriptContentsUseCase"; import { SubscriptionContentComponent } from "./SubscriptionContent/SubscriptionContentComponent"; const debug = require("debug")("irodr:SubscriptionContentsContainer"); const format = require("date-fns/format"); export interface SubscriptionContentsContainerProps { subscriptionContents: SubscriptionContentsState; } /** * get Active Item from the scroll position * @see https://gist.github.com/azu/c306c1efa31f0f41aa01c5b69576d00c#file-reader_main-0-3-8-js-L1205 * @returns {string} */ export function getActiveContentIdString(): string | undefined { const contentContainer = document.querySelector(".SubscriptionContentsContainer") as HTMLElement; const contentElements = document.querySelectorAll( ".SubscriptionContentsContainer-content" ) as NodeListOf<HTMLElement>; // TODO: should be computable // AppHeader's height = 32px const marginTopOfContentContainer = 32; const containerScrollTop = contentContainer.scrollTop; const containerOffsetHeight = contentContainer.offsetHeight; const contentCount = contentElements.length; if (!contentCount) { return; } const offsets: number[] = []; for (let i = 0; i < contentCount; i++) { offsets.push(contentElements[i].offsetTop - marginTopOfContentContainer); } if (!contentContainer) { return; } const screen = [containerScrollTop, containerScrollTop + containerOffsetHeight]; const pairs = offsets.map(function (v, i, element) { if (element[i + 1]) { return [v, element[i + 1]]; } else { // last return [v, screen[1]]; } }); const full_contain: number[] = []; debug("getActiveContentIdString:screen", screen); debug("getActiveContentIdString:pairs", pairs); const intersections = pairs.map(function (pair, i) { if (pair[1] < screen[0]) { return 0; } if (pair[0] > screen[1]) { return 0; } const top = Math.max(screen[0], pair[0]); const bottom = Math.min(screen[1], pair[1]); if (top == pair[0] && bottom == pair[1]) { full_contain.push(i); } return bottom - top; }); debug("getActiveContentIdString:full_contain", full_contain); debug("getActiveContentIdString:intersections", intersections); if (contentCount == 1) { const content = contentElements[0]; return content.dataset.contentId; } else { if (full_contain.length > 0) { const offset = full_contain.shift(); if (offset === undefined) { return; } const content = contentElements[offset]; return content.dataset.contentId; } else { const max_intersection = Math.max(...intersections); const offset = max_intersection === 0 ? contentCount - 1 : intersections.indexOf(max_intersection); if (offset === undefined) { return; } const content = contentElements[offset]; return content.dataset.contentId; } } } export class SubscriptionContentsContainer extends BaseContainer<SubscriptionContentsContainerProps, {}> { containerDivRef: React.RefObject<HTMLDivElement> = React.createRef(); private onChangedToggleContentsFilter = (checked: boolean) => { if (checked) { this.useCase(new TurnOnContentsFilterUseCase()).execute(); } else { this.useCase(new TurnOffContentsFilterUseCase()).execute(); } }; private onClickReadMore = async () => { const subscription = this.props.subscriptionContents.subscription; if (!subscription) { return; } // disable content filter this.useCase(new TurnOffContentsFilterUseCase()).execute(); // fetch more contents this.useCase(createFetchMoreSubscriptContentsUseCase()).execute(subscription.props.id); }; render() { const header = this.makeHeaderContent(this.props.subscriptionContents.subscription); if (!this.props.subscriptionContents.contents) { return ( <div className="SubscriptionContentsContainer is-noContents"> <div className="SubscriptionContentsContainer-body"> <p className="SubscriptionContentsContainer-bodyMessage">No contents</p> </div> </div> ); } const contents = this.props.subscriptionContents.contents .getContentList() .map((content, index) => this.makeContent(content, index)); return ( <div ref={this.containerDivRef} className={classnames("SubscriptionContentsContainer", this.props.className)} > <ProgressColorBar color="#a5c5ff" height={3} isCompleted={!this.props.subscriptionContents.isContentsLoadings} /> {header} <div role="main" className="SubscriptionContentsContainer-body"> {contents} </div> <footer className="SubscriptionContentsContainer-footer"> <div className="SubscriptionContentsContainer-readMore"> <DefaultButton className="SubscriptionContentsContainer-readMoreButton" onClick={this.onClickReadMore} > Read More </DefaultButton> </div> <div className="SubscriptionContentsContainer-footerPadding" style={{ height: "100vh" }} /> </footer> </div> ); } componentDidMount() { if (this.containerDivRef.current) { this.containerDivRef.current.scrollTo(0, 0); } } componentDidUpdate(prevProps: SubscriptionContentsContainerProps) { if (!prevProps.subscriptionContents.subscription && this.props.subscriptionContents.subscription) { if (this.containerDivRef.current) { this.containerDivRef.current.scrollTo(0, 0); } } if ( prevProps.subscriptionContents.subscription && !prevProps.subscriptionContents.subscription.equals(this.props.subscriptionContents.subscription) ) { if (this.containerDivRef.current) { this.containerDivRef.current.scrollTo(0, 0); } this.onContentChange(); } const scrollContentId = this.props.subscriptionContents.scrollContentId; if (scrollContentId && prevProps.subscriptionContents.scrollContentId !== scrollContentId) { this.scrollToContentId(scrollContentId); } // Avoid to Warning: Lifecycle hook scheduled a cascading update requestAnimationFrame(() => { this.updateCurrentFocus(); }); } private makeHeaderContent(subscription?: Subscription) { if (!subscription) { return null; } const editLink = ( <Link className="SubscriptionContentsContainer-subscriptionEditLink" title="Edit subscription" href={`https://www.inoreader.com/feed/${encodeURIComponent(subscription.url)}`} > <i className="ms-Icon ms-Icon--Settings" aria-hidden="true" /> </Link> ); const updatedCount = this.props.subscriptionContents.updatedContentsCount !== 0 ? this.props.subscriptionContents.updatedContentsCount : undefined; return ( <header className="SubscriptionContentsContainer-header"> <div className="SubscriptionContentsContainer-headerLeft"> <h2 className="SubscriptionContentsContainer-subscriptionTitle"> <Image className="SubscriptionContentsContainer-subscriptionImage" src={subscription.iconUrl} width={18} height={18} imageFit={ImageFit.cover} /> <Link className="SubscriptionContentsContainer-subscriptionLink" href={subscription.htmlUrl}> {subscription.title} </Link> <span className="SubscriptionContentsContainer-subscriptionUnreadCount"> ({subscription.unread.formatString + (updatedCount ? ` + ${updatedCount}` : "")}) </span> {editLink} <span className="SubscriptionContentsContainer-subscriptionUpdatedDate"> First Item: <Time dateTime={subscription.lastUpdated.isoString}> {format(subscription.lastUpdated.date, "YYYY-MM-DD mm:ss")} </Time> </span> </h2> </div> <div className="SubscriptionContentsContainer-headerRight"> <Toggle checked={this.props.subscriptionContents.enableContentFilter} onAriaLabel="Show all contents" offAriaLabel="Show only unread contents" onText="Unread" offText="All" onChanged={this.onChangedToggleContentsFilter} /> </div> </header> ); } private onContentChange() { if (this.containerDivRef.current) { const observer = new IntersectionObserver( (entries) => { this.updateCurrentFocus(); }, { root: this.containerDivRef.current, rootMargin: "10px", threshold: [0, 0.1, 0.2, 0.4, 0.6, 0.8, 0.9, 1.0] } ); Array.from(document.querySelectorAll(".SubscriptionContentsContainer-content")).forEach((element) => { observer.observe(element); }); } } private updateCurrentFocus() { const activeItemId = getActiveContentIdString(); if (activeItemId) { const contentId = this.props.subscriptionContents.getContentId(activeItemId); if (!contentId.equals(this.props.subscriptionContents.focusContentId)) { this.useCase(new FocusContentUseCase()).execute(contentId); } } } private makeContent(content: SubscriptionContent, index: number) { const isFocus = this.props.subscriptionContents.isFocusContent(content); const updateType = this.props.subscriptionContents.getTypeOfContent(content); const id = content.id.toValue(); return ( <SubscriptionContentComponent key={id} isFocus={isFocus} updateType={updateType} author={content.author} title={content.title} url={content.url} body={content.body.HTMLString} contentId={id} updatedDate={content.updatedDate.date} publishedDate={content.publishedDate.date} /> ); } private scrollToContentId(scrollContentId: SubscriptionContentIdentifier) { try { const targetElement = document.querySelector(`[data-content-id="${scrollContentId.toValue()}"]`); if (targetElement) { targetElement.scrollIntoView(); } } catch (error) { console.error("error on scrollToContentId", error); } } }
the_stack
import { HTMLElement, TextNode, HTMLComment, Node } from "../../chef/html/html"; import { Expression, Operation, VariableReference } from "../../chef/javascript/components/value/expression"; import { Value, ValueTypes, Type } from "../../chef/javascript/components/value/value"; import { FunctionDeclaration, ArgumentList } from "../../chef/javascript/components/constructs/function"; import { ObjectLiteral } from "../../chef/javascript/components/value/object"; import { cloneAST, aliasVariables } from "../../chef/javascript/utils/variables"; import { ForIteratorExpression } from "../../chef/javascript/components/statements/for"; import { ReturnStatement } from "../../chef/javascript/components/statements/statement"; import { thisDataVariable } from "../helpers"; import { NodeData } from "../template"; /** * Adds render method to existing class component definition * @param template The <template> element from the Prism * @param aliasDataToThis given data variables point them towards this * TODO settings object */ export function buildClientRenderMethod( template: HTMLElement, nodeData: WeakMap<Node, NodeData>, aliasDataToThis: boolean, shadowDOM: boolean = false, locals: Array<VariableReference> = [] ): FunctionDeclaration { if (template instanceof HTMLComment) throw Error(); const args: Array<ValueTypes> = []; for (const child of template.children) { const clientChildRendered = clientRenderPrismNode(child, nodeData, aliasDataToThis, locals); if (clientChildRendered === null) continue; args.push(clientChildRendered); } const attachTo = shadowDOM ? new Expression({ lhs: VariableReference.fromChain("this", "attachShadow"), operation: Operation.Call, rhs: new ObjectLiteral(new Map([["mode", new Value(Type.string, "open")]])) }) // super used to prevent collision with slot catching : new VariableReference("super"); return new FunctionDeclaration( "render", [], [ new Expression({ lhs: new VariableReference("append", attachTo), operation: Operation.Call, rhs: new ArgumentList(args) }), ] ); } /** * Generated the call for rendering a node (element, text node or comment) * If not needed will return null (TODO temp element should not exist at all) */ export function clientRenderPrismNode( element: Node, nodeData: WeakMap<Node, NodeData>, aliasDataToThis: boolean = false, locals: Array<VariableReference> = [], skipOverClientExpression: boolean = false ): ValueTypes { if (element instanceof HTMLElement) { // If slot then use then loaded slotted element if (element.tagName === "slot") { return new Expression({ operation: Operation.Spread, lhs: VariableReference.fromChain("this", "slotElement") }); } // Pointer to the h minified render function included in prism bundle under `render.ts` const renderFunction = new VariableReference("h"); const elementData = nodeData.get(element); // The render function (h) second argument takes 0 (falsy) if no attributes, string for a single class name and a object literal of attribute to value pairs. Mostly for minification purposes const attrs: Array<[string, ValueTypes]> = []; if (element.attributes) { for (const [name, value] of element.attributes) { if (HTMLElement.booleanAttributes.has(name)) { attrs.push([name, new Value(Type.boolean, "true")]) } else { attrs.push([name, new Value(Type.string, value ?? "")]) } } } if (elementData?.dynamicAttributes) { for (const [key, value] of elementData?.dynamicAttributes) { if (aliasDataToThis) { // Value reference is also used a lot so due to aliasVariables doing it in place best to clone it to prevent side effects const clonedValue = cloneAST(value); aliasVariables(clonedValue, thisDataVariable, locals); attrs.push([key, clonedValue]); } else { attrs.push([key, value]); } } } let eventArgument: ValueTypes; if (elementData?.events) { // TODO abstract eventArgument = new ObjectLiteral( new Map( elementData?.events.map(event => { let callback: ValueTypes; if (event.existsOnComponentClass) { callback = new Expression({ lhs: VariableReference.fromChain("this", event.callback.name, "bind"), operation: Operation.Call, rhs: new ArgumentList([new VariableReference("this")]) }); } else { callback = event.callback; } return [event.eventName, callback]; }) ) ); } else { eventArgument = new Value(Type.number, 0); } // TODO explain let childrenArgument: Array<ValueTypes>; if ((elementData?.conditionalExpression || elementData?.iteratorExpression) && !skipOverClientExpression) { if (elementData.clientRenderMethod) { if (elementData.iteratorExpression) { const clientExpression = cloneAST(elementData.iteratorExpression) as ForIteratorExpression; aliasVariables(clientExpression, thisDataVariable, locals); childrenArgument = [ new Expression({ operation: Operation.Spread, lhs: new Expression({ lhs: new VariableReference("map", clientExpression.subject), operation: Operation.Call, rhs: VariableReference.fromChain("this", elementData.clientRenderMethod.actualName!) }) }) ]; } else { return new Expression({ lhs: VariableReference.fromChain("this", elementData.clientRenderMethod.actualName!), operation: Operation.Call, }); } } else { // Produce a map expression: // *subject*.map(*variable* => *clientRenderChildren*) if (elementData.iteratorExpression) { const clientExpression = cloneAST(elementData.iteratorExpression); aliasVariables(clientExpression, thisDataVariable, locals); childrenArgument = [ new Expression({ operation: Operation.Spread, lhs: new Expression({ lhs: new VariableReference("map", clientExpression.subject), operation: Operation.Call, rhs: new FunctionDeclaration( null, [clientExpression.variable], [new ReturnStatement( clientRenderPrismNode(element.children[0], nodeData, aliasDataToThis, locals) )], { bound: false } ) }) }) ]; } // Produce a ternary expression: // *conditionExpression* ? *renderTruthyNode* : *renderFalsyChild* else { const renderTruthyChild = clientRenderPrismNode(element, nodeData, aliasDataToThis, locals, true); const { elseElement, conditionalExpression } = nodeData.get(element)!; const renderFalsyChild = clientRenderPrismNode(elseElement!, nodeData, aliasDataToThis, locals); const clientConditionExpression = cloneAST(conditionalExpression!); aliasVariables(clientConditionExpression, thisDataVariable, locals); return new Expression({ lhs: clientConditionExpression as ValueTypes, operation: Operation.Ternary, rhs: new ArgumentList([ renderTruthyChild, renderFalsyChild ]) }) } } } else if (elementData?.rawInnerHTML) { const aliasedRawInnerHTMLValue = cloneAST(elementData.rawInnerHTML); aliasVariables(aliasedRawInnerHTMLValue, thisDataVariable, locals); attrs.push(["innerHTML", aliasedRawInnerHTMLValue]); childrenArgument = []; } else { // TODO explain including case where children.length === 0 childrenArgument = element.children.map(element => clientRenderPrismNode(element, nodeData, aliasDataToThis, locals)) } const attributeArgument: ValueTypes = attrs.length > 0 ? new ObjectLiteral(new Map(attrs)) : new Value(Type.number, 0); // 0 is used as a falsy value // TODO trim trailing 0's // Arguments for: h(tagname: string, attribute: 0 | string | object, events: 0 | object, ...children: Array<string>) const argumentList = new ArgumentList([ new Value(Type.string, element.tagName), attributeArgument, eventArgument, ...childrenArgument ]); return new Expression({ lhs: renderFunction, operation: Operation.Call, rhs: argumentList }); } else if (element instanceof TextNode) { const textNodeValue = nodeData.get(element)?.textNodeValue; if (textNodeValue && aliasDataToThis) { const clonedValue = cloneAST(textNodeValue); aliasVariables(clonedValue, thisDataVariable, locals); return clonedValue; } else { // Expand out html symbols const value = element.text.replace(/&#(x)?(.*?);/g, (_, x, v) => { // If hexadecimal if (x) { return "\\u" + v.padStart(4, "0"); } else { return "\\u" + parseInt(v).toString(16).padStart(4, "0"); } }); return new Value(Type.string, value); } } else if (element instanceof HTMLComment) { const isFragment = nodeData.get(element)?.isFragment; if (!isFragment) throw Error("Client side rendering of non-fragment comment supported"); // This used to maintain the same structure as server rendered content return new Expression({ lhs: new VariableReference("cC"), // Create comment function in render.ts operation: Operation.Call, rhs: element.comment ? new Value(Type.string, element.comment) : new ArgumentList }); } else { throw Error(`Unsupported building of ${element!.constructor.name}`) } }
the_stack
import { expect } from "chai"; import * as faker from "faker"; import { Id64String } from "@itwin/core-bentley"; import { CategoryDescription } from "../../presentation-common/content/Category"; import { Descriptor, DescriptorJSON, DescriptorSource, SelectClassInfo, SelectClassInfoJSON, SortDirection, } from "../../presentation-common/content/Descriptor"; import { Field, FieldDescriptorType } from "../../presentation-common/content/Fields"; import { PropertyValueFormat } from "../../presentation-common/content/TypeDescription"; import { CompressedClassInfoJSON, RelatedClassInfo, RelatedClassInfoJSON } from "../../presentation-common/EC"; import { createTestCategoryDescription, createTestContentDescriptor, createTestNestedContentField, createTestPropertiesContentField, createTestSelectClassInfo, createTestSimpleContentField, } from "../_helpers/Content"; import { createTestPropertyInfo, createTestRelatedClassInfo, createTestRelationshipPath } from "../_helpers/EC"; describe("Descriptor", () => { describe("constructor", () => { it("creates Descriptor from DescriptorSource without categories", () => { const category = createTestCategoryDescription(); const source: DescriptorSource = { contentFlags: 9, displayType: faker.random.word(), categories: [category], fields: [createTestSimpleContentField({ category }), createTestSimpleContentField({ category })], filterExpression: faker.random.words(), selectClasses: [], }; const descriptor = new Descriptor(source); for (const key in source) { if (source.hasOwnProperty(key)) expect((descriptor as any)[key]).to.deep.eq((source as any)[key]); } }); it("creates Descriptor from DescriptorSource with categories", () => { const category = createTestCategoryDescription(); const source: DescriptorSource = { contentFlags: 9, displayType: faker.random.word(), categories: [category], fields: [createTestSimpleContentField({ category }), createTestSimpleContentField({ category })], filterExpression: faker.random.words(), selectClasses: [], }; const descriptor = new Descriptor(source); for (const key in source) { if (source.hasOwnProperty(key)) expect((descriptor as any)[key]).to.deep.eq((source as any)[key]); } }); }); describe("fromJSON", () => { const validateParentship = (fields: Field[], parent?: Field) => { fields.forEach((field) => { expect(field.parent).to.eq(parent); if (field.isNestedContentField()) validateParentship(field.nestedFields, field); }); }; it("creates valid Descriptor from valid JSON", () => { const category = createTestCategoryDescription(); const ids = ["0x1", "0x2", "0x3", "0x4"]; const testRelatedClassInfo: RelatedClassInfoJSON<string> = { sourceClassInfo: ids[1], targetClassInfo: ids[2], relationshipInfo: ids[3], isForwardRelationship: true, }; const json: DescriptorJSON = { connectionId: "", categories: [CategoryDescription.toJSON(category)], contentFlags: 0, contentOptions: 0, displayType: "", inputKeysHash: "", classesMap: { [ids[0]]: { name: "name1", label: "label1" }, [ids[1]]: { name: "name2", label: "label2" }, [ids[2]]: { name: "name3", label: "label3" }, [ids[3]]: { name: "name4", label: "label4" }, }, selectClasses: [{ selectClassInfo: ids[0], isSelectPolymorphic: true, pathFromInputToSelectClass: [testRelatedClassInfo], relatedPropertyPaths: [[testRelatedClassInfo]], navigationPropertyClasses: [testRelatedClassInfo], relatedInstancePaths: [[testRelatedClassInfo]], }], fields: [{ name: "test-simple-field", label: "Test Simple Field", type: { valueFormat: PropertyValueFormat.Primitive, typeName: "string" }, category: category.name, isReadonly: false, priority: 0, }, { name: "test-properties-field", label: "Test Properties Field", type: { valueFormat: PropertyValueFormat.Primitive, typeName: "string" }, category: category.name, isReadonly: false, priority: 0, properties: [{ property: { classInfo: ids[0], name: "PropertyName", type: "TestPropertyType", }, }], }, { name: "test-nested-content-field", label: "Test Nested Content Field", type: { valueFormat: PropertyValueFormat.Struct, typeName: "StructType", members: [{ type: { valueFormat: PropertyValueFormat.Primitive, typeName: "string" }, name: "StringType", label: "String Type", }], }, category: category.name, isReadonly: false, priority: 0, contentClassInfo: ids[1], pathToPrimaryClass: [testRelatedClassInfo], nestedFields: [{ name: "test-nested-properties-field", label: "Test Nested Properties Field", type: { valueFormat: PropertyValueFormat.Primitive, typeName: "string" }, category: category.name, isReadonly: false, priority: 0, properties: [{ property: { classInfo: ids[1], name: "NestedPropertyName", type: "TestNestedPropertyType", }, }], }], autoExpand: false, }, { name: "test-properties-field-with-navigation-property-info", label: "Test Properties Field With Navigation Property Info", type: { valueFormat: PropertyValueFormat.Primitive, typeName: "navigation" }, category: category.name, isReadonly: false, priority: 0, properties: [{ property: { classInfo: ids[1], name: "PropertyName", type: "TestPropertyType", navigationPropertyInfo: { classInfo: ids[3], isForwardRelationship: true, }, }, }], }], }; const descriptor = Descriptor.fromJSON(json); validateParentship(descriptor!.fields); expect(descriptor).to.matchSnapshot(); }); it("skips fields that fail to deserialize", () => { const category = createTestCategoryDescription(); const json: DescriptorJSON = { connectionId: "", categories: [CategoryDescription.toJSON(category)], contentFlags: 0, contentOptions: 0, displayType: "", inputKeysHash: "", selectClasses: [], classesMap: {}, fields: [ createTestSimpleContentField({ category }).toJSON(), undefined as any, ], }; const descriptor = Descriptor.fromJSON(json); expect(descriptor!.fields.length).to.eq(1); }); it("returns undefined for undefined JSON", () => { const descriptor = Descriptor.fromJSON(undefined); expect(descriptor).to.be.undefined; }); }); describe("toJSON", () => { it("creates valid CompressedDescriptorJSON", () => { const category = createTestCategoryDescription(); const fields = [ createTestSimpleContentField(), createTestPropertiesContentField({ category, properties: [{ property: createTestPropertyInfo() }], }), createTestNestedContentField({ category, nestedFields: [createTestSimpleContentField()], }), ]; const descriptor = createTestContentDescriptor({ selectClasses: [createTestSelectClassInfo({ pathFromInputToSelectClass: [createTestRelatedClassInfo()], navigationPropertyClasses: [createTestRelatedClassInfo()], relatedInstancePaths: [[createTestRelatedClassInfo()]], relatedPropertyPaths: [[createTestRelatedClassInfo()]], })], categories: [category], fields, filterExpression: "testFilterExpression", selectionInfo: { providerName: "testProviderName", level: 1 }, sortingField: fields[0], sortDirection: SortDirection.Ascending, }); expect(descriptor.toJSON()).to.matchSnapshot(); }); }); describe("getFieldByName", () => { it("returns undefined when there are no fields", () => { const descriptor = createTestContentDescriptor({ fields: [] }); expect(descriptor.getFieldByName("test")).to.be.undefined; }); it("returns undefined when field is not found", () => { const descriptor = createTestContentDescriptor({ fields: [createTestSimpleContentField()] }); expect(descriptor.getFieldByName("does-not-exist", true)).to.be.undefined; }); it("returns a field", () => { const field = createTestSimpleContentField(); const descriptor = createTestContentDescriptor({ fields: [field] }); expect(descriptor.getFieldByName(field.name)).to.eq(field); }); it("returns undefined when descriptor contains nested fields but field is not found", () => { const primitiveField = createTestSimpleContentField(); const nestedContentField = createTestNestedContentField({ nestedFields: [primitiveField], }); const descriptor = createTestContentDescriptor({ fields: [nestedContentField] }); expect(descriptor.getFieldByName("does not exist", true)).to.be.undefined; }); it("returns a nested field", () => { const primitiveField = createTestSimpleContentField(); const nestedContentField = createTestNestedContentField({ nestedFields: [primitiveField], }); const descriptor = createTestContentDescriptor({ fields: [nestedContentField] }); expect(descriptor.getFieldByName(primitiveField.name, true)).to.eq(primitiveField); }); }); describe("createDescriptorOverrides", () => { it("creates a valid object with default parameters", () => { const descriptor = createTestContentDescriptor({ fields: [], }); expect(descriptor.createDescriptorOverrides()).to.deep.eq({}); }); it("creates a valid object with display type", () => { const descriptor = createTestContentDescriptor({ fields: [], displayType: "test display type", }); expect(descriptor.createDescriptorOverrides()).to.deep.eq({ displayType: "test display type", }); }); it("creates a valid object with content flags", () => { const descriptor = createTestContentDescriptor({ fields: [], contentFlags: 123, }); expect(descriptor.createDescriptorOverrides()).to.deep.eq({ contentFlags: 123, }); }); it("creates a valid object with filter expression", () => { const descriptor = createTestContentDescriptor({ fields: [], filterExpression: "test filter", }); expect(descriptor.createDescriptorOverrides()).to.deep.eq({ filterExpression: "test filter", }); }); it("creates a valid object with sorting field ascending", () => { const field = createTestSimpleContentField(); const descriptor = createTestContentDescriptor({ fields: [field], sortingField: field, }); expect(descriptor.createDescriptorOverrides()).to.deep.eq({ sorting: { field: { type: FieldDescriptorType.Name, fieldName: field.name }, direction: SortDirection.Ascending, }, }); }); it("creates a valid object with sorting field descending", () => { const field = createTestSimpleContentField(); const descriptor = createTestContentDescriptor({ fields: [field], sortingField: field, sortDirection: SortDirection.Descending, }); expect(descriptor.createDescriptorOverrides()).to.deep.eq({ sorting: { field: { type: FieldDescriptorType.Name, fieldName: field.name }, direction: SortDirection.Descending, }, }); }); }); }); describe("SelectClassInfo", () => { let classesMap!: { [id: string]: CompressedClassInfoJSON }; let obj!: SelectClassInfo; let compressedJson!: SelectClassInfoJSON<Id64String>; beforeEach(() => { obj = { selectClassInfo: { id: "0x123", name: "name", label: "Label", }, isSelectPolymorphic: true, }; compressedJson = { selectClassInfo: "0x123", isSelectPolymorphic: true, }; classesMap = { ["0x123"]: { name: "name", label: "Label", }, }; }); describe("fromCompressedJSON", () => { it("doesn't create unnecessary members", () => { const result = SelectClassInfo.fromCompressedJSON(compressedJson, classesMap); expect(result).to.not.haveOwnProperty("pathFromInputToSelectClass"); expect(result).to.not.haveOwnProperty("relatedPropertyPaths"); expect(result).to.not.haveOwnProperty("navigationPropertyClasses"); expect(result).to.not.haveOwnProperty("relatedInstancePaths"); }); it("parses `pathFromInputToSelectClass`", () => { const pathFromInputToSelectClass = createTestRelationshipPath(2); compressedJson = { ...compressedJson, pathFromInputToSelectClass: pathFromInputToSelectClass.map((item) => RelatedClassInfo.toCompressedJSON(item, classesMap)), }; expect(SelectClassInfo.fromCompressedJSON(compressedJson, classesMap)).to.deep.eq({ ...obj, pathFromInputToSelectClass, }); }); it("parses `relatedPropertyPaths`", () => { const relatedPropertyPaths = [createTestRelationshipPath(2)]; compressedJson = { ...compressedJson, relatedPropertyPaths: relatedPropertyPaths.map((p) => p.map((i) => RelatedClassInfo.toCompressedJSON(i, classesMap))), }; expect(SelectClassInfo.fromCompressedJSON(compressedJson, classesMap)).to.deep.eq({ ...obj, relatedPropertyPaths, }); }); it("parses `navigationPropertyClasses`", () => { const navigationPropertyClasses = createTestRelationshipPath(2); compressedJson = { ...compressedJson, navigationPropertyClasses: navigationPropertyClasses.map((item) => RelatedClassInfo.toCompressedJSON(item, classesMap)), }; expect(SelectClassInfo.fromCompressedJSON(compressedJson, classesMap)).to.deep.eq({ ...obj, navigationPropertyClasses, }); }); it("parses `relatedInstancePaths`", () => { const relatedInstancePaths = [createTestRelationshipPath(2)]; compressedJson = { ...compressedJson, relatedInstancePaths: relatedInstancePaths.map((p) => p.map((i) => RelatedClassInfo.toCompressedJSON(i, classesMap))), }; expect(SelectClassInfo.fromCompressedJSON(compressedJson, classesMap)).to.deep.eq({ ...obj, relatedInstancePaths, }); }); }); describe("toCompressedJSON", () => { it("doesn't create unnecessary members", () => { const actualCompressedJson = SelectClassInfo.toCompressedJSON(obj, {}); expect(actualCompressedJson).to.not.haveOwnProperty("pathFromInputToSelectClass"); expect(actualCompressedJson).to.not.haveOwnProperty("relatedPropertyPaths"); expect(actualCompressedJson).to.not.haveOwnProperty("navigationPropertyClasses"); expect(actualCompressedJson).to.not.haveOwnProperty("relatedInstancePaths"); }); it("serializes `pathFromInputToSelectClass`", () => { const actualClassesMap = {}; const pathFromInputToSelectClass = createTestRelationshipPath(2); obj = { ...obj, pathFromInputToSelectClass, }; expect(SelectClassInfo.toCompressedJSON(obj, actualClassesMap)).to.deep.eq({ ...compressedJson, pathFromInputToSelectClass: pathFromInputToSelectClass.map((p) => RelatedClassInfo.toCompressedJSON(p, {})), }); expect(actualClassesMap).to.containSubset(classesMap); }); it("serializes `relatedPropertyPaths`", () => { const actualClassesMap = {}; const relatedPropertyPaths = [createTestRelationshipPath(2)]; obj = { ...obj, relatedPropertyPaths, }; expect(SelectClassInfo.toCompressedJSON(obj, actualClassesMap)).to.deep.eq({ ...compressedJson, relatedPropertyPaths: relatedPropertyPaths.map((p) => p.map((i) => RelatedClassInfo.toCompressedJSON(i, {}))), }); expect(actualClassesMap).to.containSubset(classesMap); }); it("serializes `navigationPropertyClasses`", () => { const actualClassesMap = {}; const navigationPropertyClasses = createTestRelationshipPath(2); obj = { ...obj, navigationPropertyClasses, }; expect(SelectClassInfo.toCompressedJSON(obj, actualClassesMap)).to.deep.eq({ ...compressedJson, navigationPropertyClasses: navigationPropertyClasses.map((p) => RelatedClassInfo.toCompressedJSON(p, {})), }); expect(actualClassesMap).to.containSubset(classesMap); }); it("serializes `relatedInstancePaths`", () => { const actualClassesMap = {}; const relatedInstancePaths = [createTestRelationshipPath(2)]; obj = { ...obj, relatedInstancePaths, }; expect(SelectClassInfo.toCompressedJSON(obj, actualClassesMap)).to.deep.eq({ ...compressedJson, relatedInstancePaths: relatedInstancePaths.map((p) => p.map((i) => RelatedClassInfo.toCompressedJSON(i, {}))), }); expect(actualClassesMap).to.containSubset(classesMap); }); }); describe("listFromCompressedJSON", () => { it("creates valid SelectClassInfo[] from compressed JSON", () => { const result = SelectClassInfo.listFromCompressedJSON([compressedJson], classesMap); expect(result).to.deep.equal([obj]); }); }); });
the_stack
import * as Long from 'long' import { util, configure, Writer, Reader } from 'protobufjs/minimal' import { Duration } from '../../google/protobuf/duration' export const protobufPackage = 'tendermint.types' /** * ConsensusParams contains consensus critical parameters that determine the * validity of blocks. */ export interface ConsensusParams { block: BlockParams | undefined evidence: EvidenceParams | undefined validator: ValidatorParams | undefined version: VersionParams | undefined } /** BlockParams contains limits on the block size. */ export interface BlockParams { /** * Max block size, in bytes. * Note: must be greater than 0 */ maxBytes: number /** * Max gas per block. * Note: must be greater or equal to -1 */ maxGas: number /** * Minimum time increment between consecutive blocks (in milliseconds) If the * block header timestamp is ahead of the system clock, decrease this value. * * Not exposed to the application. */ timeIotaMs: number } /** EvidenceParams determine how we handle evidence of malfeasance. */ export interface EvidenceParams { /** * Max age of evidence, in blocks. * * The basic formula for calculating this is: MaxAgeDuration / {average block * time}. */ maxAgeNumBlocks: number /** * Max age of evidence, in time. * * It should correspond with an app's "unbonding period" or other similar * mechanism for handling [Nothing-At-Stake * attacks](https://github.com/ethereum/wiki/wiki/Proof-of-Stake-FAQ#what-is-the-nothing-at-stake-problem-and-how-can-it-be-fixed). */ maxAgeDuration: Duration | undefined /** * This sets the maximum size of total evidence in bytes that can be committed in a single block. * and should fall comfortably under the max block bytes. * Default is 1048576 or 1MB */ maxBytes: number } /** * ValidatorParams restrict the public key types validators can use. * NOTE: uses ABCI pubkey naming, not Amino names. */ export interface ValidatorParams { pubKeyTypes: string[] } /** VersionParams contains the ABCI application version. */ export interface VersionParams { appVersion: number } /** * HashedParams is a subset of ConsensusParams. * * It is hashed into the Header.ConsensusHash. */ export interface HashedParams { blockMaxBytes: number blockMaxGas: number } const baseConsensusParams: object = {} export const ConsensusParams = { encode(message: ConsensusParams, writer: Writer = Writer.create()): Writer { if (message.block !== undefined) { BlockParams.encode(message.block, writer.uint32(10).fork()).ldelim() } if (message.evidence !== undefined) { EvidenceParams.encode(message.evidence, writer.uint32(18).fork()).ldelim() } if (message.validator !== undefined) { ValidatorParams.encode( message.validator, writer.uint32(26).fork() ).ldelim() } if (message.version !== undefined) { VersionParams.encode(message.version, writer.uint32(34).fork()).ldelim() } return writer }, decode(input: Reader | Uint8Array, length?: number): ConsensusParams { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseConsensusParams } as ConsensusParams while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.block = BlockParams.decode(reader, reader.uint32()) break case 2: message.evidence = EvidenceParams.decode(reader, reader.uint32()) break case 3: message.validator = ValidatorParams.decode(reader, reader.uint32()) break case 4: message.version = VersionParams.decode(reader, reader.uint32()) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): ConsensusParams { const message = { ...baseConsensusParams } as ConsensusParams if (object.block !== undefined && object.block !== null) { message.block = BlockParams.fromJSON(object.block) } else { message.block = undefined } if (object.evidence !== undefined && object.evidence !== null) { message.evidence = EvidenceParams.fromJSON(object.evidence) } else { message.evidence = undefined } if (object.validator !== undefined && object.validator !== null) { message.validator = ValidatorParams.fromJSON(object.validator) } else { message.validator = undefined } if (object.version !== undefined && object.version !== null) { message.version = VersionParams.fromJSON(object.version) } else { message.version = undefined } return message }, toJSON(message: ConsensusParams): unknown { const obj: any = {} message.block !== undefined && (obj.block = message.block ? BlockParams.toJSON(message.block) : undefined) message.evidence !== undefined && (obj.evidence = message.evidence ? EvidenceParams.toJSON(message.evidence) : undefined) message.validator !== undefined && (obj.validator = message.validator ? ValidatorParams.toJSON(message.validator) : undefined) message.version !== undefined && (obj.version = message.version ? VersionParams.toJSON(message.version) : undefined) return obj }, fromPartial(object: DeepPartial<ConsensusParams>): ConsensusParams { const message = { ...baseConsensusParams } as ConsensusParams if (object.block !== undefined && object.block !== null) { message.block = BlockParams.fromPartial(object.block) } else { message.block = undefined } if (object.evidence !== undefined && object.evidence !== null) { message.evidence = EvidenceParams.fromPartial(object.evidence) } else { message.evidence = undefined } if (object.validator !== undefined && object.validator !== null) { message.validator = ValidatorParams.fromPartial(object.validator) } else { message.validator = undefined } if (object.version !== undefined && object.version !== null) { message.version = VersionParams.fromPartial(object.version) } else { message.version = undefined } return message } } const baseBlockParams: object = { maxBytes: 0, maxGas: 0, timeIotaMs: 0 } export const BlockParams = { encode(message: BlockParams, writer: Writer = Writer.create()): Writer { if (message.maxBytes !== 0) { writer.uint32(8).int64(message.maxBytes) } if (message.maxGas !== 0) { writer.uint32(16).int64(message.maxGas) } if (message.timeIotaMs !== 0) { writer.uint32(24).int64(message.timeIotaMs) } return writer }, decode(input: Reader | Uint8Array, length?: number): BlockParams { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseBlockParams } as BlockParams while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.maxBytes = longToNumber(reader.int64() as Long) break case 2: message.maxGas = longToNumber(reader.int64() as Long) break case 3: message.timeIotaMs = longToNumber(reader.int64() as Long) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): BlockParams { const message = { ...baseBlockParams } as BlockParams if (object.maxBytes !== undefined && object.maxBytes !== null) { message.maxBytes = Number(object.maxBytes) } else { message.maxBytes = 0 } if (object.maxGas !== undefined && object.maxGas !== null) { message.maxGas = Number(object.maxGas) } else { message.maxGas = 0 } if (object.timeIotaMs !== undefined && object.timeIotaMs !== null) { message.timeIotaMs = Number(object.timeIotaMs) } else { message.timeIotaMs = 0 } return message }, toJSON(message: BlockParams): unknown { const obj: any = {} message.maxBytes !== undefined && (obj.maxBytes = message.maxBytes) message.maxGas !== undefined && (obj.maxGas = message.maxGas) message.timeIotaMs !== undefined && (obj.timeIotaMs = message.timeIotaMs) return obj }, fromPartial(object: DeepPartial<BlockParams>): BlockParams { const message = { ...baseBlockParams } as BlockParams if (object.maxBytes !== undefined && object.maxBytes !== null) { message.maxBytes = object.maxBytes } else { message.maxBytes = 0 } if (object.maxGas !== undefined && object.maxGas !== null) { message.maxGas = object.maxGas } else { message.maxGas = 0 } if (object.timeIotaMs !== undefined && object.timeIotaMs !== null) { message.timeIotaMs = object.timeIotaMs } else { message.timeIotaMs = 0 } return message } } const baseEvidenceParams: object = { maxAgeNumBlocks: 0, maxBytes: 0 } export const EvidenceParams = { encode(message: EvidenceParams, writer: Writer = Writer.create()): Writer { if (message.maxAgeNumBlocks !== 0) { writer.uint32(8).int64(message.maxAgeNumBlocks) } if (message.maxAgeDuration !== undefined) { Duration.encode(message.maxAgeDuration, writer.uint32(18).fork()).ldelim() } if (message.maxBytes !== 0) { writer.uint32(24).int64(message.maxBytes) } return writer }, decode(input: Reader | Uint8Array, length?: number): EvidenceParams { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseEvidenceParams } as EvidenceParams while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.maxAgeNumBlocks = longToNumber(reader.int64() as Long) break case 2: message.maxAgeDuration = Duration.decode(reader, reader.uint32()) break case 3: message.maxBytes = longToNumber(reader.int64() as Long) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): EvidenceParams { const message = { ...baseEvidenceParams } as EvidenceParams if ( object.maxAgeNumBlocks !== undefined && object.maxAgeNumBlocks !== null ) { message.maxAgeNumBlocks = Number(object.maxAgeNumBlocks) } else { message.maxAgeNumBlocks = 0 } if (object.maxAgeDuration !== undefined && object.maxAgeDuration !== null) { message.maxAgeDuration = Duration.fromJSON(object.maxAgeDuration) } else { message.maxAgeDuration = undefined } if (object.maxBytes !== undefined && object.maxBytes !== null) { message.maxBytes = Number(object.maxBytes) } else { message.maxBytes = 0 } return message }, toJSON(message: EvidenceParams): unknown { const obj: any = {} message.maxAgeNumBlocks !== undefined && (obj.maxAgeNumBlocks = message.maxAgeNumBlocks) message.maxAgeDuration !== undefined && (obj.maxAgeDuration = message.maxAgeDuration ? Duration.toJSON(message.maxAgeDuration) : undefined) message.maxBytes !== undefined && (obj.maxBytes = message.maxBytes) return obj }, fromPartial(object: DeepPartial<EvidenceParams>): EvidenceParams { const message = { ...baseEvidenceParams } as EvidenceParams if ( object.maxAgeNumBlocks !== undefined && object.maxAgeNumBlocks !== null ) { message.maxAgeNumBlocks = object.maxAgeNumBlocks } else { message.maxAgeNumBlocks = 0 } if (object.maxAgeDuration !== undefined && object.maxAgeDuration !== null) { message.maxAgeDuration = Duration.fromPartial(object.maxAgeDuration) } else { message.maxAgeDuration = undefined } if (object.maxBytes !== undefined && object.maxBytes !== null) { message.maxBytes = object.maxBytes } else { message.maxBytes = 0 } return message } } const baseValidatorParams: object = { pubKeyTypes: '' } export const ValidatorParams = { encode(message: ValidatorParams, writer: Writer = Writer.create()): Writer { for (const v of message.pubKeyTypes) { writer.uint32(10).string(v!) } return writer }, decode(input: Reader | Uint8Array, length?: number): ValidatorParams { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseValidatorParams } as ValidatorParams message.pubKeyTypes = [] while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.pubKeyTypes.push(reader.string()) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): ValidatorParams { const message = { ...baseValidatorParams } as ValidatorParams message.pubKeyTypes = [] if (object.pubKeyTypes !== undefined && object.pubKeyTypes !== null) { for (const e of object.pubKeyTypes) { message.pubKeyTypes.push(String(e)) } } return message }, toJSON(message: ValidatorParams): unknown { const obj: any = {} if (message.pubKeyTypes) { obj.pubKeyTypes = message.pubKeyTypes.map((e) => e) } else { obj.pubKeyTypes = [] } return obj }, fromPartial(object: DeepPartial<ValidatorParams>): ValidatorParams { const message = { ...baseValidatorParams } as ValidatorParams message.pubKeyTypes = [] if (object.pubKeyTypes !== undefined && object.pubKeyTypes !== null) { for (const e of object.pubKeyTypes) { message.pubKeyTypes.push(e) } } return message } } const baseVersionParams: object = { appVersion: 0 } export const VersionParams = { encode(message: VersionParams, writer: Writer = Writer.create()): Writer { if (message.appVersion !== 0) { writer.uint32(8).uint64(message.appVersion) } return writer }, decode(input: Reader | Uint8Array, length?: number): VersionParams { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseVersionParams } as VersionParams while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.appVersion = longToNumber(reader.uint64() as Long) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): VersionParams { const message = { ...baseVersionParams } as VersionParams if (object.appVersion !== undefined && object.appVersion !== null) { message.appVersion = Number(object.appVersion) } else { message.appVersion = 0 } return message }, toJSON(message: VersionParams): unknown { const obj: any = {} message.appVersion !== undefined && (obj.appVersion = message.appVersion) return obj }, fromPartial(object: DeepPartial<VersionParams>): VersionParams { const message = { ...baseVersionParams } as VersionParams if (object.appVersion !== undefined && object.appVersion !== null) { message.appVersion = object.appVersion } else { message.appVersion = 0 } return message } } const baseHashedParams: object = { blockMaxBytes: 0, blockMaxGas: 0 } export const HashedParams = { encode(message: HashedParams, writer: Writer = Writer.create()): Writer { if (message.blockMaxBytes !== 0) { writer.uint32(8).int64(message.blockMaxBytes) } if (message.blockMaxGas !== 0) { writer.uint32(16).int64(message.blockMaxGas) } return writer }, decode(input: Reader | Uint8Array, length?: number): HashedParams { const reader = input instanceof Uint8Array ? new Reader(input) : input let end = length === undefined ? reader.len : reader.pos + length const message = { ...baseHashedParams } as HashedParams while (reader.pos < end) { const tag = reader.uint32() switch (tag >>> 3) { case 1: message.blockMaxBytes = longToNumber(reader.int64() as Long) break case 2: message.blockMaxGas = longToNumber(reader.int64() as Long) break default: reader.skipType(tag & 7) break } } return message }, fromJSON(object: any): HashedParams { const message = { ...baseHashedParams } as HashedParams if (object.blockMaxBytes !== undefined && object.blockMaxBytes !== null) { message.blockMaxBytes = Number(object.blockMaxBytes) } else { message.blockMaxBytes = 0 } if (object.blockMaxGas !== undefined && object.blockMaxGas !== null) { message.blockMaxGas = Number(object.blockMaxGas) } else { message.blockMaxGas = 0 } return message }, toJSON(message: HashedParams): unknown { const obj: any = {} message.blockMaxBytes !== undefined && (obj.blockMaxBytes = message.blockMaxBytes) message.blockMaxGas !== undefined && (obj.blockMaxGas = message.blockMaxGas) return obj }, fromPartial(object: DeepPartial<HashedParams>): HashedParams { const message = { ...baseHashedParams } as HashedParams if (object.blockMaxBytes !== undefined && object.blockMaxBytes !== null) { message.blockMaxBytes = object.blockMaxBytes } else { message.blockMaxBytes = 0 } if (object.blockMaxGas !== undefined && object.blockMaxGas !== null) { message.blockMaxGas = object.blockMaxGas } else { message.blockMaxGas = 0 } return message } } declare var self: any | undefined declare var window: any | undefined var globalThis: any = (() => { if (typeof globalThis !== 'undefined') return globalThis if (typeof self !== 'undefined') return self if (typeof window !== 'undefined') return window if (typeof global !== 'undefined') return global throw 'Unable to locate global object' })() type Builtin = Date | Function | Uint8Array | string | number | undefined export type DeepPartial<T> = T extends Builtin ? T : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>> : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> } : Partial<T> function longToNumber(long: Long): number { if (long.gt(Number.MAX_SAFE_INTEGER)) { throw new globalThis.Error('Value is larger than Number.MAX_SAFE_INTEGER') } return long.toNumber() } if (util.Long !== Long) { util.Long = Long as any configure() }
the_stack
import chai, { expect } from 'chai' import { Console } from 'console' import { solidity } from 'ethereum-waffle' import { BigNumber, Signer } from 'ethers' import hre from 'hardhat' import { getMarkets, isEtheremNetwork } from '../../config' import { getPlatformSetting, updatePlatformSetting } from '../../tasks' import { Market } from '../../types/custom/config-types' import { ITellerDiamond, MainnetNFTFacet } from '../../types/typechain' import { LoanStatus } from '../../utils/consts' import { fundedMarket } from '../fixtures' import { getFunds } from '../helpers/get-funds' import { LoanHelpersReturn, LoanType, takeOutLoanWithNfts, takeOutLoanWithoutNfts, } from '../helpers/loans' chai.should() chai.use(solidity) const { getNamedSigner, contracts, tokens, ethers, evm, toBN } = hre describe('Loans', () => { getMarkets(hre.network).forEach(testLoans) function testLoans(market: Market): void { let deployer: Signer let diamond: ITellerDiamond & MainnetNFTFacet // let borrower: Signer before(async () => { await fundedMarket(hre, { assetSym: market.lendingToken, amount: 100000, keepExistingDeployments: true, extendMaxTVL: true, }) deployer = await getNamedSigner('deployer') diamond = await contracts.get('TellerDiamond') }) // tests for merged loan functions describe('merge create loan', () => { let helpers: any = null before(async () => { // update percentage submission percentage value to 0 for this test const percentageSubmission = { name: 'RequiredSubmissionsPercentage', value: 0, } await updatePlatformSetting(percentageSubmission, hre) // Advance time const { value: rateLimit } = await getPlatformSetting( 'RequestLoanTermsRateLimit', hre ) await evm.advanceTime(rateLimit) }) describe('without NFT', () => { it('should create a loan', async () => { // get helpers variables after function returns our transaction and // helper variables const { getHelpers } = await takeOutLoanWithoutNfts(hre, { lendToken: market.lendingToken, collToken: market.collateralTokens[0], loanType: LoanType.UNDER_COLLATERALIZED, }) helpers = await getHelpers() // borrower data from our helpers // borrower = helpers.details.borrower.signer // check if loan exists expect(helpers.details.loan).to.exist }) it('should have collateral deposited', async () => { // get collateral const { collateral } = helpers const amount = await collateral.current() // check if collateral is > 0 amount.gt(0).should.eq(true, 'Loan must have collateral') }) it('should be taken out', () => { // get loanStatus from helpers and check if it's equal to 2, which means // it's active and taken out const loanStatus = helpers.details.loan.status expect(loanStatus).to.equal(2) }) it('should not be able to take out a loan when loan facet is paused', async () => { const LOANS_ID = hre.ethers.utils.id('LOANS') // Pause lending await diamond .connect(deployer) .pause(LOANS_ID, true) .should.emit(diamond, 'Paused') .withArgs(LOANS_ID, await deployer.getAddress()) // trying to run the function will revert with the same error message // written in our PausableMods file const { tx } = await takeOutLoanWithoutNfts(hre, { lendToken: market.lendingToken, collToken: market.collateralTokens[0], loanType: LoanType.UNDER_COLLATERALIZED, }) await tx.should.be.revertedWith('Pausable: paused') // Unpause lending await diamond .connect(deployer) .pause(LOANS_ID, false) .should.emit(diamond, 'UnPaused') .withArgs(LOANS_ID, await deployer.getAddress()) }) // it('should not be able to take out a loan without enough collateral', async () => { // const { tx } = await takeOutLoanWithoutNfts({ // lendToken: market.lendingToken, // collToken: market.collateralTokens[0], // loanType: LoanType.OVER_COLLATERALIZED, // collAmount: 1 // }) // // Try to take out loan which should fail // await tx.should.be.revertedWith('Teller: more collateral required') // }) }) describe('with NFT', () => { beforeEach(async () => { await hre.deployments.fixture('protocol', { keepExistingDeployments: true, }) // Advance time const { value: rateLimit } = await getPlatformSetting( 'RequestLoanTermsRateLimit', hre ) await evm.advanceTime(rateLimit) }) if (isEtheremNetwork(hre.network)) { describe('V1', () => { let helpers: LoanHelpersReturn it('creates a loan', async () => { // get helpers const borrower = await getNamedSigner('borrower') const { nfts, getHelpers } = await takeOutLoanWithNfts(hre, { amount: 100, lendToken: market.lendingToken, borrower, version: 1, }) helpers = await getHelpers() helpers.details.loan.should.exist // get loanStatus from helpers and check if it's equal to 2, which means it's active const loanStatus = helpers.details.loan.status loanStatus.should.equal(2, 'Loan is not active') const loanNFTs = await diamond.getLoanNFTs( helpers.details.loan.id ) loanNFTs.should.eql(nfts.v1, 'Staked NFTs do not match') }) it('should be able to create and repay a loan', async () => { const borrower = await getNamedSigner('borrower') const { getHelpers } = await takeOutLoanWithNfts(hre, { amount: 100, lendToken: market.lendingToken, borrower: borrower, version: 1, }) const helpers: LoanHelpersReturn = await getHelpers() expect(helpers.details.loan).to.exist const loanId = helpers.details.loan.id const lendingToken = helpers.details.lendingToken const lendingTokenDecimals = await lendingToken.decimals() //add lending token funds to the borrower await getFunds({ to: borrower, tokenSym: market.lendingToken, amount: hre.toBN(200, lendingTokenDecimals), hre, }) const borrowerAddress = await borrower.getAddress() const borrowerBalance = await lendingToken.balanceOf( borrowerAddress ) const balanceLeftToRepay = await diamond.getTotalOwed(loanId) await lendingToken .connect(borrower) .approve(diamond.address, balanceLeftToRepay) await diamond .connect(borrower) .repayLoan(loanId, balanceLeftToRepay) const totalOwedAfterRepay = await diamond.getTotalOwed(loanId) const loanData = await diamond.getLoan(loanId) totalOwedAfterRepay.should.eql(0) expect(loanData.status).to.equal(LoanStatus.Closed) }) it('should be able to create and repay a loan to restake NFTs', async () => { const borrower = await getNamedSigner('borrower') const { getHelpers } = await takeOutLoanWithNfts(hre, { amount: 100, lendToken: market.lendingToken, borrower: borrower, version: 1, }) const helpers: LoanHelpersReturn = await getHelpers() expect(helpers.details.loan).to.exist const loanId = helpers.details.loan.id const lendingToken = helpers.details.lendingToken const lendingTokenDecimals = await lendingToken.decimals() await getFunds({ to: borrower, tokenSym: market.lendingToken, amount: hre.toBN(200, lendingTokenDecimals), hre, }) const borrowerAddress = await borrower.getAddress() const borrowerBalance = await lendingToken.balanceOf( borrowerAddress ) const balanceLeftToRepay = await diamond.getTotalOwed(loanId) await lendingToken .connect(borrower) .approve(diamond.address, balanceLeftToRepay) const stakedNFTsBeforeRepay = await diamond.getStakedNFTs( borrowerAddress ) const loanNFTsBeforeRepay = await diamond.getLoanNFTs(loanId) expect(stakedNFTsBeforeRepay.length).to.equal(0) await diamond .connect(borrower) .repayLoan(loanId, hre.toBN(100, lendingTokenDecimals)) const totalOwedAfterRepay = await diamond.getTotalOwed(loanId) const loanData = await diamond.getLoan(loanId) const stakedNFTsAfterRepay = await diamond.getStakedNFTs( borrowerAddress ) expect(stakedNFTsAfterRepay.length).to.equal( loanNFTsBeforeRepay.length ) totalOwedAfterRepay.should.eql(0) expect(loanData.status).to.equal(LoanStatus.Closed) }) }) describe('V3', () => { let helpers: LoanHelpersReturn it('creates a loan from v1 and v2 Ids', async () => { const borrower = await getNamedSigner('borrower') const { nfts, getHelpers } = await takeOutLoanWithNfts(hre, { amount: 100, lendToken: market.lendingToken, borrower, version: 3, }) helpers = await getHelpers() helpers.details.loan.should.exist // get loanStatus from helpers and check if it's equal to 2, which means it's active const loanStatus = helpers.details.loan.status loanStatus.should.equal(2, 'Loan is not active') // get loan NFTs from our loan const loanNFTs = await diamond.getLoanNFTs( helpers.details.loan.id ) const loanNFTsV2 = await diamond.getLoanNFTsV2( helpers.details.loan.id ) // check if loan NFTs are equal to each other loanNFTs.should.eql(nfts.v1, 'Staked NFTs do not match') loanNFTsV2.loanNFTs_.should.eql( nfts.v2.ids, 'Staked NFT IDs do not match' ) loanNFTsV2.amounts_.should.eql( nfts.v2.balances, 'Staked NFT balances do not match' ) }) }) } describe('V2', () => { let helpers: LoanHelpersReturn it('creates a loan', async () => { // get helpers const borrower = await getNamedSigner('borrower') const { nfts, getHelpers } = await takeOutLoanWithNfts(hre, { amount: 100, lendToken: market.lendingToken, borrower, version: 2, }) helpers = await getHelpers() helpers.details.loan.should.exist const loanStatus = helpers.details.loan.status loanStatus.should.equal(LoanStatus.Active, 'Loan is not active') const loanNFTsV2 = await diamond.getLoanNFTsV2( helpers.details.loan.id ) loanNFTsV2.loanNFTs_.should.eql( nfts.v2.ids, 'Staked NFT IDs do not match' ) loanNFTsV2.amounts_.should.eql( nfts.v2.balances, 'Staked NFT balances do not match' ) }) it('should be able to create and repay a loan', async () => { const borrower = await getNamedSigner('borrower') const { getHelpers } = await takeOutLoanWithNfts(hre, { amount: 100, lendToken: market.lendingToken, borrower: borrower, version: 2, }) const helpers: LoanHelpersReturn = await getHelpers() expect(helpers.details.loan).to.exist const loanId = helpers.details.loan.id const lendingToken = helpers.details.lendingToken const lendingTokenDecimals = await lendingToken.decimals() await getFunds({ to: borrower, tokenSym: market.lendingToken, amount: hre.toBN(200, lendingTokenDecimals), hre, }) const borrowerAddress = await borrower.getAddress() const borrowerBalance = await lendingToken.balanceOf( borrowerAddress ) const balanceLeftToRepay = await diamond.getTotalOwed(loanId) await lendingToken .connect(borrower) .approve(diamond.address, balanceLeftToRepay) const stakedNFTsBeforeRepay = await diamond.getStakedNFTsV2( borrowerAddress ) const loanNFTs = await diamond.getLoanNFTsV2(loanId) expect(stakedNFTsBeforeRepay.staked_.length).to.equal(0) await diamond .connect(borrower) .repayLoan(loanId, hre.toBN(100, lendingTokenDecimals)) const totalOwedAfterRepay = await diamond.getTotalOwed(loanId) const loanData = await diamond.getLoan(loanId) const stakedNFTsAfterRepay = await diamond.getStakedNFTsV2( borrowerAddress ) expect(stakedNFTsAfterRepay.staked_.length).to.equal( loanNFTs.loanNFTs_.length + stakedNFTsBeforeRepay.staked_.length ) const stakedNFTAmounts = stakedNFTsAfterRepay.staked_.reduce<{ [nftID: string]: BigNumber }>((obj, nftID, i) => { obj[nftID.toString()] = stakedNFTsAfterRepay.amounts_[i] return obj }, {}) for (let i = 0; i < loanNFTs.loanNFTs_.length; i++) { const nftID = loanNFTs.loanNFTs_[i] const stakedNFTBeforeRepayAmount = stakedNFTsBeforeRepay.amounts_[i] ?? 0 const expectedAmount = loanNFTs.amounts_[i].add( stakedNFTBeforeRepayAmount ) stakedNFTAmounts[nftID.toString()].should.eql(expectedAmount) } totalOwedAfterRepay.should.eql(0) expect(loanData.status).to.equal(LoanStatus.Closed) }) }) }) }) } })
the_stack
import * as Constants from "./Constants"; import { CryptoManager, BoxCryptoManager, LoginCryptoManager, concatArrayBuffersArrays } from "./Crypto"; import { IntegrityError, MissingContentError } from "./Exceptions"; import { base64, fromBase64, toBase64, fromString, toString, randomBytes, symmetricKeyLength, msgpackEncode, msgpackDecode, bufferPad, bufferUnpad, memcmp, shuffle, bufferPadSmall, bufferPadFixed, bufferUnpadFixed } from "./Helpers"; import { SignedInvitationContent } from "./Etebase"; export type CollectionType = string; export type ContentType = File | Blob | Uint8Array | string | null; export type ItemMetadata<T = {}> = { type?: string; name?: string; // The name of the item, e.g. filename in case of files mtime?: number; // The modification time description?: string; color?: string; } & T; export type ChunkJson = [base64, Uint8Array?]; export interface CollectionItemRevisionJsonWrite { uid: base64; meta: Uint8Array; chunks: ChunkJson[]; deleted: boolean; } export type CollectionItemRevisionJsonRead = CollectionItemRevisionJsonWrite; export interface CollectionItemJsonWrite { uid: base64; version: number; encryptionKey?: Uint8Array; content: CollectionItemRevisionJsonWrite; etag: string | null; } export type CollectionItemJsonRead = CollectionItemJsonWrite; export enum CollectionAccessLevel { ReadOnly = 0, Admin = 1, ReadWrite = 2, } export interface CollectionJsonWrite { collectionKey: Uint8Array; item: CollectionItemJsonWrite; collectionType: Uint8Array; } export interface CollectionJsonRead extends CollectionJsonWrite { accessLevel: CollectionAccessLevel; stoken: string | null; // FIXME: hack, we shouldn't expose it here... item: CollectionItemJsonRead; } export interface SignedInvitationWrite { uid: base64; version: number; username: string; collection: base64; accessLevel: CollectionAccessLevel; signedEncryptionKey: Uint8Array; } export interface SignedInvitationRead extends SignedInvitationWrite { fromUsername?: string; fromPubkey: Uint8Array; } function genUidBase64(): base64 { return toBase64(randomBytes(24)); } export class MainCryptoManager extends CryptoManager { protected Main = true; // So classes are different constructor(key: Uint8Array, version: number = Constants.CURRENT_VERSION) { super(key, "Main", version); } public getLoginCryptoManager(): LoginCryptoManager { return LoginCryptoManager.keygen(this.asymKeySeed); } public getAccountCryptoManager(privkey: Uint8Array): AccountCryptoManager { return new AccountCryptoManager(privkey, this.version); } public getIdentityCryptoManager(privkey: Uint8Array): BoxCryptoManager { return BoxCryptoManager.fromPrivkey(privkey); } } export class AccountCryptoManager extends CryptoManager { protected Account = true; // So classes are different private colTypePadSize = 32; constructor(key: Uint8Array, version: number = Constants.CURRENT_VERSION) { super(key, "Acct", version); } public colTypeToUid(colType: string): Uint8Array { return this.deterministicEncrypt(bufferPadFixed(fromString(colType), this.colTypePadSize)); } public colTypeFromUid(colTypeUid: Uint8Array): string { return toString(bufferUnpadFixed(this.deterministicDecrypt(colTypeUid), this.colTypePadSize)); } } export class MinimalCollectionCryptoManager extends CryptoManager { protected Collection = true; // So classes are different constructor(key: Uint8Array, version: number = Constants.CURRENT_VERSION) { super(key, "Col", version); } } export class CollectionCryptoManager extends MinimalCollectionCryptoManager { public readonly accountCryptoManager: AccountCryptoManager; constructor(accountCryptoManager: AccountCryptoManager, key: Uint8Array, version: number = Constants.CURRENT_VERSION) { super(key, version); this.accountCryptoManager = accountCryptoManager; } } export class CollectionItemCryptoManager extends CryptoManager { protected CollectionItem = true; // So classes are different constructor(key: Uint8Array, version: number = Constants.CURRENT_VERSION) { super(key, "ColItem", version); } } export class StorageCryptoManager extends CryptoManager { protected Storage = true; // So classes are different constructor(key: Uint8Array, version: number = Constants.CURRENT_VERSION) { super(key, "Stor", version); } } export function getMainCryptoManager(mainEncryptionKey: Uint8Array, version: number) { return new MainCryptoManager(mainEncryptionKey, version); } class EncryptedRevision<CM extends CollectionItemCryptoManager> { public uid: base64; public meta: Uint8Array; public deleted: boolean; public chunks: [base64, Uint8Array?][]; constructor() { this.deleted = false; } public static async create<CM extends CollectionItemCryptoManager>(cryptoManager: CM, additionalData: Uint8Array, meta: any, content: Uint8Array): Promise<EncryptedRevision<CM>> { const ret = new EncryptedRevision<CM>(); ret.chunks = []; ret.setMeta(cryptoManager, additionalData, meta); await ret.setContent(cryptoManager, additionalData, content); return ret; } public static deserialize<CM extends CollectionItemCryptoManager>(json: CollectionItemRevisionJsonRead) { const { uid, meta, chunks, deleted } = json; const ret = new EncryptedRevision<CM>(); ret.uid = uid; ret.meta = meta; ret.deleted = deleted; ret.chunks = chunks.map((chunk) => { return [chunk[0], chunk[1] ?? undefined]; }); return ret; } public serialize() { const ret: CollectionItemRevisionJsonWrite = { uid: this.uid, meta: this.meta, deleted: this.deleted, chunks: this.chunks.map((chunk) => [chunk[0], chunk[1] ?? undefined]), }; return ret; } public static cacheLoad<CM extends CollectionItemCryptoManager>(cached_: Uint8Array) { const cached = msgpackDecode(cached_) as any[]; const ret = new EncryptedRevision<CM>(); ret.uid = toBase64(cached[0]); ret.meta = cached[1]; ret.deleted = cached[2]; ret.chunks = cached[3].map((chunk: Uint8Array[]) => [ toBase64(chunk[0]), chunk[1] ?? undefined, ]); return ret; } public cacheSave(saveContent: boolean): Uint8Array { return msgpackEncode([ fromBase64(this.uid), this.meta, this.deleted, ((saveContent) ? this.chunks.map((chunk) => [fromBase64(chunk[0]), chunk[1] ?? null]) : this.chunks.map((chunk) => [fromBase64(chunk[0])]) ), ]); } public verify(cryptoManager: CM, additionalData: Uint8Array) { const adHash = this.calculateAdHash(cryptoManager, additionalData); const mac = fromBase64(this.uid); try { cryptoManager.verify(this.meta, mac, adHash); return true; } catch (e) { throw new IntegrityError(`mac verification failed.`); } } private calculateAdHash(cryptoManager: CM, additionalData: Uint8Array) { const cryptoMac = cryptoManager.getCryptoMac(); cryptoMac.update(new Uint8Array([(this.deleted) ? 1 : 0])); cryptoMac.updateWithLenPrefix(additionalData); // We hash the chunks separately so that the server can (in the future) return just the hash instead of the full // chunk list if requested - useful for asking for collection updates const chunksHash = cryptoManager.getCryptoMac(false); this.chunks.forEach((chunk) => chunksHash.update(fromBase64(chunk[0])) ); cryptoMac.update(chunksHash.finalize()); return cryptoMac.finalize(); } public setMeta(cryptoManager: CM, additionalData: Uint8Array, meta: any): void { const adHash = this.calculateAdHash(cryptoManager, additionalData); const encContent = cryptoManager.encryptDetached(bufferPadSmall(msgpackEncode(meta)), adHash); this.meta = encContent[1]; this.uid = toBase64(encContent[0]); } public getMeta(cryptoManager: CM, additionalData: Uint8Array): any { const mac = fromBase64(this.uid); const adHash = this.calculateAdHash(cryptoManager, additionalData); return msgpackDecode(bufferUnpad(cryptoManager.decryptDetached(this.meta, mac, adHash))); } public async setContent(cryptoManager: CM, additionalData: Uint8Array, content: Uint8Array): Promise<void> { const meta = this.getMeta(cryptoManager, additionalData); let chunks: [base64, Uint8Array][] = []; const minChunk = 1 << 14; const maxChunk = 1 << 16; let chunkStart = 0; // Only try chunking if our content is larger than the minimum chunk size if (content.length > minChunk) { // FIXME: figure out what to do with mask - should it be configurable? const buzhash = cryptoManager.getChunker(); const mask = (1 << 12) - 1; let pos = 0; while (pos < content.length) { buzhash.update(content[pos]); if (pos - chunkStart >= minChunk) { if ((pos - chunkStart >= maxChunk) || (buzhash.split(mask))) { const buf = content.subarray(chunkStart, pos); const hash = toBase64(cryptoManager.calculateMac(buf)); chunks.push([hash, buf]); chunkStart = pos; } } pos++; } } if (chunkStart < content.length) { const buf = content.subarray(chunkStart); const hash = toBase64(cryptoManager.calculateMac(buf)); chunks.push([hash, buf]); } // Shuffle the items and save the ordering if we have more than one if (chunks.length > 0) { const indices = shuffle(chunks); // Filter duplicates and construct the indice list. const uidIndices = new Map<string, number>(); chunks = chunks.filter((chunk, i) => { const uid = chunk[0]; const previousIndex = uidIndices.get(uid); if (previousIndex !== undefined) { indices[i] = previousIndex; return false; } else { uidIndices.set(uid, i); return true; } }); // If we have more than one chunk we need to encode the mapping header in the last chunk if (indices.length > 1) { // We encode it in an array so we can extend it later on if needed const buf = msgpackEncode([indices]); const hash = toBase64(cryptoManager.calculateMac(buf)); chunks.push([hash, buf]); } } // Encrypt all of the chunks this.chunks = chunks.map((chunk) => [chunk[0], cryptoManager.encrypt(bufferPad(chunk[1]))]); this.setMeta(cryptoManager, additionalData, meta); } public async getContent(cryptoManager: CM): Promise<Uint8Array> { let indices: number[] = [0]; const decryptedChunks: Uint8Array[] = this.chunks.map((chunk) => { if (!chunk[1]) { throw new MissingContentError("Missing content for item. Please download it using `downloadContent`"); } const buf = bufferUnpad(cryptoManager.decrypt(chunk[1])); const hash = cryptoManager.calculateMac(buf); if (!memcmp(hash, fromBase64(chunk[0]))) { throw new IntegrityError(`The content's mac is different to the expected mac (${chunk[0]})`); } return buf; }); // If we have more than one chunk we have the mapping header in the last chunk if (this.chunks.length > 1) { const lastChunk = msgpackDecode(decryptedChunks.pop()!) as [number[]]; indices = lastChunk[0]; } // We need to unshuffle the chunks if (indices.length > 1) { const sortedChunks: Uint8Array[] = []; for (const index of indices) { sortedChunks.push(decryptedChunks[index]); } return concatArrayBuffersArrays(sortedChunks); } else if (decryptedChunks.length > 0) { return decryptedChunks[0]; } else { return new Uint8Array(); } } public delete(cryptoManager: CM, additionalData: Uint8Array, preserveContent: boolean): void { const meta = this.getMeta(cryptoManager, additionalData); if (!preserveContent) { this.chunks = []; } this.deleted = true; this.setMeta(cryptoManager, additionalData, meta); } public clone() { const rev = new EncryptedRevision<CM>(); rev.uid = this.uid; rev.meta = this.meta; rev.chunks = this.chunks; rev.deleted = this.deleted; return rev; } } export class EncryptedCollection { private collectionKey: Uint8Array; private collectionType: Uint8Array; public item: EncryptedCollectionItem; public accessLevel: CollectionAccessLevel; public stoken: string | null; // FIXME: hack, we shouldn't expose it here... public static async create<T>(parentCryptoManager: AccountCryptoManager, collectionTypeName: string, meta: ItemMetadata<T>, content: Uint8Array): Promise<EncryptedCollection> { const ret = new EncryptedCollection(); ret.collectionType = parentCryptoManager.colTypeToUid(collectionTypeName); ret.collectionKey = parentCryptoManager.encrypt(randomBytes(symmetricKeyLength), ret.collectionType); ret.accessLevel = CollectionAccessLevel.Admin; ret.stoken = null; const cryptoManager = ret.getCryptoManager(parentCryptoManager, Constants.CURRENT_VERSION); ret.item = await EncryptedCollectionItem.create(cryptoManager, meta, content); return ret; } public static deserialize(json: CollectionJsonRead): EncryptedCollection { const { stoken, accessLevel, collectionType, collectionKey } = json; const ret = new EncryptedCollection(); ret.collectionKey = collectionKey; ret.item = EncryptedCollectionItem.deserialize(json.item); ret.collectionType = collectionType; ret.accessLevel = accessLevel; ret.stoken = stoken; return ret; } public serialize() { const ret: CollectionJsonWrite = { item: this.item.serialize(), collectionType: this.collectionType, collectionKey: this.collectionKey, }; return ret; } public static cacheLoad(cached_: Uint8Array) { const cached = msgpackDecode(cached_) as any[]; const ret = new EncryptedCollection(); ret.collectionKey = cached[1]; ret.accessLevel = cached[2]; ret.stoken = cached[3]; ret.item = EncryptedCollectionItem.cacheLoad(cached[4]); ret.collectionType = cached[5]; return ret; } public cacheSave(saveContent: boolean) { return msgpackEncode([ 1, // Cache version format this.collectionKey, this.accessLevel, this.stoken, this.item.cacheSave(saveContent), this.collectionType, ]); } public __markSaved() { this.item.__markSaved(); } public verify(cryptoManager: MinimalCollectionCryptoManager) { const itemCryptoManager = this.item.getCryptoManager(cryptoManager); return this.item.verify(itemCryptoManager); } public setMeta<T>(cryptoManager: MinimalCollectionCryptoManager, meta: ItemMetadata<T>): void { const itemCryptoManager = this.item.getCryptoManager(cryptoManager); this.item.setMeta(itemCryptoManager, meta); } public getMeta<T>(cryptoManager: MinimalCollectionCryptoManager): ItemMetadata<T> { this.verify(cryptoManager); const itemCryptoManager = this.item.getCryptoManager(cryptoManager); return this.item.getMeta(itemCryptoManager); } public async setContent(cryptoManager: MinimalCollectionCryptoManager, content: Uint8Array): Promise<void> { const itemCryptoManager = this.item.getCryptoManager(cryptoManager); return this.item.setContent(itemCryptoManager, content); } public async getContent(cryptoManager: MinimalCollectionCryptoManager): Promise<Uint8Array> { this.verify(cryptoManager); const itemCryptoManager = this.item.getCryptoManager(cryptoManager); return this.item.getContent(itemCryptoManager); } public delete(cryptoManager: MinimalCollectionCryptoManager, preserveContent: boolean): void { const itemCryptoManager = this.item.getCryptoManager(cryptoManager); this.item.delete(itemCryptoManager, preserveContent); } public get isDeleted() { return this.item.isDeleted; } public get uid() { return this.item.uid; } public get etag() { return this.item.etag; } public get lastEtag() { return this.item.lastEtag; } public get version() { return this.item.version; } public getCollectionType(parentCryptoManager: AccountCryptoManager): string { // FIXME: remove this condition "collection-type-migration" is done if (!this.collectionType) { const cryptoManager = this.getCryptoManager(parentCryptoManager); const meta = this.getMeta(cryptoManager); return meta.type!!; } return parentCryptoManager.colTypeFromUid(this.collectionType); } public async createInvitation(parentCryptoManager: AccountCryptoManager, identCryptoManager: BoxCryptoManager, username: string, pubkey: Uint8Array, accessLevel: CollectionAccessLevel): Promise<SignedInvitationWrite> { const uid = randomBytes(32); const encryptionKey = this.getCollectionKey(parentCryptoManager); const collectionType = this.getCollectionType(parentCryptoManager); const content: SignedInvitationContent = { encryptionKey, collectionType }; const rawContent = bufferPadSmall(msgpackEncode(content)); const signedEncryptionKey = identCryptoManager.encrypt(rawContent, pubkey); const ret: SignedInvitationWrite = { version: Constants.CURRENT_VERSION, uid: toBase64(uid), username, collection: this.uid, accessLevel, signedEncryptionKey, }; return ret; } public getCryptoManager(parentCryptoManager: AccountCryptoManager, version?: number) { const encryptionKey = this.getCollectionKey(parentCryptoManager); return new CollectionCryptoManager(parentCryptoManager, encryptionKey, version ?? this.version); } private getCollectionKey(parentCryptoManager: AccountCryptoManager) { // FIXME: remove the ?? null once "collection-type-migration" is done return parentCryptoManager.decrypt(this.collectionKey, this.collectionType ?? null).subarray(0, symmetricKeyLength); } } export class EncryptedCollectionItem { public uid: base64; public version: number; private encryptionKey: Uint8Array | null; private content: EncryptedRevision<CollectionItemCryptoManager>; public lastEtag: string | null; public static async create<T>(parentCryptoManager: MinimalCollectionCryptoManager, meta: ItemMetadata<T>, content: Uint8Array): Promise<EncryptedCollectionItem> { const ret = new EncryptedCollectionItem(); ret.uid = genUidBase64(); ret.version = Constants.CURRENT_VERSION; ret.encryptionKey = null; ret.lastEtag = null; const cryptoManager = ret.getCryptoManager(parentCryptoManager); ret.content = await EncryptedRevision.create(cryptoManager, ret.getAdditionalMacData(), meta, content); return ret; } public static deserialize(json: CollectionItemJsonRead): EncryptedCollectionItem { const { uid, version, encryptionKey, content } = json; const ret = new EncryptedCollectionItem(); ret.uid = uid; ret.version = version; ret.encryptionKey = encryptionKey ?? null; ret.content = EncryptedRevision.deserialize(content); ret.lastEtag = ret.content.uid; return ret; } public serialize() { const ret: CollectionItemJsonWrite = { uid: this.uid, version: this.version, encryptionKey: this.encryptionKey ?? undefined, etag: this.lastEtag, content: this.content.serialize(), }; return ret; } public static cacheLoad(cached_: Uint8Array) { const cached = msgpackDecode(cached_) as any[]; const ret = new EncryptedCollectionItem(); ret.uid = toBase64(cached[1]); ret.version = cached[2]; ret.encryptionKey = cached[3]; ret.lastEtag = (cached[4]) ? toBase64(cached[4]) : null; ret.content = EncryptedRevision.cacheLoad(cached[5]); return ret; } public cacheSave(saveContent: boolean) { return msgpackEncode([ 1, // Cache version format fromBase64(this.uid), this.version, this.encryptionKey, (this.lastEtag) ? fromBase64(this.lastEtag) : null, this.content.cacheSave(saveContent), ]); } public __markSaved() { this.lastEtag = this.content.uid; } public __getPendingChunks(): ChunkJson[] { return this.content.chunks; } public __getMissingChunks(): ChunkJson[] { return this.content.chunks.filter(([_uid, content]) => !content); } private isLocallyChanged() { return this.lastEtag !== this.content.uid; } public verify(cryptoManager: CollectionItemCryptoManager) { return this.content.verify(cryptoManager, this.getAdditionalMacData()); } public setMeta<T>(cryptoManager: CollectionItemCryptoManager, meta: ItemMetadata<T>): void { let rev = this.content; if (!this.isLocallyChanged()) { rev = this.content.clone(); } rev.setMeta(cryptoManager, this.getAdditionalMacData(), meta); this.content = rev; } public getMeta<T>(cryptoManager: CollectionItemCryptoManager): ItemMetadata<T> { this.verify(cryptoManager); return this.content.getMeta(cryptoManager, this.getAdditionalMacData()); } public async setContent(cryptoManager: CollectionItemCryptoManager, content: Uint8Array): Promise<void> { let rev = this.content; if (!this.isLocallyChanged()) { rev = this.content.clone(); } await rev.setContent(cryptoManager, this.getAdditionalMacData(), content); this.content = rev; } public async getContent(cryptoManager: CollectionItemCryptoManager): Promise<Uint8Array> { this.verify(cryptoManager); return this.content.getContent(cryptoManager); } public delete(cryptoManager: CollectionItemCryptoManager, preserveContent: boolean): void { let rev = this.content; if (!this.isLocallyChanged()) { rev = this.content.clone(); } rev.delete(cryptoManager, this.getAdditionalMacData(), preserveContent); this.content = rev; } public get isDeleted() { return this.content.deleted; } public get etag() { return this.content.uid; } public get isMissingContent() { return this.content.chunks.some(([_uid, content]) => !content); } public getCryptoManager(parentCryptoManager: MinimalCollectionCryptoManager) { const encryptionKey = (this.encryptionKey) ? parentCryptoManager.decrypt(this.encryptionKey) : parentCryptoManager.deriveSubkey(fromString(this.uid)); return new CollectionItemCryptoManager(encryptionKey, this.version); } public getHierarchicalCryptoManager(parentCryptoManager: MinimalCollectionCryptoManager) { const encryptionKey = (this.encryptionKey) ? parentCryptoManager.decrypt(this.encryptionKey) : parentCryptoManager.deriveSubkey(fromString(this.uid)); return new MinimalCollectionCryptoManager(encryptionKey, this.version); } protected getAdditionalMacData() { return fromString(this.uid); } }
the_stack
import { boot } from '../../../boot' import { Graph } from '../../../Class/Graph' import { APINotSupportedError } from '../../../exception/APINotImplementedError' import { DisplayMediaAPINotSupported } from '../../../exception/DisplayMediaAPINotSupported' import { MediaDevicesAPINotSupported } from '../../../exception/MediaDeviceAPINotSupported' import { U } from '../../../interface/U' import { NOOP } from '../../../NOOP' import { sleep } from '../../../sleep' import { API, System } from '../../../system' import { Storage_ } from '../../../system/platform/api/storage/Storage_' import { BundleSpec } from '../../../system/platform/method/process/BundleSpec' import { GraphSpecs } from '../../../types' import { Callback } from '../../../types/Callback' import { Dict } from '../../../types/Dict' import { IBluetoothDeviceOpt } from '../../../types/global/IBluetoothDevice' import { IBluetoothServer } from '../../../types/global/IBluetoothServer' import { IChannel, IChannelOpt } from '../../../types/global/IChannel' import { IDisplayMediaOpt } from '../../../types/global/IDisplayMedia' import { IDownloadDataOpt } from '../../../types/global/IDownloadData' import { IFileHandler } from '../../../types/global/IFileHandler' import { IGeoPosition } from '../../../types/global/IGeoPosition' import { IHTTPServer, IHTTPServerOpt } from '../../../types/global/IHTTPServer' import { IPod, IPodOpt } from '../../../types/global/IPod' import { ISpeechGrammarList, ISpeechGrammarListOpt, } from '../../../types/global/ISpeechGrammarList' import { ISpeechRecognition, ISpeechRecognitionOpt, } from '../../../types/global/ISpeechRecognition' import { ISpeechSynthesis, ISpeechSynthesisOpt, } from '../../../types/global/ISpeechSynthesis' import { ISpeechSynthesisUtterance, ISpeechSynthesisUtteranceOpt, } from '../../../types/global/ISpeechSynthesisUtterance' import { IUserMediaOpt } from '../../../types/global/IUserMedia' import { IWakeLock } from '../../../types/global/IWakeLock' import { Unlisten } from '../../../types/Unlisten' import { PeerSpec } from '../../host/service/peer' import { VMSpec } from '../../host/service/vm' import { WebSpec } from '../../host/service/web' import { createSharedServiceApi } from '../../host/store' import { MutationObserver_ } from '../../MutationObserver_' import { PositionObserver } from '../../PositionObserver' import { attachApp } from '../../render/attachApp' import { attachCanvas } from '../../render/attachCanvas' import { attachGesture } from '../../render/attachGesture' import { attachLongPress } from '../../render/attachLongPress' import { attachSprite } from '../../render/attachSprite' import { attachSVG } from '../../render/attachSVG' import { ResizeObserver_ } from '../../ResizeObserver_' import { SYSTEM_ROOT_ID } from '../../SYSTEM_ROOT_ID' import { Size } from '../../util/geometry' import { measureText } from '../../util/web/measureText' export default function webBoot(): System { return _webBoot(window) } export function _webBoot(window: Window): System { const { document, fetch, navigator } = window const root = document.getElementById(SYSTEM_ROOT_ID) // @ts-ignore const MutationObserver = window.MutationObserver || MutationObserver_ // @ts-ignore const ResizeObserver = window.ResizeObserver || ResizeObserver_ const cloudStorage: Storage = { length: 0, clear: function (): void { throw new Error('Function not implemented.') }, getItem: function (key: string): string { throw new Error('Function not implemented.') }, key: function (index: number): string { throw new Error('Function not implemented.') }, removeItem: function (key: string): void { throw new Error('Function not implemented.') }, setItem: function (key: string, value: string): void { throw new Error('Function not implemented.') }, } async function requestWakeLock(): Promise<IWakeLock> { throw new APINotSupportedError('Screen Wake Lock') } const HTTPServer = (opt: IHTTPServerOpt): IHTTPServer => { return { listen(port: number): Unlisten { return NOOP }, } } const LocalChannel = (opt: IChannelOpt): IChannel => { return { close(): void {}, postMessage(message: any): void {}, addListener(event: string, callback: Callback): Unlisten { return NOOP }, } } const LocalPod = (opt: IPodOpt): IPod => { return { refUnit(id: string): U { return // TODO }, refGraph(bundle: BundleSpec): [Dict<string>, Graph] { return // TODO }, getSpecs(): GraphSpecs { return {} // TODO }, } } const SpeechRecognition = ({ lang, grammars, continuous, interimResults, maxAlternatives, }: ISpeechRecognitionOpt): ISpeechRecognition => { const SpeechRecognition_ = // @ts-ignore window.SpeechRecognition || window.webkitSpeechRecognition if (!SpeechRecognition_) { throw new APINotSupportedError('Speech') } const recognition = new SpeechRecognition_() if (grammars) { recognition.grammars = grammars } recognition.lang = lang recognition.interimResults = interimResults recognition.maxAlternatives = maxAlternatives recognition.continuous = continuous const speechRecognition: ISpeechRecognition = { start: function (): void { recognition.start() }, stop: function (): void { recognition.start() }, addListener: function (event, listener): Unlisten { let _listener = listener if (event === 'error') { _listener = ({ error }) => { if (error === 'aborted' || error === 'no-speech') { return } listener(error) } } else if (event === 'result') { _listener = (event) => { const results = event.results listener(results) } } recognition.addEventListener(event, _listener) return () => { recognition.removeEventListener(event, _listener) } }, } return speechRecognition } const SpeechGrammarList = ( opt: ISpeechGrammarListOpt ): ISpeechGrammarList => { const SpeechGrammarList_ = // @ts-ignore window.SpeechGrammarList || window.webkitSpeechGrammarList if (!SpeechGrammarList_) { throw new APINotSupportedError('Speech') } const speechRecognitionList = new SpeechGrammarList_() return speechRecognitionList } const SpeechSynthesis = (opt: ISpeechSynthesisOpt): ISpeechSynthesis => { if (!window.speechSynthesis) { throw new APINotSupportedError('Speech Synthesis') } const { speechSynthesis } = window return { getVoices: () => { return speechSynthesis.getVoices() }, speak(utterance: ISpeechSynthesisUtterance): void { speechSynthesis.speak(utterance) }, } } const SpeechSynthesisUtterance = ({ text, voice, }: ISpeechSynthesisUtteranceOpt): ISpeechSynthesisUtterance => { // @ts-ignore if (!window.SpeechSynthesisUtterance) { throw new APINotSupportedError('Speech Synthesis') } // @ts-ignore const utterance = new window.SpeechSynthesisUtterance(text) utterance.voice = voice return utterance } // TODO const http = { server: { local: HTTPServer, cloud: HTTPServer, }, fetch: fetch, } // TODO const channel = { tab: LocalChannel, session: LocalChannel, local: LocalChannel, cloud: LocalChannel, } // TODO const pod = { session: LocalPod, local: LocalPod, cloud: LocalPod, } function showSaveFilePicker(opt: { suggestedName?: string startIn?: string id?: string excludeAcceptAllOption?: boolean types?: { description: string accept: Dict<string[]> }[] }): Promise<IFileHandler[]> { if (globalThis.showSaveFilePicker) { return globalThis.showSaveFilePicker(opt) } else { throw new APINotSupportedError('File System') } } function showOpenFilePicker(opt: { suggestedName?: string startIn?: string id?: string excludeAcceptAllOption?: boolean types?: { description: string accept: Dict<string[]> }[] multiple?: boolean }): Promise<IFileHandler[]> { if (globalThis.showOpenFilePicker) { return globalThis.showOpenFilePicker(opt) } else { throw new APINotSupportedError('File System') } } const downloadData = async ({ name, mimeType, charset, data, }: IDownloadDataOpt) => { const dataStr = `data:${mimeType};charset=${charset},${encodeURIComponent( data )}` const a = document.createElement('a') document.body.appendChild(a) a.download = name a.href = dataStr a.click() document.body.removeChild(a) } const file = { showSaveFilePicker, showOpenFilePicker, downloadData, } const screen = { requestWakeLock, } const bluetooth = { requestDevice: async (opt: IBluetoothDeviceOpt) => { // @ts-ignore if (navigator.bluetooth) { // show system UI on next tick to prevent possible // interference with triggering event propagation await sleep() try { // @ts-ignore const device = await navigator.bluetooth.requestDevice(opt) return { getServer: async () => { const { gatt } = device if (gatt) { try { return (await device.gatt.connect()) as IBluetoothServer } catch (err) { throw new Error(err.message) } } else { throw new Error( 'cannot find bluetooth device remote GATT server' ) } }, } } catch (err) { const { message } = err if (message === 'User cancelled the requestDevice() chooser.') { throw new Error('user cancelled chooser') } else if ( message === "Failed to execute 'requestDevice' on 'Bluetooth': Either 'filters' should be present or 'acceptAllDevices' should be true, but not both." ) { throw new Error( `either 'filters' should be present or 'acceptAllDevices' should be true, but not both.` ) } else { throw err } } } else { throw new APINotSupportedError('Bluetooth') } }, } const device = { vibrate: async (pattern: VibratePattern) => { if (navigator.vibrate) { navigator.vibrate(pattern) } else { throw new APINotSupportedError('Vibrate') } }, } const getCurrentPosition = async (): Promise<IGeoPosition> => { if ( !navigator || !navigator.geolocation || !navigator.geolocation.getCurrentPosition ) { throw new APINotSupportedError('Geolocation') } return new Promise((resolve, reject) => { navigator.geolocation.getCurrentPosition((position) => { resolve({ latitude: position.coords.latitude, longitude: position.coords.longitude, }) }) }) } const geolocation = { getCurrentPosition, } const speech = { SpeechRecognition, SpeechGrammarList, SpeechSynthesis, SpeechSynthesisUtterance, } const media = { getUserMedia: async (opt: IUserMediaOpt): Promise<MediaStream> => { if (!navigator || !navigator.mediaDevices) { throw new MediaDevicesAPINotSupported() } if (!navigator.mediaDevices.getUserMedia) { throw new MediaDevicesAPINotSupported() } try { return await navigator.mediaDevices.getUserMedia(opt) } catch (err) { const { message } = err if ( message === "Failed to execute 'getUserMedia' on 'MediaDevices': At least one of audio and video must be requested" ) { throw new Error('at least one of audio or video must be requested') } throw err } }, getDisplayMedia: async (opt: IDisplayMediaOpt): Promise<MediaStream> => { if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) { throw new DisplayMediaAPINotSupported() } try { return navigator.mediaDevices.getDisplayMedia(opt) } catch (err) { throw new Error(err.message) } }, enumerateDevices: async () => { if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) { throw new APINotSupportedError('Enumerate Media Devices') } return navigator.mediaDevices .enumerateDevices() .then((ds: MediaDeviceInfo[]) => { return ds.map((d) => ({ deviceId: d.deviceId, kind: d.kind, groupId: d.groupId, label: d.label, })) }) }, } const readText = async () => { if (navigator.clipboard && navigator.clipboard.readText) { const text = await navigator.clipboard.readText() return text } } const writeText = async (text: string) => { if (navigator.clipboard && navigator.clipboard.writeText) { await navigator.clipboard.writeText(text) } else { throw new APINotSupportedError('Clipboard') } } const clipboard = { readText, writeText, } const containsSelection = (element) => { const selection = window.getSelection() if (selection) { const { anchorNode } = selection return element.contains(anchorNode) } } const removeSelection = () => { const selection = window.getSelection() selection.removeAllRanges() } const selection = { containsSelection, removeSelection, } const storage = { local: () => new Storage_(localStorage), session: () => new Storage_(sessionStorage), cloud: () => new Storage_(cloudStorage), } const _document = { createElement<K extends keyof HTMLElementTagNameMap>( tagName: K ): HTMLElementTagNameMap[K] { return document.createElement(tagName) }, createElementNS<K extends keyof SVGElementTagNameMap>( namespaceURI: 'http://www.w3.org/2000/svg', qualifiedName: K ): SVGElementTagNameMap[K] { return document.createElementNS(namespaceURI, qualifiedName) }, createTextNode(text: string): Text { return document.createTextNode(text) }, MutationObserver: MutationObserver, ResizeObserver: ResizeObserver, PositionObserver: PositionObserver, } const querystring = { parse: (str: string): Dict<any> => { const urlSearchParams = new URLSearchParams(str) const obj = {} urlSearchParams.forEach((value, key) => { obj[key] = value }) return obj }, stringify: (obj: Dict<any>): string => { const urlSearchParams = new URLSearchParams(obj) const str = urlSearchParams.toString() return str }, } const _canvas: HTMLCanvasElement = document.createElement('canvas') const _ctx = _canvas.getContext('2d') _ctx.textAlign = 'center' const text = { measureText: (text: string, fontSize: number): Size => { return measureText(_ctx, text, fontSize) }, } const host = { fetch: (opt) => fetch(location.host, opt), send: () => { // TODO }, } const input: API['input'] = { keyboard: {}, gamepad: { getGamepads: () => { return navigator.getGamepads() }, addEventListener: ( type: 'gamepadconnected' | 'gamepadisconnected', listener: (ev: GamepadEvent) => any, options?: boolean | AddEventListenerOptions ) => { return window.addEventListener(type, listener, options) }, removeEventListener: ( type: 'gamepadconnected' | 'gamepadisconnected', listener: (ev: GamepadEvent) => any, options?: boolean | AddEventListenerOptions ): void => { return window.removeEventListener(type, listener, options) }, }, } const api: API = { storage, selection, file, device, screen, bluetooth, clipboard, geolocation, media, http, channel, input, pod, speech, document: _document, querystring, text, service: { graph: (opt: {}) => createSharedServiceApi<BundleSpec>(system, '', 'graph'), web: (opt: {}) => createSharedServiceApi<WebSpec>(system, '', 'web'), peer: (opt: {}) => createSharedServiceApi<PeerSpec>(system, '', 'web'), vm: (opt: {}) => createSharedServiceApi<VMSpec>(system, '', 'web'), }, worker: { start() { const { href } = location const url = `${href}/_worker.js` const worker = new Worker(url) return worker }, }, host, } const system = boot({ api }) system.root = root system.mounted = true attachSprite(system) attachApp(system) attachCanvas(system) attachGesture(system) attachSVG(system) attachLongPress(system) return system }
the_stack
import * as React from 'react'; import { Link } from 'react-router-dom'; import { Grid, Label, Popup, Table } from 'semantic-ui-react'; import { getStatusSemanticColor, ProcessEntry, ProcessKind, ProcessStatus } from '../../../api/process'; import { formatDuration } from '../../../utils'; import { GitHubLink, LocalTimestamp, ProcessLastErrorModal } from '../../molecules'; import { TriggeredByPopup } from '../../organisms'; interface Props { process?: ProcessEntry; } const kindToDescription = (k: ProcessKind): string => { switch (k) { case ProcessKind.DEFAULT: return 'Default'; case ProcessKind.FAILURE_HANDLER: return 'onFailure handler'; case ProcessKind.CANCEL_HANDLER: return 'onCancel handler'; case ProcessKind.TIMEOUT_HANDLER: return 'onTimeout handler'; default: return 'Unknown'; } }; class ProcessStatusTable extends React.PureComponent<Props> { static renderCommitId(process?: ProcessEntry) { if (!process || !process.commitId) { return ' - '; } const link = ( <GitHubLink url={process.repoUrl!} commitId={process.commitId} text={process.commitId} /> ); if (!process.commitMsg) { return link; } return <Popup trigger={<span>{link}</span>} content={process.commitMsg} />; } static renderProcessKind(process?: ProcessEntry) { if (!process) { return '-'; } return ( <> {kindToDescription(process.kind)} {process.kind === ProcessKind.FAILURE_HANDLER && process.status !== ProcessStatus.FAILED && ( <ProcessLastErrorModal processMeta={process.meta} title="Parent process' error" /> )} </> ); } static renderTags(process?: ProcessEntry) { if (!process) { return '-'; } const tags = process.tags; if (!tags || tags.length === 0) { return ' - '; } const items = tags.map((t) => <Link to={`/process?tags=${t}`}>{t}</Link>); const result = []; for (let i = 0; i < items.length; i++) { result.push(items[i]); if (i + 1 !== items.length) { result.push(', '); } } return result; } static renderTriggeredBy(process?: ProcessEntry) { if (!process) { return ' - '; } return <TriggeredByPopup entry={process} />; } static renderParentInstanceId(process?: ProcessEntry) { if (!process || !process.parentInstanceId) { return '-'; } const parentId = process.parentInstanceId; return <Link to={`/process/${parentId}`}>{parentId}</Link>; } static renderInitiator(process?: ProcessEntry) { if (!process) { return '-'; } return process.initiator; } static renderCreatedAt(process?: ProcessEntry) { if (!process) { return '-'; } return <LocalTimestamp value={process.createdAt} />; } static renderStartAt(process?: ProcessEntry) { if (!process || !process.startAt) { return '-'; } return <LocalTimestamp value={process.startAt} />; } static renderLastUpdatedAt(process?: ProcessEntry) { if (!process) { return '-'; } return <LocalTimestamp value={process.lastUpdatedAt} />; } static renderTimeout(process?: ProcessEntry) { if (!process || (!process.timeout && !process.suspendTimeout)) { return '-'; } return ( <> {process.timeout && ( <Label key={'running'}> <Popup trigger={<span>running: {formatDuration(process.timeout * 1000)}</span>} content={`${process.timeout}s`} /> </Label> )} {process.suspendTimeout && ( <Label key={'suspended'}> <Popup trigger={ <span> suspended: {formatDuration(process.suspendTimeout * 1000)} </span> } content={`${process.suspendTimeout}s`} /> </Label> )} </> ); } static renderProject(process?: ProcessEntry) { if (!process || !process.projectName) { return '-'; } return ( <Link to={`/org/${process.orgName}/project/${process.projectName}`}> {process.projectName} </Link> ); } static renderRepo(process?: ProcessEntry) { if (!process || !process.repoName) { return '-'; } return ( <Link to={`/org/${process.orgName}/project/${process.projectName}/repository/${process.repoName}`}> {process.repoName} </Link> ); } static renderRepoUrl(process?: ProcessEntry) { if (!process || !process.repoUrl) { return '-'; } return <GitHubLink url={process.repoUrl} text={process.repoUrl} />; } static renderRepoPath(process?: ProcessEntry) { if (!process || !process.commitId) { return '-'; } return ( <GitHubLink url={process.repoUrl!} commitId={process.commitId} path={process.repoPath || '/'} text={process.repoPath || '/'} /> ); } render() { const { process } = this.props; return ( <Grid columns={2} className={process ? '' : 'loading'}> <Grid.Column> <Table definition={true} color={process ? getStatusSemanticColor(process.status) : 'grey'} style={{ height: '100%' }}> <Table.Body> <Table.Row> <Table.Cell collapsing={true} singleLine={true}> Parent ID </Table.Cell> <Table.Cell> {ProcessStatusTable.renderParentInstanceId(process)} </Table.Cell> </Table.Row> <Table.Row> <Table.Cell collapsing={true} singleLine={true}> Initiator </Table.Cell> <Table.Cell> {ProcessStatusTable.renderInitiator(process)} </Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Type</Table.Cell> <Table.Cell> {ProcessStatusTable.renderProcessKind(process)} </Table.Cell> </Table.Row> <Table.Row> <Table.Cell collapsing={true} singleLine={true}> Created At </Table.Cell> <Table.Cell> {ProcessStatusTable.renderCreatedAt(process)} </Table.Cell> </Table.Row> <Table.Row> <Table.Cell collapsing={true} singleLine={true}> Start At </Table.Cell> <Table.Cell>{ProcessStatusTable.renderStartAt(process)}</Table.Cell> </Table.Row> <Table.Row> <Table.Cell collapsing={true} singleLine={true}> Last Update </Table.Cell> <Table.Cell> {ProcessStatusTable.renderLastUpdatedAt(process)} </Table.Cell> </Table.Row> <Table.Row style={{ height: '100%' }}> <Table.Cell collapsing={true} singleLine={true}> Timeout </Table.Cell> <Table.Cell>{ProcessStatusTable.renderTimeout(process)}</Table.Cell> </Table.Row> </Table.Body> </Table> </Grid.Column> <Grid.Column> <Table definition={true} color={process ? getStatusSemanticColor(process.status) : 'grey'} style={{ height: '100%' }}> <Table.Body style={{ wordBreak: 'break-all' }}> <Table.Row> <Table.Cell collapsing={true} singleLine={true}> Project </Table.Cell> <Table.Cell>{ProcessStatusTable.renderProject(process)}</Table.Cell> </Table.Row> <Table.Row> <Table.Cell collapsing={true} singleLine={true}> Concord Repository </Table.Cell> <Table.Cell>{ProcessStatusTable.renderRepo(process)}</Table.Cell> </Table.Row> <Table.Row> <Table.Cell collapsing={true} singleLine={true}> Repository URL </Table.Cell> <Table.Cell>{ProcessStatusTable.renderRepoUrl(process)}</Table.Cell> </Table.Row> <Table.Row> <Table.Cell collapsing={true} singleLine={true}> Repository Path </Table.Cell> <Table.Cell> {ProcessStatusTable.renderRepoPath(process)} </Table.Cell> </Table.Row> <Table.Row> <Table.Cell collapsing={true} singleLine={true}> Commit ID </Table.Cell> <Table.Cell> {ProcessStatusTable.renderCommitId(process)} </Table.Cell> </Table.Row> <Table.Row> <Table.Cell collapsing={true} singleLine={true}> Process Tags </Table.Cell> <Table.Cell>{ProcessStatusTable.renderTags(process)}</Table.Cell> </Table.Row> <Table.Row> <Table.Cell collapsing={true} singleLine={true}> Triggered By </Table.Cell> <Table.Cell> {ProcessStatusTable.renderTriggeredBy(process)} </Table.Cell> </Table.Row> </Table.Body> </Table> </Grid.Column> </Grid> ); } } export default ProcessStatusTable;
the_stack
import { createCompiler } from '../compiler'; import * as Fs from 'fs'; import * as Path from 'path'; import * as PropertyAnalyzer from './property-analyzer'; import * as ReactUtils from '../react-utils'; import * as SlotAnalyzer from './slot-analyzer'; import * as Types from '@meetalva/types'; import * as TypeScriptUtils from '../typescript-utils'; import * as ts from 'typescript'; import * as Util from 'util'; import * as uuid from 'uuid'; import { Compiler } from 'webpack'; import * as resolve from 'resolve'; import { last, merge } from 'lodash'; import * as Tsa from 'ts-simple-ast'; import { usesChildren } from '../react-utils/uses-children'; import { getTsaExport } from '../typescript-utils/get-tsa-export'; import { setExtname } from '../typescript-utils/set-extname'; import { getExportedNode } from '../typescript-utils/get-exported-node'; import * as IdHasher from '../id-hasher'; const precinct = require('precinct'); const readPkg = require('read-pkg'); export interface PatternCandidate { artifactPath: string; declarationPath: string; description: string; displayName: string; id: string; sourcePath: string; } export interface AnalyzeOptions { analyzeBuiltins: boolean; } interface AnalyzeContext { candidate: PatternCandidate; options: AnalyzeOptions; program: ts.Program; project: Tsa.Project; pkg: unknown; pkgPath: string; knownProperties: Types.PropertyAnalysis[]; knownPatterns: Types.InternalPatternAnalysis[]; } type PatternAnalyzer = ( candidate: PatternCandidate, previous: Types.InternalPatternAnalysis[], predicate: PatternAnalyzerPredicate ) => Types.InternalPatternAnalysis[]; type PatternAnalyzerPredicate = ( ex: TypeScriptUtils.TypescriptExport, ctx: AnalyzeContext ) => Types.InternalPatternAnalysis | undefined; export const analyzeDefaults = { analyzeBuiltins: false, ids: { patterns: [], properties: [], enumOptions: [], slots: [] } }; export async function analyze( pkgPath: string, rawOptions: Partial<AnalyzeOptions> = analyzeDefaults ): Promise<Types.LibraryAnalysisResult> { try { const id = uuid.v4(); // readPkg is typed faultily const pkg = await readPkg({ cwd: Path.dirname(pkgPath) }); const cwd = Path.dirname(pkgPath); const options = merge({}, analyzeDefaults, rawOptions) as AnalyzeOptions; const patterns = await analyzePatterns({ pkgPath, options, pkg, cwd }); const getBundle = async () => { if (patterns.length === 0) { return ''; } const compiler = await createPatternCompiler(patterns, { cwd, id }); const stats = await Util.promisify(compiler.run).bind(compiler)(); if (stats.hasErrors()) { const message = stats.toString({ chunks: false, colors: false }); console.error(message); throw new Error(); } if (stats.hasWarnings()) { console.warn( stats.toString({ chunks: false, colors: false }) ); } return (compiler.outputFileSystem as any).readFileSync(`/${id}.js`).toString(); }; return { type: Types.LibraryAnalysisResultType.Success, result: { bundle: await getBundle(), id, packageFile: pkg, path: pkgPath, patterns: patterns.map(p => ({ path: p.path, pattern: p.pattern, properties: p.properties.map(prop => prop.property) })) } }; } catch (error) { return { type: Types.LibraryAnalysisResultType.Error, error }; } } async function analyzePatterns(context: { cwd: string; pkgPath: string; options: AnalyzeOptions; pkg: unknown; }): Promise<Types.InternalPatternAnalysis[]> { const patternCandidates = await findPatternCandidates({ cwd: context.cwd, pkg: context.pkg }); const declarationPaths = patternCandidates.map(p => p.declarationPath); const optionsPath = ts.findConfigFile(context.cwd, Fs.existsSync); const options = optionsPath ? ts.readConfigFile(optionsPath, path => String(Fs.readFileSync(path))) : { config: {} }; const compilerHost = ts.createCompilerHost(options.config); compilerHost.getCurrentDirectory = () => context.cwd; const program = ts.createProgram(declarationPaths, options.config, compilerHost); const project = new Tsa.Project({ tsConfigFilePath: optionsPath }); const analyzePattern = getPatternAnalyzer( program, project, context.pkg, context.pkgPath, context.options ); return patternCandidates.reduce<Types.InternalPatternAnalysis[]>( (acc, candidate) => [...acc, ...analyzePattern(candidate, acc, analyzePatternExport)], [] ); } async function createPatternCompiler( patterns: Types.InternalPatternAnalysis[], context: { cwd: string; id: string } ): Promise<Compiler> { const compilerPatterns = patterns.map(({ path: patternPath, pattern }) => ({ id: pattern.id, path: patternPath })); return createCompiler(compilerPatterns, { cwd: context.cwd, infrastructure: false, id: context.id }); } export function getPatternAnalyzer( program: ts.Program, project: Tsa.Project, pkg: unknown, pkgPath: string, options: AnalyzeOptions ): PatternAnalyzer { return ( candidate: PatternCandidate, previous: Types.InternalPatternAnalysis[], predicate: PatternAnalyzerPredicate ): Types.InternalPatternAnalysis[] => { const sourceFile = program.getSourceFile(candidate.declarationPath); const knownProperties = previous.reduce<Types.PropertyAnalysis[]>( (a, p) => [...a, ...p.properties], [] ); if (!sourceFile) { return []; } return TypeScriptUtils.getExports(sourceFile, program) .map(ex => predicate(ex, { program, project, pkg, pkgPath, candidate, options, knownProperties, knownPatterns: previous }) ) .filter((p): p is Types.InternalPatternAnalysis => typeof p !== 'undefined'); }; } export function analyzePatternExport( ex: TypeScriptUtils.TypescriptExport, ctx: AnalyzeContext ): Types.InternalPatternAnalysis | undefined { const reactType = ReactUtils.findReactComponentType(ex.type, { program: ctx.program }); if (!reactType) { return; } const reactTypeArguments = reactType.getTypeArguments(); if (reactTypeArguments.length === 0) { return; } const [propTypes] = reactTypeArguments; if (!propTypes) { return; } const symbol = propTypes.type.symbol; if (!symbol) { return; } if (ctx.knownPatterns.some(p => p.symbol === symbol)) { return; } const exportName = ex.exportName || 'default'; const contextId = `${ctx.candidate.id}:${exportName}`; const id = IdHasher.getGlobalPatternId(contextId); if (ex.ignore) { return; } const properties = PropertyAnalyzer.analyze(propTypes.type, { program: ctx.program, getPropertyId: (propertyContextId: string) => IdHasher.getGlobalPropertyId(id, propertyContextId), getEnumOptionId: (enumId, optionContextId) => IdHasher.getGlobalEnumOptionId(enumId, optionContextId) }); const slots = SlotAnalyzer.analyzeSlots(propTypes.type, { program: ctx.program, project: ctx.project, getSlotId: (slotContextId: string) => IdHasher.getGlobalSlotId(id, slotContextId) }); // Try to find out if children are used if they are not typed explicitly if (!slots.some(slot => slot.type === 'children')) { const exp = getTsaExport(ex, { project: ctx.project }); const expNode = getExportedNode(exp); if (expNode && usesChildren(expNode, { project: ctx.project })) { slots.push({ model: Types.ModelName.PatternSlot, contextId: 'children', description: 'Element that render inside this element', defaultValue: undefined, example: '', hidden: false, id: IdHasher.getGlobalSlotId(id, 'children'), label: 'children', propertyName: 'children', quantity: 'multiple', required: false, type: 'children' }); } } return { symbol, path: ctx.candidate.artifactPath, libraryName: (ctx.pkg as { name: string }).name, pattern: { model: Types.ModelName.Pattern, contextId, description: ex.description ? ex.description : ctx.candidate.description, exportName, icon: ex.icon, group: ex.group, id, name: ex.displayName || (exportName !== 'default' ? exportName : ctx.candidate.displayName), propertyIds: properties.map(p => { const known = ctx.knownProperties.find(k => k.symbol === p.symbol); return known ? known.property.id : p.property.id; }), slots, type: ctx.options.analyzeBuiltins ? ex.patternType : 'pattern' }, properties: properties.filter(p => { const unique = !ctx.knownProperties.some(k => k.symbol === p.symbol); return unique; }) }; } async function findPatternCandidates({ cwd, pkg }: { cwd: string; // tslint:disable-next-line:no-any pkg: any; }): Promise<PatternCandidate[]> { const entry = Path.join(cwd, getTypingsEntry(pkg)); const declarationsList = getImportsFromPath(entry, { extensions: ['.d.ts'], deep: true, init: new Set() }); return [...declarationsList].map(declarationPath => { const artifactPath = setExtname(declarationPath, '.js'); const significantPath = getSignificantPath(Path.relative(cwd, declarationPath)); const dName = last(significantPath); return { artifactPath, declarationPath, description: '', displayName: dName ? Path.basename(dName, Path.extname(dName)) : 'Unknown Pattern', id: significantPath.join('/'), sourcePath: Path.dirname(declarationPath) }; }); } function getImportsFromPath( path: string, config: { extensions: string[]; init: Set<string>; deep: boolean } = { init: new Set(), deep: true, extensions: [] } ): Set<string> { const basedir = Path.dirname(path); const dependencyList: string[] = precinct .paperwork(path) .filter((p: string) => p.startsWith('.')) .map((p: string) => resolve.sync(p, { basedir, extensions: config.extensions }) ); if (!config.deep) { return new Set(dependencyList); } return dependencyList.reduce((acc: Set<string>, dependency: string) => { if (config.init.has(dependency)) { return acc; } acc.add(dependency); getImportsFromPath(dependency, { ...config, init: acc }); return acc; }, config.init); } export function getSignificantPath(input: string): string[] { const stripped = Path.basename(input, Path.extname(input)); if (stripped === 'index' || stripped === 'index.d') { return Path.dirname(input) .split(Path.sep) .filter(p => p !== '..'); } return input.split(Path.sep).filter(p => p !== '..'); } // tslint:disable-next-line:no-any function getTypingsEntry(pkg: { [key: string]: unknown }): string { if (typeof pkg['alva:typings'] === 'string') { return pkg['alva:typings'] as string; } if (typeof pkg.typings === 'string') { return pkg.typings; } if (typeof pkg['alva:main'] === 'string') { return setExtname(pkg['alva:main'] as string, '.d.ts'); } if (typeof pkg.main === 'string') { return setExtname(pkg.main, '.d.ts'); } return './index.d.ts'; }
the_stack
class PWA { // Copy text... async copyText(text: string) { try { if (navigator.clipboard) { await navigator.clipboard.writeText(text); // Copied... return { ok: true, message: "Copied" }; } else { return { ok: false, message: "Copy Text API not supported", }; } } catch (error) { // Error... throw error; } } // Copy image async copyImage(imgURL: string) { try { if (navigator.clipboard) { const data = await fetch(imgURL); const blob = await data.blob(); await navigator.clipboard.write([ new ClipboardItem({ [blob.type]: blob, }), ]); return { ok: true, message: "Image copied", }; } else { return { ok: false, message: "Copy Image API not supported" }; } } catch (error) { // Error... throw error; } } // Web Share... async Share(data: ShareData) { try { if (data.files) { if (navigator.canShare && navigator.canShare(data)) { await navigator.share(data); return { ok: true, message: "Shared" }; } else { return { ok: false, message: "Share Files API not supported" }; } } else { // Check support... if (navigator.share) { await navigator.share(data); // Shared... return { ok: true, message: "Shared" }; } else { return { ok: false, message: "Web Share API not supported" }; } } } catch (error) { // Error.. throw error; } } // Contacts Picker... async Contacts( props: string[], options?: { multiple: boolean; }, ) { try { if ("contacts" in navigator && "ContactsManager" in window) { const contacts = await navigator.contacts.select(props, options); // Return contacts... return { ok: true, message: "Selected", contacts }; } else { return { ok: false, message: "Contacts Picker API not supported" }; } } catch (error) { // Error... throw error; } } // Connectivity... async Connectivity(online: () => "online", offline: () => "offline") { // Once the DOM is loaded, check for connectivity... try { if (navigator.onLine) { online(); return { ok: true, message: "Online" }; } else { offline(); return { ok: true, message: "Offline" }; } } catch (error) { // Error... throw error; } } // Set badge... async setBadge(unreadCount: number) { try { if (navigator.setAppBadge) { await navigator.setAppBadge(unreadCount); return { ok: true, message: "Set" }; } else { return { ok: false, message: "Badging API not supported", }; } } catch (error) { // Error... throw error; } } // Clear badge... async clearBadge() { try { if (navigator.clearAppBadge) { await navigator.clearAppBadge(); return { ok: true, message: "Cleared" }; } else { return { ok: false, message: "Badging API not supported" }; } } catch (error) { // Error... throw error; } } // Content Indexing... async contentIndexing() { try { const registration = (await navigator.serviceWorker.ready) as any; // Remember to feature-detect before using the API: if ("index" in registration) { return { ok: true, getAll: async () => { try { return (await registration.index.getAll()) as { [key: string]: string | number | boolean | object | any; }[]; } catch (error) { throw error; } }, addItem: async (item: { id: string; title: string; // Optional; valid categories are currently: // 'homepage', 'article', 'video', 'audio', or '' (default). category?: "homepage" | "article" | "video" | "audio" | ""; description: string; icons: { src: string; sizes: string; type: string; }[]; url: string; }) => { try { // Add to content index... await registration.index.add({ ...item, category: item.category || "", }); return { ok: true, message: "Added" }; } catch (error) { throw error; } }, removeItem: async (id: string) => { try { await registration.index.delete(id); return { ok: true, message: "Removed" }; } catch (error) { throw error; } }, message: "Context Indexing ready", }; } else { return { ok: false, message: "Content Indexing API not supported", }; } } catch (error) { throw error; } } // Fullscreen... async Fullscreen() { try { if (document.fullscreenEnabled) { await document.documentElement.requestFullscreen(); return { ok: true, message: "Fullscreen" }; } else { // Error... return { ok: false, message: "Fullscreen disabled" }; } } catch (error) { // Error... throw error; } } // Notification... async Notification(data: { title: string; options: object }) { const { title, options } = data; try { if ("Notification" in window) { const permission = await Notification.requestPermission(); if (permission === "granted") { await navigator.serviceWorker.ready.then((registration) => { registration.showNotification(title, options); // Sent... return { ok: true, message: "Sent" }; }); } else { // Denied... return { ok: true, message: "Denied" }; } } else { // Error... return { ok: false, message: "Notification API not supported" }; } } catch (error) { // Error... throw error; } } // Install... Install(button: HTMLElement) { try { if (navigator.serviceWorker) { window.addEventListener("beforeinstallprompt", (event: any) => { // Stash the event so it can be triggered later... window.deferredPrompt = event; }); // Install... button.addEventListener("click", () => { const promptEvent = window.deferredPrompt; if (!promptEvent) { return null; } // Show the install prompt... promptEvent.prompt(); // Log the result promptEvent.userChoice.then((result: any) => { // Reset the deferred prompt variable... window.deferredPrompt = null; // Hide the install button... }); }); // Installed.... window.addEventListener("appinstalled", (event: any) => { // Installed... }); } else { // Error... return { ok: false, message: "Service Worker not supported" }; } } catch (error) { throw error; } } // Idle detection... async idleDetection( action = "start", callback = () => { // Idle... }, threshold = 60000, ) { try { // Idle Detection... if ("IdleDetector" in window) { // Make sure "idle-detection" permission is granted... const state = await IdleDetector.requestPermission(); if (state === "granted") { // Permission granted... const controller = new AbortController(); const signal = controller.signal; const idleDetector = new IdleDetector(); idleDetector.addEventListener("change", () => { const userState = idleDetector.userState; // const screenState = idleDetector.screenState; // Handle states... if (userState === "idle") { callback(); } else { // Do nothing... } }); // Handle detector... if (action === "start") { // Start... await idleDetector.start({ threshold: threshold > 60000 ? threshold : 60000, signal, }); return { ok: true, message: "Started" }; } else { // Abort... controller.abort(); return { ok: true, message: "Aborted" }; } } else { // Need to request permission first... return { ok: false, message: "Need to request permission first" }; } } else { // Not supported... return { ok: false, message: "Idle Detection API not supported" }; } } catch (error) { throw error; } } // Wakelock... async wakeLock() { try { if ("wakeLock" in navigator) { const wakeLock = await navigator.wakeLock.request("screen"); if (wakeLock) { return { ok: true, message: "WakeLock Active" }; } else { return { ok: false, message: "WakeLock Failed" }; } } else { return { ok: false, message: "WakeLock API not supported" }; } } catch (error) { throw error; } } // Visibility... async Visibility(isVisible: () => void, notAvailable: () => void) { try { if (document.visibilityState) { const state = document.visibilityState; if (state === "visible") { // Call back function... isVisible(); return { ok: true, message: "Visible" }; } } else { // Alternative... notAvailable(); return { ok: false, message: "Visibility API not supported", }; } } catch (error) { // Error... throw error; } } // Pick text file.. async pickTextFile() { try { let fileHandle; [fileHandle] = await window.showOpenFilePicker(); const file = await fileHandle.getFile(); if (file) { const typeList = file.type.split("/"); if (typeList.includes("text")) { const contents = await file.text(); return { ok: true, message: "File picked", contents }; } else { return { ok: false, message: "File Picker API not supported" }; } } else { // Please pick text type file return { ok: false, message: "Please pick text type file" }; } } catch (error) { // Error... throw error; } } // Pick any file... async pickFile() { try { let fileHandle: any; [fileHandle] = await window.showOpenFilePicker(); const file: any = await fileHandle.getFile(); if (file) { return { file, ok: true, message: "File picked", }; } else { return { file: null, ok: false, message: "File Picker API not supported", }; } } catch (error) { throw error; } } // Payment... async Payment( paydata: { paymentMethods: PaymentMethodData[]; paymentDetails: PaymentDetailsInit; options: any; }, validatePayment: (arg0: PaymentResponse) => void, ) { // Initiate user interface... try { const paymentRequest = new PaymentRequest(paydata.paymentMethods, paydata.paymentDetails); if (paymentRequest) { const canPay = await paymentRequest.canMakePayment(); if (canPay) { const paymentResponse = await paymentRequest.show(); // Validate with backend... validatePayment(paymentResponse); return { ok: true, message: "Payment" }; } else { return { ok: false, message: "Payment method(s) not supported" }; } } else { return { ok: false, message: "Payment Request API not supported" }; } } catch (error) { throw error; } } } // Export pwa class... export default PWA;
the_stack
import { StateService } from '@uirouter/core'; import _ = require('lodash'); import { ApiService } from '../../../../services/api.service'; import NotificationService from '../../../../services/notification.service'; const ApiSubscriptionComponent: ng.IComponentOptions = { bindings: { api: '<', subscription: '<', }, template: require('./subscription.html'), controller: class { private subscription: any; private keys: any[]; private api: any; private plans: any[]; private transferablePlans: any[]; private backStateParams: any; private canUseCustomApiKey: boolean; constructor( private $rootScope: ng.IRootScopeService, private $mdDialog: angular.material.IDialogService, private NotificationService: NotificationService, private ApiService: ApiService, private $state: StateService, private Constants: any, ) { 'ngInject'; this.backStateParams = { application: $state.params.application, plan: $state.params.plan, status: $state.params.status, page: $state.params.page, size: $state.params.size, api_key: $state.params.api_key, }; } $onInit() { this.canUseCustomApiKey = this.Constants.env.settings.plan.security.customApiKey.enabled; this.listApiKeys(); this.getApiPlans(); } listApiKeys() { if (this.subscription.plan.security === 'API_KEY') { // Retrieve api_keys for current current subscription this.ApiService.listApiKeys(this.api.id, this.subscription.id).then((response) => { this.keys = response.data; }); } } close() { let msg = '<code>' + this.subscription.application.name + '</code> will not be able to consume <code>' + this.api.name + '</code> anymore.'; if (this.subscription.plan.security === 'API_KEY') { msg += '<br/>All Api-keys associated to this subscription will be closed and could not be used.'; } this.$mdDialog .show({ controller: 'DialogConfirmController', controllerAs: 'ctrl', template: require('../../../../components/dialog/confirmWarning.dialog.html'), clickOutsideToClose: true, locals: { title: 'Are you sure you want to close this subscription to ' + this.subscription.plan.name + '?', msg: msg, confirmButton: 'Close the subscription', }, }) .then((response) => { if (response) { this.ApiService.closeSubscription(this.api.id, this.subscription.id).then((response) => { this.NotificationService.show('The subscription has been closed'); this.subscription = response.data; this.listApiKeys(); }); } }); } pause() { let msg = 'The application will not be able to consume this API anymore.'; if (this.subscription.plan.security === 'API_KEY') { msg += '<br/>All Api-keys associated to this subscription will be paused and could not be used.'; } this.$mdDialog .show({ controller: 'DialogConfirmController', controllerAs: 'ctrl', template: require('../../../../components/dialog/confirmWarning.dialog.html'), clickOutsideToClose: true, locals: { title: 'Are you sure you want to pause this subscription?', msg: msg, confirmButton: 'Pause', }, }) .then((response) => { if (response) { this.ApiService.pauseSubscription(this.api.id, this.subscription.id).then((response) => { this.NotificationService.show('The subscription has been paused'); this.subscription = response.data; this.listApiKeys(); }); } }); } resume() { const msg = 'The application will again be able to consume your API.'; this.$mdDialog .show({ controller: 'DialogConfirmController', controllerAs: 'ctrl', template: require('../../../../components/dialog/confirmWarning.dialog.html'), clickOutsideToClose: true, locals: { title: 'Are you sure you want to resume this subscription?', msg: msg, confirmButton: 'Resume', }, }) .then((response) => { if (response) { this.ApiService.resumeSubscription(this.api.id, this.subscription.id).then((response) => { this.NotificationService.show('The subscription has been resumed'); this.subscription = response.data; this.listApiKeys(); }); } }); } reject() { this.$mdDialog .show({ controller: 'DialogSubscriptionRejectController', controllerAs: 'dialogSubscriptionRejectController', template: require('./dialog/subscription.reject.dialog.html'), clickOutsideToClose: true, }) .then((reason) => { this.process({ accepted: false, reason: reason }); }); } accept() { this.$mdDialog .show({ controller: 'DialogSubscriptionAcceptController', controllerAs: 'dialogSubscriptionAcceptController', template: require('./dialog/subscription.accept.dialog.html'), clickOutsideToClose: true, locals: { apiId: this.api.id, applicationId: this.subscription.application.id, canUseCustomApiKey: this.canUseCustomApiKey, }, }) .then((subscription) => { subscription.accepted = true; this.process(subscription); }); } process(processSubscription) { this.ApiService.processSubscription(this.api.id, this.subscription.id, processSubscription).then((response) => { this.NotificationService.show('The subscription has been ' + (processSubscription.accepted ? 'accepted' : 'rejected')); this.subscription = response.data; this.$rootScope.$broadcast('graviteeUserTaskRefresh'); if (processSubscription.accepted) { this.listApiKeys(); } }); } transferSubscription(transferSubscription) { this.ApiService.transferSubscription(this.api.id, this.subscription.id, transferSubscription).then((response) => { this.NotificationService.show('The subscription has been successfully transferred'); this.subscription = response.data; this.getApiPlans(); }); } renewApiKey() { this.$mdDialog .show({ controller: 'DialogSubscriptionRenewController', controllerAs: 'ctrl', template: require('./dialog/subscription.renew.dialog.html'), clickOutsideToClose: true, locals: { title: 'Are you sure you want to renew your API Key?', msg: 'Your previous API Key will be no longer valid in 2 hours!', customMessage: this.canUseCustomApiKey ? 'You can provide a custom API key here' : null, confirmButton: 'Renew', apiId: this.api.id, applicationId: this.subscription.application.id, }, }) .then((response) => { if (response && response.confirmed) { this.ApiService.renewApiKey(this.api.id, this.subscription.id, response.customValue).then(() => { this.NotificationService.show('A new API Key has been generated'); this.listApiKeys(); }); } }); } revokeApiKey(apiKey) { this.$mdDialog .show({ controller: 'DialogConfirmController', controllerAs: 'ctrl', template: require('../../../../components/dialog/confirmWarning.dialog.html'), clickOutsideToClose: true, locals: { title: "Are you sure you want to revoke API Key '" + apiKey.key + "'?", confirmButton: 'Revoke', }, }) .then((response) => { if (response) { this.ApiService.revokeApiKey(this.api.id, this.subscription.id, apiKey.id).then(() => { this.NotificationService.show('API Key ' + apiKey.key + ' has been revoked!'); this.listApiKeys(); }); } }); } expireApiKey(apiKey) { this.$mdDialog .show({ controller: 'DialogApiKeyExpirationController', controllerAs: 'dialogApiKeyExpirationController', template: require('./dialog/apikey.expiration.dialog.html'), clickOutsideToClose: true, locals: { maxEndDate: this.subscription.ending_at, }, }) .then((expirationDate) => { apiKey.expire_at = expirationDate; this.ApiService.updateApiKey(this.api.id, this.subscription.id, apiKey).then(() => { this.NotificationService.show('An expiration date has been defined for API Key.'); this.listApiKeys(); }); }); } reactivateApiKey(apiKey) { this.$mdDialog .show({ controller: 'DialogConfirmController', controllerAs: 'ctrl', template: require('../../../../components/dialog/confirm.dialog.html'), clickOutsideToClose: true, locals: { title: "Are you sure you want to reactivate API Key '" + apiKey.key + "'?", confirmButton: 'Reactivate', }, }) .then((response) => { if (response) { this.ApiService.reactivateApiKey(this.api.id, this.subscription.id, apiKey.id).then(() => { this.NotificationService.show('API Key ' + apiKey.key + ' has been reactivated!'); this.listApiKeys(); }); } }); } onCopyApiKeySuccess(e) { this.NotificationService.show('API Key has been copied to clipboard'); e.clearSelection(); } transfer() { this.$mdDialog .show({ controller: 'DialogSubscriptionTransferController', controllerAs: '$ctrl', template: require('./dialog/subscription.transfer.dialog.html'), clickOutsideToClose: true, locals: { plans: this.transferablePlans, }, }) .then((plan) => { this.subscription.plan = plan; this.transferSubscription(this.subscription); }); } changeEndDate() { this.$mdDialog .show({ controller: 'DialogSubscriptionChangeEndDateController', controllerAs: '$ctrl', template: require('./dialog/subscription.change.end.date.dialog.html'), clickOutsideToClose: true, locals: { subscription: this.subscription, }, }) .then((endDate) => { this.subscription.ending_at = endDate; this.ApiService.updateSubscription(this.api.id, this.subscription).then(() => { this.NotificationService.show('The end date has been modified.'); this.listApiKeys(); }); }); } isValid(key) { return !key.revoked && !key.expired; } private getApiPlans() { this.ApiService.getApiPlans(this.api.id, 'PUBLISHED', this.subscription.plan.security).then((response) => { this.plans = response.data; this.transferablePlans = _.filter(response.data, (plan) => plan.id !== this.subscription.plan.id); }); } }, }; export default ApiSubscriptionComponent;
the_stack
import 'chrome://resources/cr_elements/cr_radio_button/cr_radio_button.m.js'; import 'chrome://resources/cr_elements/cr_radio_group/cr_radio_group.m.js'; import 'chrome://resources/cr_elements/md_select_css.m.js'; import '../controls/settings_toggle_button.js'; import '../prefs/prefs.js'; import '../settings_shared_css.js'; import './secure_dns_input.js'; import {assertNotReached} from 'chrome://resources/js/assert.m.js'; import {WebUIListenerMixin} from 'chrome://resources/js/web_ui_listener_mixin.js'; import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {loadTimeData} from '../i18n_setup.js'; import {PrefsMixin} from '../prefs/prefs_mixin.js'; import {PrivacyPageBrowserProxy, PrivacyPageBrowserProxyImpl, ResolverOption, SecureDnsMode, SecureDnsSetting, SecureDnsUiManagementMode} from './privacy_page_browser_proxy.js'; interface SettingsSecureDnsElement { $: { privacyPolicy: HTMLElement, secureDnsInput: HTMLElement, secureResolverSelect: HTMLSelectElement, }; } const SettingsSecureDnsElementBase = WebUIListenerMixin(PrefsMixin(PolymerElement)); class SettingsSecureDnsElement extends SettingsSecureDnsElementBase { static get is() { return 'settings-secure-dns'; } static get template() { return html`{__html_template__}`; } static get properties() { return { /** * Preferences state. */ prefs: { type: Object, notify: true, }, /** * Mirroring the secure DNS mode enum so that it can be used from HTML * bindings. */ secureDnsModeEnum_: { type: Object, value: SecureDnsMode, }, /** * The setting sublabel. */ secureDnsDescription_: String, /** * Represents whether the main toggle for the secure DNS setting is * switched on or off. */ secureDnsToggle_: { type: Object, value() { return { type: chrome.settingsPrivate.PrefType.BOOLEAN, value: false, }; }, }, /** * Whether the radio buttons should be shown. */ showRadioGroup_: Boolean, /** * Represents the selected radio button. Should always have a value of * 'automatic' or 'secure'. */ secureDnsRadio_: { type: String, value: SecureDnsMode.AUTOMATIC, }, /** * List of secure DNS resolvers to display in dropdown menu. */ resolverOptions_: Array, /** * Track the selected dropdown option so that it can be logged when a * user- initiated UI dropdown selection change event occurs. */ lastResolverOption_: String, /** * String displaying the privacy policy of the resolver selected in the * dropdown menu. */ privacyPolicyString_: String, /** * String to display in the custom text field. */ secureDnsInputValue_: String, }; } private secureDnsDescription_: string; private secureDnsToggle_: chrome.settingsPrivate.PrefObject; private showRadioGroup_: boolean; private secureDnsRadio_: SecureDnsMode; private resolverOptions_: Array<ResolverOption>; private lastResolverOption_: string; private privacyPolicyString_: string; private secureDnsInputValue_: string; private browserProxy_: PrivacyPageBrowserProxy = PrivacyPageBrowserProxyImpl.getInstance(); connectedCallback() { super.connectedCallback(); // Fetch the options for the dropdown menu before configuring the setting // to match the underlying host resolver configuration. this.browserProxy_.getSecureDnsResolverList().then(resolvers => { this.resolverOptions_ = resolvers; this.lastResolverOption_ = this.resolverOptions_[0].value; this.browserProxy_.getSecureDnsSetting().then( (setting: SecureDnsSetting) => this.onSecureDnsPrefsChanged_(setting)); // Listen to changes in the host resolver configuration and update the // UI representation to match. (Changes to the host resolver configuration // may be generated in ways other than direct UI manipulation). this.addWebUIListener( 'secure-dns-setting-changed', (setting: SecureDnsSetting) => this.onSecureDnsPrefsChanged_(setting)); }); } /** * Update the UI representation to match the underlying host resolver * configuration. */ private onSecureDnsPrefsChanged_(setting: SecureDnsSetting) { switch (setting.mode) { case SecureDnsMode.SECURE: this.set('secureDnsToggle_.value', true); this.secureDnsRadio_ = SecureDnsMode.SECURE; // Only update the selected dropdown item if the user is in secure // mode. Otherwise, we may be losing a selection that hasn't been // pushed yet to prefs. this.updateTemplatesRepresentation_(setting.templates); this.updatePrivacyPolicyLine_(); break; case SecureDnsMode.AUTOMATIC: this.set('secureDnsToggle_.value', true); this.secureDnsRadio_ = SecureDnsMode.AUTOMATIC; break; case SecureDnsMode.OFF: this.set('secureDnsToggle_.value', false); break; default: assertNotReached('Received unknown secure DNS mode'); } this.updateManagementView_(setting.managementMode); } /** * Updates the underlying secure DNS mode pref based on the new toggle * selection (and the underlying radio button if the toggle has just been * enabled). */ onToggleChanged_() { this.showRadioGroup_ = this.secureDnsToggle_.value; if (this.secureDnsRadio_ === SecureDnsMode.SECURE && !this.$.secureResolverSelect.value) { this.$.secureDnsInput.focus(); } this.updateDnsPrefs_( this.secureDnsToggle_.value ? this.secureDnsRadio_ : SecureDnsMode.OFF); } /** * Updates the underlying secure DNS prefs based on the newly selected radio * button. This should only be called from the HTML. Focuses the custom text * field if the custom option has been selected. */ private onRadioSelectionChanged_(event: CustomEvent<{value: SecureDnsMode}>) { if (event.detail.value === SecureDnsMode.SECURE && !this.$.secureResolverSelect.value) { this.$.secureDnsInput.focus(); } this.updateDnsPrefs_(event.detail.value); } /** * Helper method for updating the underlying secure DNS prefs based on the * provided mode and templates (if the latter is specified). The templates * param should only be specified when the underlying prefs are being updated * after a custom entry has been validated. */ private updateDnsPrefs_(mode: SecureDnsMode, templates: string = '') { switch (mode) { case SecureDnsMode.SECURE: // If going to secure mode, set the templates pref first to prevent the // stub resolver config from being momentarily invalid. If the user has // selected the custom dropdown option, only update the underlying // prefs if the templates param was specified. If the templates param // was not specified, the custom entry may be invalid or may not // have passed validation yet, and we should not update either the // underlying mode or templates prefs. if (!this.$.secureResolverSelect.value) { if (!templates) { return; } this.setPrefValue('dns_over_https.templates', templates); } else { this.setPrefValue( 'dns_over_https.templates', this.$.secureResolverSelect.value); } this.setPrefValue('dns_over_https.mode', mode); break; case SecureDnsMode.AUTOMATIC: case SecureDnsMode.OFF: // If going to automatic or off mode, set the mode pref first to avoid // clearing the dropdown selection when the templates pref is cleared. this.setPrefValue('dns_over_https.mode', mode); this.setPrefValue('dns_over_https.templates', ''); break; default: assertNotReached('Received unknown secure DNS mode'); } } /** * Prevent interactions with the dropdown menu or custom text field from * causing the corresponding radio button to be selected. */ private stopEventPropagation_(event: Event) { event.stopPropagation(); } /** * Updates the underlying secure DNS templates pref based on the selected * resolver and displays the corresponding privacy policy. Focuses the custom * text field if the custom option has been selected. */ onDropdownSelectionChanged_() { // If we're already in secure mode, update the prefs. if (this.secureDnsRadio_ === SecureDnsMode.SECURE) { this.updateDnsPrefs_(SecureDnsMode.SECURE); } this.updatePrivacyPolicyLine_(); if (!this.$.secureResolverSelect.value) { this.$.secureDnsInput.focus(); } this.browserProxy_.recordUserDropdownInteraction( this.lastResolverOption_, this.$.secureResolverSelect.value); this.lastResolverOption_ = this.$.secureResolverSelect.value; } /** * Updates the setting to communicate the type of management, if any. The * setting is always collapsed if there is any management. */ private updateManagementView_(managementMode: SecureDnsUiManagementMode) { if (this.prefs === undefined) { return; } // If the underlying secure DNS mode pref has an enforced value, communicate // that via the toggle pref. const pref: chrome.settingsPrivate.PrefObject = { key: '', type: chrome.settingsPrivate.PrefType.BOOLEAN, value: this.secureDnsToggle_.value, }; if (this.getPref('dns_over_https.mode').enforcement === chrome.settingsPrivate.Enforcement.ENFORCED) { pref.enforcement = chrome.settingsPrivate.Enforcement.ENFORCED; pref.controlledBy = this.getPref('dns_over_https.mode').controlledBy; this.secureDnsDescription_ = loadTimeData.getString('secureDnsDescription'); } else { // If the secure DNS mode was forcefully overridden by Chrome, provide an // explanation in the setting subtitle. switch (managementMode) { case SecureDnsUiManagementMode.NO_OVERRIDE: this.secureDnsDescription_ = loadTimeData.getString('secureDnsDescription'); break; case SecureDnsUiManagementMode.DISABLED_MANAGED: pref.enforcement = chrome.settingsPrivate.Enforcement.ENFORCED; this.secureDnsDescription_ = loadTimeData.getString('secureDnsDisabledForManagedEnvironment'); break; case SecureDnsUiManagementMode.DISABLED_PARENTAL_CONTROLS: pref.enforcement = chrome.settingsPrivate.Enforcement.ENFORCED; this.secureDnsDescription_ = loadTimeData.getString('secureDnsDisabledForParentalControl'); break; default: assertNotReached( 'Received unknown secure DNS management mode ' + managementMode); } } this.secureDnsToggle_ = pref; if (this.secureDnsToggle_.enforcement === chrome.settingsPrivate.Enforcement.ENFORCED) { this.showRadioGroup_ = false; } else { this.showRadioGroup_ = this.secureDnsToggle_.value; } } /** * Updates the UI to represent the given secure DNS templates. * @param secureDnsTemplates List of secure DNS templates in the current host * resolver configuration. */ private updateTemplatesRepresentation_(secureDnsTemplates: Array<string>) { // If there is exactly one template and it is one of the non-custom dropdown // options, select that option. if (secureDnsTemplates.length === 1) { const resolver = this.resolverOptions_.slice(1).find( r => r.value === secureDnsTemplates[0]); if (resolver) { this.$.secureResolverSelect.value = resolver.value; this.lastResolverOption_ = resolver.value; return; } } // Otherwise, select the custom option. this.$.secureResolverSelect.value = ''; this.lastResolverOption_ = ''; // Only update the custom input field if the templates are non-empty. // Otherwise, we may be clearing a previous value that the user wishes to // reuse. if (secureDnsTemplates.length > 0) { this.secureDnsInputValue_ = secureDnsTemplates.join(' '); } } /** * Displays the privacy policy corresponding to the selected dropdown resolver * or hides the privacy policy line if a custom resolver is selected. */ private updatePrivacyPolicyLine_() { // If the selected item is the custom provider option, hide the privacy // policy line. if (!this.$.secureResolverSelect.value) { this.$.privacyPolicy.style.display = 'none'; this.$.secureDnsInput.style.display = 'block'; return; } // Otherwise, display the corresponding privacy policy. this.$.privacyPolicy.style.display = 'block'; this.$.secureDnsInput.style.display = 'none'; const resolver = this.resolverOptions_.find( r => r.value === this.$.secureResolverSelect.value); if (!resolver) { return; } this.privacyPolicyString_ = loadTimeData.substituteString( loadTimeData.getString('secureDnsSecureDropdownModePrivacyPolicy'), resolver.policy); } /** * Updates the underlying prefs if a custom entry was determined to be valid. * If the custom entry was determined to be invalid, moves the selected radio * button away from 'secure' if necessary. */ private onSecureDnsInputEvaluated_( event: CustomEvent<{text: string, isValid: boolean}>) { if (event.detail.isValid) { this.updateDnsPrefs_(this.secureDnsRadio_, event.detail.text); } } } customElements.define(SettingsSecureDnsElement.is, SettingsSecureDnsElement);
the_stack
import * as _ from 'lodash'; import { expect } from 'chai'; import * as parallel from 'mocha.parallel'; import type * as BalenaSdk from '../../..'; import { toWritable } from '../../../lib/util/types'; import { timeSuite } from '../../util'; import type * as tagsHelper from './tags'; import { balena, credentials, givenADevice, givenAnApplication, givenLoggedInUser, givenMulticontainerApplicationWithADevice, givenInitialOrganization, sdkOpts, applicationRetrievalFields, } from '../setup'; import { itShouldSetGetAndRemoveTags, itShouldGetAllTagsByResource, } from './tags'; describe('Application Model', function () { timeSuite(before); givenLoggedInUser(before); givenInitialOrganization(before); describe('given no applications', function () { describe('[read operations]', function () { parallel('balena.models.application.getAll()', function () { it('should include public apps [promise]', async function () { const applications = await balena.models.application.getAll(); const publicApps = applications.filter((app) => app.is_public); expect(publicApps).to.have.length.that.is.greaterThan(0); }); it('should include public apps [callback]', function (done) { // @ts-expect-error balena.models.application.getAll(function (err, applications) { try { expect(err).to.be.null; const publicApps = applications.filter((app) => app.is_public); expect(publicApps).to.have.length.that.is.greaterThan(0); done(); } catch (err) { done(err); } }); }); it('should eventually become an empty array of accessible apps [Promise]', async function () { const apps = await balena.models.application.getAll( {}, 'directly_accessible', ); expect(apps).to.deep.equal([]); }); it('should eventually become an empty array of accessible apps [callback]', function (done) { balena.models.application.getAll( {}, 'directly_accessible', // @ts-expect-error function (err, applications) { try { expect(err).to.be.null; expect(applications).to.deep.equal([]); done(); } catch (err) { done(err); } }, ); }); }); parallel( 'balena.models.application.getAllDirectlyAccessible()', function () { it('should eventually become an empty array of accessible apps [Promise]', async function () { const apps = await balena.models.application.getAllDirectlyAccessible(); expect(apps).to.deep.equal([]); }); it('should eventually become an empty array of accessible apps [callback]', function (done) { balena.models.application.getAllDirectlyAccessible( {}, // @ts-expect-error function (err, applications) { try { expect(err).to.be.null; expect(applications).to.deep.equal([]); done(); } catch (err) { done(err); } }, ); }); }, ); parallel('balena.models.application.getAppByName()', function () { it('should eventually reject [Promise]', async function () { const promise = balena.models.application.getAppByName('testapp'); await expect(promise).to.be.rejected.and.eventually.have.property( 'code', 'BalenaApplicationNotFound', ); }); it('should eventually reject [callback]', function (done) { balena.models.application.getAppByName( 'testapp', // @ts-expect-error function (err) { try { expect(err).to.not.be.undefined; done(); } catch (err) { done(err); } }, ); }); }); parallel('balena.models.application.getAppByOwner()', function () { it('should eventually reject [Promise]', function () { const promise = balena.models.application.getAppByOwner( 'testapp', 'FooBar', ); return expect(promise).to.be.rejected; }); it('should eventually reject [callback]', function (done) { balena.models.application.getAppByOwner( 'testapp', 'FooBar', // @ts-expect-error function (err) { try { expect(err).to.not.be.undefined; done(); } catch (err) { done(err); } }, ); }); }); describe('balena.models.application.hasAny()', function () { it('should eventually be false', function () { const promise = balena.models.application.hasAny(); return expect(promise).to.eventually.be.false; }); }); }); describe('balena.models.application.create()', function () { let ctx: Mocha.Context; before(function () { ctx = this; }); parallel('[read operations]', function () { it('should be rejected if the application type is invalid', function () { const promise = balena.models.application.create({ name: 'FooBar', applicationType: 'non-existing', deviceType: 'raspberry-pi', organization: ctx.initialOrg.id, }); return expect(promise).to.be.rejectedWith( 'Invalid application type: non-existing', ); }); it('should be rejected if the device type is invalid', function () { const promise = balena.models.application.create({ name: 'FooBar', applicationType: 'microservices-starter', deviceType: 'foobarbaz', organization: ctx.initialOrg.id, }); return expect(promise).to.be.rejectedWith( 'Invalid device type: foobarbaz', ); }); it('should be rejected if the device type is discontinued', function () { const promise = balena.models.application.create({ name: 'FooBar', applicationType: 'microservices-starter', deviceType: 'edge', organization: ctx.initialOrg.id, }); return expect(promise).to.be.rejectedWith( 'Discontinued device type: edge', ); }); it('should be rejected if the name has less than four characters', function () { const promise = balena.models.application.create({ name: 'Foo', applicationType: 'microservices-starter', deviceType: 'raspberry-pi', organization: ctx.initialOrg.id, }); return expect(promise).to.be.rejected.then(function (error) { expect(error).to.have.property('code', 'BalenaRequestError'); expect(error).to.have.property('statusCode', 400); return expect(error) .to.have.property('message') .that.contains( 'It is necessary that each application has an app name that has a Length (Type) that is greater than or equal to 4 and is less than or equal to 100', ); }); }); it('should be rejected if the user did not provide an organization parameter', () => expect( // @ts-expect-error balena.models.application.create({ name: 'FooBar', deviceType: 'raspberry-pi', }), ).to.be.rejectedWith( "undefined is not a valid value for parameter 'organization'", )); it('should be rejected if the user does not have access to find the organization by handle', function () { const promise = balena.models.application.create({ name: 'FooBar', deviceType: 'raspberry-pi', // add some extra invalid characters to the organization's handle just to be sure organization: 'balena-test-non-existing-organization-handle-!@#', }); return expect(promise).to.be.rejectedWith( 'Organization not found: balena-test-non-existing-organization-handle-!@#', ); }); it('should be rejected if the user does not have access to find the organization by id', function () { const promise = balena.models.application.create({ name: 'FooBar', deviceType: 'raspberry-pi', // This test will fail if org 1 adds the SDK's test user as a member... organization: 1, }); return expect(promise).to.be.rejectedWith( 'Organization not found: 1', ); }); }); describe('[mutating operations]', function () { let appCount = 0; beforeEach(() => { appCount++; }); after(() => balena.pine.delete({ resource: 'application', options: { $filter: { 1: 1 }, }, }), ); ['id', 'handle'].forEach((prop) => it(`should be able to create an application using the user's initial organization ${prop}`, async function () { await balena.models.application.create({ name: `FooBarByOrg${_.startCase(prop)}`, deviceType: 'raspberrypi', organization: this.initialOrg[prop], }); const apps = await balena.models.application.getAll( { $select: 'id', $expand: { organization: { $select: 'id' } }, }, 'directly_accessible', ); expect(apps).to.have.length(appCount); expect(apps[0]).to.have.nested.property( 'organization[0].id', this.initialOrg.id, ); }), ); it('...should be able to create an application w/o providing an application type', function () { return balena.models.application .create({ name: 'FooBarNoAppType', deviceType: 'raspberry-pi', organization: this.initialOrg.id, }) .then(function () { const promise = balena.models.application.getAll( {}, 'directly_accessible', ); return expect(promise).to.eventually.have.length(appCount); }); }); it('...should be able to create an application with a specific application type', function () { return balena.models.application .create({ name: 'FooBarWithAppType', applicationType: 'microservices-starter', deviceType: 'raspberry-pi', organization: this.initialOrg.id, }) .then(function (app) { expect(app).to.have.property('id').that.is.a('number'); expect(app.is_for__device_type) .to.be.an('object') .that.has.property('__id') .that.is.a('number'); return balena.models.application .getAll( { $expand: { is_for__device_type: { $select: 'slug' } }, $orderby: 'id desc', }, 'directly_accessible', ) .then(function (apps) { expect(apps).to.have.length(appCount); expect(apps[0]).to.have.property('id', app.id); expect(apps[0]) .to.have.property('is_for__device_type') .that.is.an('array'); expect(apps[0].is_for__device_type).to.have.length(1); return expect( apps[0].is_for__device_type[0], ).to.have.property('slug', 'raspberry-pi'); }); }); }); it('...should be able to create an application using a device type alias', async function () { await balena.models.application.create({ name: 'FooBarDeviceTypeAlias', applicationType: 'microservices-starter', deviceType: 'raspberrypi', organization: this.initialOrg.id, }); const promise = balena.models.application.getAll( {}, 'directly_accessible', ); await expect(promise).to.eventually.have.length(appCount); }); it('should be able to create a child application', async function () { const parentApplication = await balena.models.application.create({ name: 'FooBarParent', applicationType: 'microservices-starter', deviceType: 'raspberry-pi', organization: this.initialOrg.id, }); const childApplication = await balena.models.application.create({ name: 'FooBarChild', applicationType: 'microservices-starter', deviceType: 'generic', organization: this.initialOrg.id, parent: parentApplication.id, }); expect(childApplication.depends_on__application).to.be.an('object'); expect(childApplication.depends_on__application).to.have.property( '__id', parentApplication.id, ); const [retrievedParentApplication, retrievedChildApplication] = await balena.models.application.getAll({ $select: ['id', 'depends_on__application'], $filter: { id: { $in: [parentApplication.id, childApplication.id], }, }, $orderby: { id: 'asc' }, }); expect(retrievedChildApplication.depends_on__application).to.be.an( 'object', ); expect( retrievedChildApplication.depends_on__application, ).to.have.property('__id', retrievedParentApplication.id); }); }); }); }); describe('given a single application', function () { describe('balena.models.application.remove()', function () { it('should be rejected if the application slug does not exist', function () { const promise = balena.models.application.remove( `${this.initialOrg.handle}/helloworldapp`, ); return expect(promise).to.be.rejectedWith( `Application not found: ${this.initialOrg.handle}/helloworldapp`, ); }); it('should be rejected if the application id does not exist', function () { const promise = balena.models.application.remove(999999); return expect(promise).to.be.rejectedWith( 'Application not found: 999999', ); }); describe('[mutating operations]', function () { givenAnApplication(beforeEach); applicationRetrievalFields.forEach((prop) => { it(`should be able to remove an existing application by ${prop}`, function () { return balena.models.application .remove(this.application[prop]) .then(function () { const promise = balena.models.application.getAll( {}, 'directly_accessible', ); return expect(promise).to.eventually.have.length(0); }); }); }); }); }); describe('[contained scenario]', function () { givenAnApplication(before); describe('[read operations]', function () { let ctx: Mocha.Context; before(function () { ctx = this; }); describe('balena.models.application.hasAny()', function () { it('should eventually be true', function () { const promise = balena.models.application.hasAny(); return expect(promise).to.eventually.be.true; }); }); describe('balena.models.application.create()', function () { it('should reject if trying to create an app with the same name', function () { const promise = balena.models.application.create({ name: 'FooBar', applicationType: 'microservices-starter', deviceType: 'beaglebone-black', organization: this.initialOrg.id, }); return expect(promise).to.be.rejected.then(function (error) { expect(error).to.have.property('code', 'BalenaRequestError'); expect(error).to.have.property('statusCode', 409); return expect(error) .to.have.property('message') .that.matches(/\bunique\b/i); }); }); }); // TODO: re-enable once the API regression gets fixed // expect(error).to.have.property('message').that.contains('Application name must be unique') describe('balena.models.application.hasAny()', function () { it('should eventually be true', function () { const promise = balena.models.application.hasAny(); return expect(promise).to.eventually.be.true; }); }); describe('balena.models.application.getAppByName()', function () { it('should find the created application', async function () { const app = await balena.models.application.getAppByName('FooBar'); expect(app.id).to.equal(ctx.application.id); }); it('should find the created application [directly_accessible]', async function () { const app = await balena.models.application.getAppByName( 'FooBar', {}, 'directly_accessible', ); expect(app.id).to.equal(ctx.application.id); }); }); parallel('balena.models.application.getAppByOwner()', function () { it('should find the created application', function () { return balena.models.application .getAppByOwner('FooBar', ctx.initialOrg.handle) .then((application) => { return expect(application.id).to.equal(ctx.application.id); }); }); it('should not find the created application with a different organization handle', function () { const promise = balena.models.application.getAppByOwner( 'FooBar', 'test_org_handle', ); return expect(promise).to.eventually.be.rejectedWith( 'Application not found: test_org_handle/foobar', ); }); }); parallel('balena.models.application.getAll()', function () { it('should eventually become an array containing the application', async function () { const applications = await balena.models.application.getAll( {}, 'directly_accessible', ); expect(applications).to.have.length(1); expect(applications[0].id).to.equal(ctx.application.id); }); it('should support arbitrary pinejs options [Promise]', async function () { const applications = await balena.models.application.getAll( { $expand: { organization: { $select: 'handle' } } }, 'directly_accessible', ); expect(applications[0].organization[0].handle).to.equal( credentials.username, ); }); it('should support arbitrary pinejs options [callback]', function (done) { balena.models.application.getAll( { $expand: { organization: { $select: 'handle' } } }, 'directly_accessible', // @ts-expect-error function (err, applications) { try { expect(err).to.be.null; expect(applications[0].organization[0].handle).to.equal( credentials.username, ); done(); } catch (err) { done(err); } }, ); }); }); parallel( 'balena.models.application.getAllDirectlyAccessible()', function () { it('should eventually become an array containing the application', async function () { const applications = await balena.models.application.getAllDirectlyAccessible(); expect(applications).to.have.length(1); expect(applications[0].id).to.equal(ctx.application.id); }); it('should support arbitrary pinejs options [Promise]', async function () { const applications = await balena.models.application.getAllDirectlyAccessible({ $expand: { organization: { $select: 'handle' } }, }); expect(applications[0].organization[0].handle).to.equal( credentials.username, ); }); it('should support arbitrary pinejs options [callback]', function (done) { balena.models.application.getAllDirectlyAccessible( { $expand: { organization: { $select: 'handle' } } }, // @ts-expect-error function (err, applications) { try { expect(err).to.be.null; expect(applications[0].organization[0].handle).to.equal( credentials.username, ); done(); } catch (err) { done(err); } }, ); }); }, ); parallel('balena.models.application.get()', function () { applicationRetrievalFields.forEach((prop) => it(`should be able to get an application by ${prop}`, function () { const promise = balena.models.application.get( ctx.application[prop], ); return expect(promise).to.become(ctx.application); }), ); it('should be able to get an application by slug regardless of casing', function () { if ( ctx.application.app_name === ctx.application.slug.toUpperCase() ) { throw new Error( 'This tests expects the application name to not be fully upper case', ); } const promise = balena.models.application.get( ctx.application.slug.toUpperCase(), ); return expect(promise).to.become(ctx.application); }); it('should be rejected if the application slug does not exist', function () { const promise = balena.models.application.get( `${ctx.initialOrg.handle}/helloworldapp`, ); return expect(promise).to.be.rejectedWith( `Application not found: ${ctx.initialOrg.handle}/helloworldapp`, ); }); it('should be rejected if the application id does not exist', function () { const promise = balena.models.application.get(999999); return expect(promise).to.be.rejectedWith( 'Application not found: 999999', ); }); it('should support arbitrary pinejs options', function () { return balena.models.application .get(ctx.application.id, { $expand: { organization: { $select: 'handle' } }, }) .then((application) => expect(application.organization[0].handle).to.equal( credentials.username, ), ); }); }); parallel( 'balena.models.application.getDirectlyAccessible()', function () { applicationRetrievalFields.forEach((prop) => it(`should be able to get an application by ${prop}`, function () { const promise = balena.models.application.getDirectlyAccessible( ctx.application[prop], ); return expect(promise).to.become(ctx.application); }), ); }, ); parallel('balena.models.application.has()', function () { applicationRetrievalFields.forEach((prop) => it(`should eventually be true if the application ${prop} exists`, function () { const promise = balena.models.application.has( ctx.application[prop], ); return expect(promise).to.eventually.be.true; }), ); it('should return false if the application id is undefined', function () { // @ts-expect-error const promise = balena.models.application.has(undefined); return expect(promise).to.eventually.be.false; }); it('should eventually be false if the application slug does not exist', function () { const promise = balena.models.application.has( `${ctx.initialOrg.handle}/helloworldapp`, ); return expect(promise).to.eventually.be.false; }); it('should eventually be false if the application id does not exist', function () { const promise = balena.models.application.has(999999); return expect(promise).to.eventually.be.false; }); }); }); describe('balena.models.application.rename()', function () { it('should be rejected if the application slug does not exist', function () { const promise = balena.models.application.rename( `${this.initialOrg.handle}/helloworldapp`, 'newAppName', ); return expect(promise).to.be.rejectedWith( `Application not found: ${this.initialOrg.handle}/helloworldapp`, ); }); describe('[mutating operations]', function () { let originalAppName; before(function () { originalAppName = this.application.app_name; }); afterEach(function () { return balena.models.application.rename( this.application.id, originalAppName, ); }); applicationRetrievalFields.forEach((prop) => { it(`should be able to rename an existing application by ${prop}`, function () { return balena.models.application .rename(this.application[prop], 'newApplicationName_' + prop) .then(function () { balena.models.application .get('newApplicationName_' + prop) .then(function (app) { return expect(app).to.have.property( 'app_name', 'newApplicationName_' + prop, ); }); }); }); }); }); }); describe('balena.models.application.generateApiKey()', function () { applicationRetrievalFields.forEach((prop) => it(`should be able to generate an API key by ${prop}`, async function () { const apiKey = await balena.models.application.generateApiKey( this.application[prop], ); expect(apiKey).to.be.a('string'); expect(apiKey).to.have.length(32); }), ); it('should be rejected if the application slug does not exist', function () { const promise = balena.models.application.generateApiKey( `${this.initialOrg.handle}/helloworldapp`, ); return expect(promise).to.be.rejectedWith( `Application not found: ${this.initialOrg.handle}/helloworldapp`, ); }); it('should be rejected if the application id does not exist', function () { const promise = balena.models.application.generateApiKey(999999); return expect(promise).to.be.rejectedWith( 'Application not found: 999999', ); }); }); describe('balena.models.application.generateProvisioningKey()', function () { const getProvisioningKeys = async function (appNameOrSlug) { const provisioningKeys = await balena.models.apiKey.getProvisioningApiKeysByApplication( appNameOrSlug, ); expect(provisioningKeys).to.be.an('array'); return provisioningKeys; }; applicationRetrievalFields.forEach((prop) => it(`should be able to generate a provisioning key by ${prop}`, function () { return balena.models.application .generateProvisioningKey(this.application[prop]) .then(function (key) { expect(_.isString(key)).to.be.true; return expect(key).to.have.length(32); }); }), ); applicationRetrievalFields.forEach((prop) => { it(`should be able to generate a provisioning key by ${prop} with key name as key_${prop}`, async function () { const provisioningKeys = await getProvisioningKeys( this.application[prop], ); const key = await balena.models.application.generateProvisioningKey( this.application[prop], `key_${prop}`, ); expect(key).to.be.a('string'); expect(key).to.have.length(32); const updatedProvisioningKeys = await getProvisioningKeys( this.application[prop], ); const provisionKeys = _.differenceWith( updatedProvisioningKeys, provisioningKeys, _.isEqual, ); expect(provisionKeys).to.have.lengthOf(1); expect(provisionKeys[0]).to.have.property('name'); expect(provisionKeys[0]) .to.have.property('name') .to.be.equal(`key_${prop}`); }); it(`should be able to generate a provisioning key by ${prop} with description as 'Provisioning key generated with name key_${prop}'`, async function () { const provisioningKeys = await getProvisioningKeys( this.application[prop], ); const key = await balena.models.application.generateProvisioningKey( this.application[prop], `key_${prop}`, `Provisioning key generated with name key_${prop}`, ); expect(key).to.be.a('string'); expect(key).to.have.length(32); const updatedProvisioningKeys = await getProvisioningKeys( this.application[prop], ); const provisionKeys = _.differenceWith( updatedProvisioningKeys, provisioningKeys, _.isEqual, ); expect(provisionKeys).to.have.lengthOf(1); expect(provisionKeys[0]).to.have.property('name'); expect(provisionKeys[0]) .to.have.property('description') .to.be.equal(`Provisioning key generated with name key_${prop}`); }); }); it('should be rejected if the application slug does not exist', function () { const promise = balena.models.application.generateProvisioningKey( `${this.initialOrg.handle}/helloworldapp`, ); return expect(promise).to.be.rejectedWith( `Application not found: ${this.initialOrg.handle}/helloworldapp`, ); }); it('should be rejected if the application id does not exist', function () { const promise = balena.models.application.generateProvisioningKey(999999); return expect(promise).to.be.rejectedWith( 'Application not found: 999999', ); }); }); describe('balena.models.application.grantSupportAccess()', function () { it('should throw an error if the expiry time stamp is in the past', function () { const expiryTimestamp = Date.now() - 3600 * 1000; return expect( balena.models.application.grantSupportAccess( this.application.id, expiryTimestamp, ), ).to.be.rejected; }); it('should throw an error if the expiry time stamp is undefined', function () { return expect( // @ts-expect-error balena.models.application.grantSupportAccess(this.application.id), ).to.be.rejected; }); it('should grant support access until the specified time', function () { const expiryTime = Date.now() + 3600 * 1000; const promise = balena.models.application .grantSupportAccess(this.application.id, expiryTime) .then(() => { return balena.models.application.get(this.application.id, { $select: 'is_accessible_by_support_until__date', }); }) .then((app) => Date.parse(app.is_accessible_by_support_until__date), ); return expect(promise).to.eventually.equal(expiryTime); }); }); describe('balena.models.application.revokeSupportAccess()', () => { it('...should revoke support access', async function () { const { is_accessible_by_support_until__date: originalSupportExpiry, } = await balena.models.application.get(this.application.id, { $select: 'is_accessible_by_support_until__date', }); expect(originalSupportExpiry).to.not.equal(null); await balena.models.application.revokeSupportAccess( this.application.id, ); const { is_accessible_by_support_until__date: supportExpiry } = await balena.models.application.get(this.application.id, { $select: 'is_accessible_by_support_until__date', }); expect(supportExpiry).to.equal(null); }); }); describe('balena.models.application.tags', function () { const tagTestOptions: tagsHelper.Options<BalenaSdk.ApplicationTag> = { model: balena.models.application .tags as tagsHelper.TagModelBase<BalenaSdk.ApplicationTag>, modelNamespace: 'balena.models.application.tags', resourceName: 'application', uniquePropertyNames: applicationRetrievalFields, }; before(function () { tagTestOptions.resourceProvider = () => this.application; }); itShouldSetGetAndRemoveTags(tagTestOptions); describe('balena.models.application.tags.getAllByApplication()', function () { itShouldGetAllTagsByResource(tagTestOptions); }); }); describe('balena.models.application.configVar', function () { const configVarModel = balena.models.application.configVar; applicationRetrievalFields.forEach(function (appParam) { const appParamUpper = appParam.toUpperCase(); it(`can create a variable by ${appParam}`, function () { const promise = configVarModel.set( this.application[appParam], `BALENA_EDITOR_${appParamUpper}`, 'vim', ); return expect(promise).to.not.be.rejected; }); it(`...can retrieve a created variable by ${appParam}`, function () { return configVarModel .get(this.application[appParam], `BALENA_EDITOR_${appParamUpper}`) .then((result) => expect(result).to.equal('vim')); }); it(`...can update and retrieve a variable by ${appParam}`, function () { return configVarModel .set( this.application[appParam], `BALENA_EDITOR_${appParamUpper}`, 'emacs', ) .then(() => { return configVarModel.get( this.application[appParam], `BALENA_EDITOR_${appParamUpper}`, ); }) .then((result) => expect(result).to.equal('emacs')); }); it(`...can delete and then fail to retrieve a variable by ${appParam}`, function () { return configVarModel .remove( this.application[appParam], `BALENA_EDITOR_${appParamUpper}`, ) .then(() => { return configVarModel.get( this.application[appParam], `BALENA_EDITOR_${appParamUpper}`, ); }) .then((result) => expect(result).to.equal(undefined)); }); it(`can create and then retrieve multiple variables by ${appParam}`, function () { return Promise.all([ configVarModel.set( this.application[appParam], `BALENA_A_${appParamUpper}`, 'a', ), configVarModel.set( this.application[appParam], `BALENA_B_${appParamUpper}`, 'b', ), ]) .then(() => { return configVarModel.getAllByApplication( this.application[appParam], ); }) .then(function (result) { expect(_.find(result, { name: `BALENA_A_${appParamUpper}` })) .to.be.an('object') .that.has.property('value', 'a'); return expect( _.find(result, { name: `BALENA_B_${appParamUpper}` }), ) .to.be.an('object') .that.has.property('value', 'b'); }) .then(() => Promise.all([ configVarModel.remove( this.application[appParam], `BALENA_A_${appParamUpper}`, ), configVarModel.remove( this.application[appParam], `BALENA_B_${appParamUpper}`, ), ]), ); }); }); }); describe('balena.models.application.envVar', function () { const envVarModel = balena.models.application.envVar; applicationRetrievalFields.forEach(function (appParam) { it(`can create a variable by ${appParam}`, function () { const promise = envVarModel.set( this.application[appParam], `EDITOR_BY_${appParam}`, 'vim', ); return expect(promise).to.not.be.rejected; }); it(`...can retrieve a created variable by ${appParam}`, function () { return envVarModel .get(this.application[appParam], `EDITOR_BY_${appParam}`) .then((result) => expect(result).to.equal('vim')); }); it(`...can update and retrieve a variable by ${appParam}`, function () { return envVarModel .set(this.application[appParam], `EDITOR_BY_${appParam}`, 'emacs') .then(() => { return envVarModel.get( this.application[appParam], `EDITOR_BY_${appParam}`, ); }) .then((result) => expect(result).to.equal('emacs')); }); it(`...can delete and then fail to retrieve a variable by ${appParam}`, function () { return envVarModel .remove(this.application[appParam], `EDITOR_BY_${appParam}`) .then(() => { return envVarModel.get( this.application[appParam], `EDITOR_BY_${appParam}`, ); }) .then((result) => expect(result).to.equal(undefined)); }); it(`can create and then retrieve multiple variables by ${appParam}`, function () { return Promise.all([ envVarModel.set( this.application[appParam], `A_BY_${appParam}`, 'a', ), envVarModel.set( this.application[appParam], `B_BY_${appParam}`, 'b', ), ]) .then(() => { return envVarModel.getAllByApplication( this.application[appParam], ); }) .then(function (result) { expect(_.find(result, { name: `A_BY_${appParam}` })) .to.be.an('object') .that.has.property('value', 'a'); return expect(_.find(result, { name: `B_BY_${appParam}` })) .to.be.an('object') .that.has.property('value', 'b'); }) .then(() => Promise.all([ envVarModel.remove( this.application[appParam], `A_BY_${appParam}`, ), envVarModel.remove( this.application[appParam], `B_BY_${appParam}`, ), ]), ); }); }); }); describe('balena.models.application.buildEnvVar', function () { const envVarModel = balena.models.application.buildVar; applicationRetrievalFields.forEach(function (appParam) { it(`can create a variable by ${appParam}`, function () { const promise = envVarModel.set( this.application[appParam], `EDITOR_BY_${appParam}`, 'vim', ); return expect(promise).to.not.be.rejected; }); it(`...can retrieve a created variable by ${appParam}`, function () { return envVarModel .get(this.application[appParam], `EDITOR_BY_${appParam}`) .then((result) => expect(result).to.equal('vim')); }); it(`...can update and retrieve a variable by ${appParam}`, function () { return envVarModel .set(this.application[appParam], `EDITOR_BY_${appParam}`, 'emacs') .then(() => { return envVarModel.get( this.application[appParam], `EDITOR_BY_${appParam}`, ); }) .then((result) => expect(result).to.equal('emacs')); }); it(`...can delete and then fail to retrieve a variable by ${appParam}`, function () { return envVarModel .remove(this.application[appParam], `EDITOR_BY_${appParam}`) .then(() => { return envVarModel.get( this.application[appParam], `EDITOR_BY_${appParam}`, ); }) .then((result) => expect(result).to.equal(undefined)); }); it(`can create and then retrieve multiple variables by ${appParam}`, function () { return Promise.all([ envVarModel.set( this.application[appParam], `A_BY_${appParam}`, 'a', ), envVarModel.set( this.application[appParam], `B_BY_${appParam}`, 'b', ), ]) .then(() => { return envVarModel.getAllByApplication( this.application[appParam], ); }) .then(function (result) { expect(_.find(result, { name: `A_BY_${appParam}` })) .to.be.an('object') .that.has.property('value', 'a'); return expect(_.find(result, { name: `B_BY_${appParam}` })) .to.be.an('object') .that.has.property('value', 'b'); }) .then(() => Promise.all([ envVarModel.remove( this.application[appParam], `A_BY_${appParam}`, ), envVarModel.remove( this.application[appParam], `B_BY_${appParam}`, ), ]), ); }); }); }); describe('with a registered device', function () { givenADevice(before); describe('balena.models.application.enableDeviceUrls()', () => { it("should enable the device url for the application's devices", function () { const promise = balena.models.application .enableDeviceUrls(this.application.id) .then(() => { return balena.models.device.hasDeviceUrl(this.device.uuid); }); return expect(promise).to.eventually.be.true; }); }); describe('balena.models.application.disableDeviceUrls()', () => { it("...should disable the device url for the application's devices", function () { const promise = balena.models.device .enableDeviceUrl(this.device.uuid) .then(() => { return balena.models.application.disableDeviceUrls( this.application.id, ); }) .then(() => { return balena.models.device.hasDeviceUrl(this.device.uuid); }); return expect(promise).to.eventually.be.false; }); }); describe('given two releases', function () { before(async function () { const userId = await balena.auth.getUserId(); this.oldRelease = await balena.pine.post({ resource: 'release', body: { belongs_to__application: this.application.id, is_created_by__user: userId, commit: 'old-release-commit', status: 'success', source: 'cloud', composition: {}, start_timestamp: 1234, }, }); this.newRelease = await balena.pine.post({ resource: 'release', body: { belongs_to__application: this.application.id, is_created_by__user: userId, commit: 'new-release-commit', status: 'success', source: 'cloud', composition: {}, start_timestamp: 54321, }, }); }); describe('balena.models.application.willTrackNewReleases()', function () { it('should be configured to track new releases by default', async function () { expect( await balena.models.application.willTrackNewReleases( this.application.id, ), ).to.be.true; }); it('...should be false when should_track_latest_release is false', async function () { await balena.pine.patch({ resource: 'application', id: this.application.id, body: { should_track_latest_release: false }, }); expect( await balena.models.application.willTrackNewReleases( this.application.id, ), ).to.be.false; await balena.pine.patch({ resource: 'application', id: this.application.id, body: { should_track_latest_release: true }, }); expect( await balena.models.application.willTrackNewReleases( this.application.id, ), ).to.be.true; }); it('...should be true regardless of the current commit', async function () { await balena.pine.patch({ resource: 'application', id: this.application.id, body: { should_be_running__release: this.oldRelease.id }, }); expect( await balena.models.application.willTrackNewReleases( this.application.id, ), ).to.be.true; await balena.pine.patch({ resource: 'application', id: this.application.id, body: { should_be_running__release: this.newRelease.id }, }); expect( await balena.models.application.willTrackNewReleases( this.application.id, ), ).to.be.true; }); }); describe('balena.models.application.isTrackingLatestRelease()', function () { it('should be tracking the latest release by default', async function () { expect( await balena.models.application.isTrackingLatestRelease( this.application.id, ), ).to.be.true; }); it('...should be false when should_track_latest_release is false', async function () { await balena.pine.patch({ resource: 'application', id: this.application.id, body: { should_track_latest_release: false }, }); expect( await balena.models.application.isTrackingLatestRelease( this.application.id, ), ).to.be.false; await balena.pine.patch({ resource: 'application', id: this.application.id, body: { should_track_latest_release: true }, }); expect( await balena.models.application.isTrackingLatestRelease( this.application.id, ), ).to.be.true; }); it('...should be false when the current commit is not of the latest release', async function () { await balena.pine.patch({ resource: 'application', id: this.application.id, body: { should_be_running__release: this.oldRelease.id }, }); expect( await balena.models.application.isTrackingLatestRelease( this.application.id, ), ).to.be.false; await balena.pine.patch({ resource: 'application', id: this.application.id, body: { should_be_running__release: this.newRelease.id }, }); expect( await balena.models.application.isTrackingLatestRelease( this.application.id, ), ).to.be.true; }); }); describe('balena.models.application.getTargetReleaseHash()', () => { it('should retrieve the commit hash of the current release', function () { const promise = balena.models.application.getTargetReleaseHash( this.application.id, ); return expect(promise).to.eventually.equal('new-release-commit'); }); }); describe('balena.models.application.pinToRelease()', () => { it('should set the application to specific release & disable latest release tracking', function () { return balena.models.application .pinToRelease(this.application.id, 'old-release-commit') .then(() => { const promise = balena.models.application.getTargetReleaseHash( this.application.id, ); return expect(promise).to.eventually.equal( 'old-release-commit', ); }) .then(() => { const promise = balena.models.application.willTrackNewReleases( this.application.id, ); return expect(promise).to.eventually.be.false; }) .then(() => { const promise = balena.models.application.isTrackingLatestRelease( this.application.id, ); return expect(promise).to.eventually.be.false; }); }); }); describe('balena.models.application.trackLatestRelease()', () => { it('...should re-enable latest release tracking', async function () { expect( await balena.models.application.isTrackingLatestRelease( this.application.id, ), ).to.be.false; await balena.models.application.trackLatestRelease( this.application.id, ); expect( await balena.models.application.getTargetReleaseHash( this.application.id, ), ).to.equal('new-release-commit'); expect( await balena.models.application.willTrackNewReleases( this.application.id, ), ).to.be.true; expect( await balena.models.application.isTrackingLatestRelease( this.application.id, ), ).to.be.true; }); }); ( [ [ 'draft', async function () { this.testNonLatestRelease = await balena.pine.post({ resource: 'release', body: { belongs_to__application: this.application.id, is_created_by__user: await balena.auth.getUserId(), commit: 'draft-release-commit', status: 'success', source: 'cloud', is_final: false, composition: {}, start_timestamp: Date.now(), }, }); }, ], [ 'invalidated', async function () { this.testNonLatestRelease = await balena.pine.post({ resource: 'release', body: { belongs_to__application: this.application.id, is_created_by__user: await balena.auth.getUserId(), commit: 'invalidated-release-commit', status: 'success', source: 'cloud', is_invalidated: true, composition: {}, start_timestamp: Date.now(), }, }); }, ], ] as const ).forEach(([releaseType, prepareFn]) => { describe(`given a new ${releaseType} release`, function () { before(prepareFn); describe('balena.models.application.isTrackingLatestRelease()', function () { it(`should not account newer ${releaseType} releases as the default`, async function () { expect( await balena.models.application.getTargetReleaseHash( this.application.id, ), ).to.equal('new-release-commit'); expect( await balena.models.application.isTrackingLatestRelease( this.application.id, ), ).to.be.true; }); }); describe('balena.models.application.trackLatestRelease()', () => { it(`should not use a ${releaseType} releases as the latest`, async function () { await balena.models.application.pinToRelease( this.application.id, 'old-release-commit', ); expect( await balena.models.application.isTrackingLatestRelease( this.application.id, ), ).to.be.false; await balena.models.application.trackLatestRelease( this.application.id, ); expect( await balena.models.application.getTargetReleaseHash( this.application.id, ), ).to.equal('new-release-commit'); expect( await balena.models.application.willTrackNewReleases( this.application.id, ), ).to.be.true; expect( await balena.models.application.isTrackingLatestRelease( this.application.id, ), ).to.be.true; }); }); }); }); }); }); }); }); describe('given a multicontainer application with a single offline device', function () { givenMulticontainerApplicationWithADevice(before); const itShouldBeAnApplicationWithDeviceServiceDetails = function ( application, expectCommit, ) { // Commit is empty on newly created application, so ignoring it if (expectCommit == null) { expectCommit = false; } const omittedFields = [ 'owns__device', 'should_be_running__release', '__metadata', ]; expect(_.omit(application, omittedFields)).to.deep.equal( _.omit(this.application, omittedFields), ); // Check the app's target release after the release got created expect(application.should_be_running__release).to.have.property( '__id', this.currentRelease.id, ); const deviceExpectation = { device_name: this.device.device_name, uuid: this.device.uuid, is_running__release: { __id: this.currentRelease.id, }, current_services: { web: [ { id: this.newWebInstall.id, service_id: this.webService.id, image_id: this.newWebImage.id, ...(expectCommit && { commit: 'new-release-commit' }), status: 'Downloading', download_progress: 50, }, { id: this.oldWebInstall.id, service_id: this.webService.id, image_id: this.oldWebImage.id, ...(expectCommit && { commit: 'old-release-commit' }), status: 'Running', download_progress: null, }, ], db: [ { id: this.newDbInstall.id, service_id: this.dbService.id, image_id: this.newDbImage.id, ...(expectCommit && { commit: 'new-release-commit' }), status: 'Running', download_progress: null, }, ], }, }; expect(application.owns__device).to.have.lengthOf(1); const [deviceDetails] = application.owns__device; expect(deviceDetails).to.deep.match(deviceExpectation); // Should include the Device model properties expect(deviceDetails.image_install).to.have.lengthOf(3); deviceDetails.image_install.forEach((imageInstall) => { expect(imageInstall) .to.have.property('id') .that.is.oneOf([ this.oldWebInstall.id, this.newWebInstall.id, this.newDbInstall.id, ]); expect(imageInstall) .to.have.property('download_progress') .that.is.oneOf([50, null]); expect(imageInstall).to.have.property('image').that.has.length(1); if (expectCommit) { expect(imageInstall) .to.have.property('is_provided_by__release') .that.has.length(1); } else { expect(imageInstall).to.not.have.property('is_provided_by__release'); } expect(imageInstall) .to.have.property('install_date') .that.is.a('string'); expect(imageInstall).to.have.property('status').that.is.a('string'); expect(imageInstall).to.not.have.property('service_id'); expect(imageInstall).to.not.have.property('image_id'); expect(imageInstall).to.not.have.property('commit'); }); expect(deviceDetails.gateway_download).to.have.lengthOf(0); // Augmented properties // Should filter out deleted image installs expect(deviceDetails.current_services.db).to.have.lengthOf(1); // Should have an empty list of gateway downloads expect(deviceDetails.current_gateway_downloads).to.have.lengthOf(0); }; describe('balena.models.application.getWithDeviceServiceDetails()', function () { it("should retrieve the application and it's devices along with service details", function () { return balena.models.application .getWithDeviceServiceDetails(this.application.id) .then((applicationDetails) => { return itShouldBeAnApplicationWithDeviceServiceDetails.call( this, applicationDetails, true, ); }); }); }); describe('when expanding the release of the image installs', function () { const extraServiceDetailOptions = { $expand: { owns__device: { $expand: { image_install: { $expand: { is_provided_by__release: { $select: toWritable(['id', 'commit'] as const), }, }, }, }, }, }, } as const; describe('balena.models.application.getWithDeviceServiceDetails()', () => it("should retrieve the application and it's devices along with service details including their commit", function () { return balena.models.application .getWithDeviceServiceDetails( this.application.id, extraServiceDetailOptions, ) .then((applicationDetails) => { return itShouldBeAnApplicationWithDeviceServiceDetails.call( this, applicationDetails, true, ); }); })); }); }); describe('helpers', () => describe('balena.models.application.getDashboardUrl()', function () { it('should return the respective DashboardUrl when an application id is provided', function () { const dashboardUrl = sdkOpts.apiUrl!.replace(/api/, 'dashboard'); return expect(balena.models.application.getDashboardUrl(1)).to.equal( `${dashboardUrl}/apps/1`, ); }); it('should throw when an application id is not a number', () => expect(() => // @ts-expect-error balena.models.application.getDashboardUrl('my-app'), ).to.throw()); it('should throw when an application id is not provided', () => expect(() => // @ts-expect-error balena.models.application.getDashboardUrl(), ).to.throw()); })); describe('given public apps', function () { let publicApp: Pick<BalenaSdk.Application, 'id' | 'app_name' | 'slug'>; before(async function () { const [app] = await balena.models.application.getAll({ $top: 1, $select: ['id', 'app_name', 'slug', 'uuid', 'is_public'], $filter: { is_public: true }, }); expect(app).to.have.property('is_public', true); publicApp = app; }); const $it = function (description, fn) { it(description, function () { if (!publicApp) { this.skip(); return; } return fn.call(this); }); }; describe('when logged in', function () { parallel('balena.models.application.get()', function () { applicationRetrievalFields.forEach((prop) => $it( `should be able to get the public application by ${prop}`, async function () { const app = await balena.models.application.get(publicApp[prop]); expect(app.id).to.equal(publicApp.id); }, ), ); }); parallel( 'balena.models.application.get() [directly_accessible]', function () { applicationRetrievalFields.forEach((prop) => $it( `should not return the public application by ${prop}`, async function () { const promise = balena.models.application.get( publicApp[prop], {}, 'directly_accessible', ); await expect(promise).to.eventually.be.rejectedWith( `Application not found: ${publicApp[prop]}`, ); }, ), ); }, ); parallel( 'balena.models.application.getDirectlyAccessible()', function () { applicationRetrievalFields.forEach((prop) => $it( `should not return the public application by ${prop}`, async function () { const promise = balena.models.application.getDirectlyAccessible( publicApp[prop], ); await expect(promise).to.eventually.be.rejectedWith( `Application not found: ${publicApp[prop]}`, ); }, ), ); }, ); describe('balena.models.application.getAppByName()', function () { $it(`should be able to get the public application`, async function () { const app = await balena.models.application.getAppByName( publicApp.app_name, ); expect(app.id).to.equal(publicApp.id); }); }); describe('balena.models.application.getAppByName() [directly_accessible]', function () { $it(`should not return the public application`, async function () { const promise = balena.models.application.getAppByName( publicApp.app_name, {}, 'directly_accessible', ); await expect(promise).to.eventually.be.rejectedWith( `Application not found: ${publicApp.app_name}`, ); }); }); describe('balena.models.application.getAll()', function () { $it('should be able to get the public application', async function () { const apps = await balena.models.application.getAll({ $filter: { id: publicApp.id }, }); expect(apps).to.have.length(1); expect(apps[0].id).to.equal(publicApp.id); }); }); describe('balena.models.application.getAll() [directly_accessible]', function () { $it('should be able to get the public application', async function () { const apps = await balena.models.application.getAll( { $filter: { id: publicApp.id } }, 'directly_accessible', ); expect(apps).to.have.length(0); }); }); describe('balena.models.application.getAllDirectlyAccessible()', function () { $it( 'should not be able to get the public application', async function () { const apps = await balena.models.application.getAllDirectlyAccessible({ $filter: { id: publicApp.id }, }); expect(apps).to.have.length(0); }, ); }); }); describe('when not being logged in', function () { before(() => balena.auth.logout()); describe('arbitrary pinejs queries', () => $it( 'should be able to retrieve the available public apps', function () { return balena.pine .get({ resource: 'application', options: { $select: ['id', 'app_name', 'slug', 'uuid', 'is_public'], }, }) .then(function (apps) { expect(apps.length).to.be.gte(1); const appIds = apps.map((app) => app.id); expect(appIds.includes(publicApp.id)).to.be.true; apps.forEach(function (app) { expect(app).to.have.property('id').that.is.a('number'); expect(app).to.have.property('app_name').that.is.a('string'); expect(app).to.have.property('slug').that.is.a('string'); expect(app).to.have.property('uuid').that.is.a('string'); expect(app).to.have.property('is_public', true); }); }); }, )); parallel('balena.models.application.get()', function () { applicationRetrievalFields.forEach((prop) => { $it( `should be able to get a public application by ${prop}`, function () { return balena.models.application .get(publicApp[prop]) .then(function (app) { expect(app).to.have.property('id').that.is.a('number'); expect(app).to.have.property('app_name').that.is.a('string'); expect(app).to.have.property('slug').that.is.a('string'); expect(app).to.have.property('uuid').that.is.a('string'); expect(app).to.have.property('is_public', true); }); }, ); }); }); }); }); });
the_stack
import { MAGNETIC_MODULE_TYPE, TEMPERATURE_MODULE_TYPE, THERMOCYCLER_MODULE_TYPE, MAGNETIC_MODULE_V1, MAGNETIC_MODULE_V2, } from '@opentrons/shared-data' import { orderedStepIds, labwareInvariantProperties, moduleInvariantProperties, presavedStepForm, savedStepForms, unsavedForm, batchEditFormChanges, SavedStepFormsActions, UnsavedFormActions, RootState, PresavedStepFormState, PresavedStepFormAction, } from '../reducers' import { _getPipetteEntitiesRootState, _getLabwareEntitiesRootState, _getInitialDeckSetupRootState, } from '../selectors' import { handleFormChange } from '../../steplist/formLevel/handleFormChange' import { moveDeckItem } from '../../labware-ingred/actions' import { INITIAL_DECK_SETUP_STEP_ID, SPAN7_8_10_11_SLOT, PAUSE_UNTIL_TEMP, } from '../../constants' import { FormData, PROFILE_CYCLE, PROFILE_STEP, StepType, } from '../../form-types' import { PRESAVED_STEP_ID } from '../../steplist/types' import { createPresavedStepForm } from '../utils/createPresavedStepForm' import { createInitialProfileCycle } from '../utils/createInitialProfileItems' import { getLabwareIsCompatible } from '../../utils/labwareModuleCompatibility' import { uuid } from '../../utils' import { DeckSlot } from '../../types' import { DeleteContainerAction } from '../../labware-ingred/actions/actions' import { DeletePipettesAction, SubstituteStepFormPipettesAction, } from '../actions/pipettes' import { CreateModuleAction, DeleteModuleAction, EditModuleAction, } from '../actions/modules' import { ModuleEntity } from '@opentrons/step-generation' import { AddStepAction, DuplicateMultipleStepsAction, DuplicateStepAction, SelectMultipleStepsAction, SelectStepAction, SelectTerminalItemAction, } from '../../ui/steps' import { ChangeBatchEditFieldAction, SaveStepFormsMultiAction, ResetBatchEditFieldChangesAction, } from '../actions' import { AddProfileCycleAction, AddProfileStepAction, ChangeFormInputAction, DeleteMultipleStepsAction, DeleteProfileCycleAction, DeleteProfileStepAction, EditProfileCycleAction, EditProfileStepAction, } from '../../steplist/actions' jest.mock('../../labware-defs/utils') jest.mock('../selectors') jest.mock('../../steplist/formLevel/handleFormChange') jest.mock('../utils/createPresavedStepForm') jest.mock('../../utils/labwareModuleCompatibility') jest.mock('../../utils') const mockUuid = uuid as jest.MockedFunction<typeof uuid> const mockCreatePresavedStepForm = createPresavedStepForm as jest.MockedFunction< typeof createPresavedStepForm > const handleFormChangeMock = handleFormChange as jest.MockedFunction< typeof handleFormChange > const getLabwareIsCompatibleMock = getLabwareIsCompatible as jest.MockedFunction< typeof getLabwareIsCompatible > const mock_getPipetteEntitiesRootState = _getPipetteEntitiesRootState as jest.MockedFunction< typeof _getPipetteEntitiesRootState > const mock_getLabwareEntitiesRootState = _getLabwareEntitiesRootState as jest.MockedFunction< typeof _getLabwareEntitiesRootState > const mock_getInitialDeckSetupRootState = _getInitialDeckSetupRootState as jest.MockedFunction< typeof _getInitialDeckSetupRootState > afterEach(() => { jest.clearAllMocks() }) describe('orderedStepIds reducer', () => { it('should add a saved step when that step is new', () => { const state = ['99'] const action = { type: 'SAVE_STEP_FORM', payload: { id: '123', stepType: 'moveLiquid', }, } expect(orderedStepIds(state, action)).toEqual(['99', '123']) }) it('should not update when an existing step is saved', () => { const state = ['99', '123', '11'] const action = { type: 'SAVE_STEP_FORM', payload: { id: '123', stepType: 'moveLiquid', }, } expect(orderedStepIds(state, action)).toBe(state) }) it('should remove a saved step when the step is deleted', () => { const state = ['1', '2', '3'] const action = { type: 'DELETE_STEP', payload: '2', } expect(orderedStepIds(state, action)).toEqual(['1', '3']) }) it('should remove multiple saved steps when multiple steps are deleted', () => { const state = ['1', '2', '3'] const action = { type: 'DELETE_MULTIPLE_STEPS', payload: ['1', '3'], } expect(orderedStepIds(state, action)).toEqual(['2']) }) it('should add a new step when the step is duplicated', () => { const state = ['1', '2', '3'] const action = { type: 'DUPLICATE_STEP', payload: { stepId: '1', duplicateStepId: 'dup_1', }, } expect(orderedStepIds(state, action)).toEqual(['1', 'dup_1', '2', '3']) }) describe('duplicating multiple steps', () => { const steps = [ { stepId: 'id1', duplicateStepId: 'dup_1', }, { stepId: 'id2', duplicateStepId: 'dup_2', }, { stepId: 'id3', duplicateStepId: 'dup_3', }, ] const testCases = [ { name: 'should add new steps at the 0th index', state: ['1', '2', '3'], action: { type: 'DUPLICATE_MULTIPLE_STEPS', payload: { steps: [...steps], indexToInsert: 0, }, }, expected: ['dup_1', 'dup_2', 'dup_3', '1', '2', '3'], }, { name: 'should add new steps at the 2nd index', state: ['1', '2', '3'], action: { type: 'DUPLICATE_MULTIPLE_STEPS', payload: { steps: [...steps], indexToInsert: 2, }, }, expected: ['1', '2', 'dup_1', 'dup_2', 'dup_3', '3'], }, { name: 'should add new steps at the last index', state: ['1', '2', '3'], action: { type: 'DUPLICATE_MULTIPLE_STEPS', payload: { steps: [...steps], indexToInsert: 3, }, }, expected: ['1', '2', '3', 'dup_1', 'dup_2', 'dup_3'], }, ] testCases.forEach(({ name, state, action, expected }) => { it(name, () => { expect(orderedStepIds(state, action)).toEqual(expected) }) }) }) describe('reorder steps', () => { const state = ['1', '2', '3', '4'] const testCases = [ { label: '+1 to first', payload: { delta: 1, stepId: '1', }, expected: ['2', '1', '3', '4'], }, { label: '+0 to first: no change', payload: { delta: 0, stepId: '1', }, expected: state, }, { label: '-1 to first: no change', payload: { delta: -1, stepId: '1', }, expected: state, }, { label: '-10 to first: no change', payload: { delta: -10, stepId: '1', }, expected: state, }, { label: '-1 to second', payload: { delta: -1, stepId: '2', }, expected: ['2', '1', '3', '4'], }, { label: '-10 to second', payload: { delta: -10, stepId: '2', }, expected: ['2', '1', '3', '4'], }, { label: '+1 to last: no change', payload: { delta: 1, stepId: '4', }, expected: state, }, { label: '+10 to last: no change', payload: { delta: 10, stepId: '4', }, expected: state, }, ] testCases.forEach(({ label, payload, expected }) => { it(label, () => { const action = { type: 'REORDER_SELECTED_STEP', payload, } expect(orderedStepIds(state, action)).toEqual(expected) }) }) }) }) describe('labwareInvariantProperties reducer', () => { it('replace custom labware def', () => { const prevState = { labwareIdA1: { labwareDefURI: 'foo/a/1', }, labwareIdA2: { labwareDefURI: 'foo/a/1', }, labwareIdB: { labwareDefURI: 'foo/b/1', }, } const result = labwareInvariantProperties(prevState, { type: 'REPLACE_CUSTOM_LABWARE_DEF', payload: { defURIToOverwrite: 'foo/a/1', newDef: { parameters: { loadName: 'a', }, version: 2, namespace: 'foo', }, isOverwriteMismatched: false, }, }) expect(result).toEqual({ // changed labwareIdA1: { labwareDefURI: 'foo/a/2', }, labwareIdA2: { labwareDefURI: 'foo/a/2', }, // unchanged labwareIdB: { labwareDefURI: 'foo/b/1', }, }) }) }) describe('moduleInvariantProperties reducer', () => { let prevState: Record<string, ModuleEntity> const existingModuleId = 'existingModuleId' const newId = 'newModuleId' beforeEach(() => { prevState = { [existingModuleId]: { id: existingModuleId, slot: '1', type: MAGNETIC_MODULE_TYPE, // @ts-expect-error(sa, 2021-6-14): not a valid magnetic module model model: 'someMagModel', }, } }) it('create module', () => { const newModuleData = { id: newId, slot: '3', type: TEMPERATURE_MODULE_TYPE, model: 'someTempModel', } const result = moduleInvariantProperties(prevState, { type: 'CREATE_MODULE', payload: newModuleData, }) expect(result).toEqual({ ...prevState, [newId]: { id: newId, type: newModuleData.type, model: newModuleData.model, }, }) }) it('edit module (change its model)', () => { const newModel = 'someDifferentModel' const result = moduleInvariantProperties(prevState, { type: 'EDIT_MODULE', payload: { id: existingModuleId, model: newModel, }, }) expect(result).toEqual({ [existingModuleId]: { ...prevState.existingModuleId, model: newModel }, }) }) it('delete module', () => { const result = moduleInvariantProperties(prevState, { type: 'DELETE_MODULE', payload: { id: existingModuleId, }, }) expect(result).toEqual({}) }) }) interface MakeDeckSetupStepArgs { labwareLocationUpdate?: Record<string, DeckSlot> pipetteLocationUpdate?: Record<string, DeckSlot> moduleLocationUpdate?: Record<string, DeckSlot> } const makeDeckSetupStep = (args: MakeDeckSetupStepArgs = {}): any => ({ stepType: 'manualIntervention', id: '__INITIAL_DECK_SETUP_STEP__', labwareLocationUpdate: args.labwareLocationUpdate || {}, pipetteLocationUpdate: args.pipetteLocationUpdate || {}, moduleLocationUpdate: args.moduleLocationUpdate || {}, }) const makePrevRootState = (args?: MakeDeckSetupStepArgs): any => ({ savedStepForms: { [INITIAL_DECK_SETUP_STEP_ID]: makeDeckSetupStep(args), }, }) describe('savedStepForms reducer: initial deck setup step', () => { const existingLabwareId = '_existingLabwareId' const otherLabwareId = '_otherLabwareId' const newLabwareId = '_newLabwareId' const moduleId = '_moduleId' const otherModuleId = '_otherModuleId' const labwareOnModuleId = '_labwareOnModuleId' describe('create (or duplicate) new labware', () => { const newSlot = '8' const testCases: Array<{ testName: string action: SavedStepFormsActions }> = [ { testName: 'duplicate labware', action: { type: 'DUPLICATE_LABWARE', payload: { templateLabwareId: existingLabwareId, duplicateLabwareId: newLabwareId, duplicateLabwareNickname: 'new labware nickname', slot: newSlot, }, }, }, { testName: `create labware in slot ${newSlot}`, action: { type: 'CREATE_CONTAINER', payload: { slot: newSlot, labwareDefURI: 'fixtures/foo/1', id: newLabwareId, }, }, }, ] testCases.forEach(({ testName, action }) => { it(testName, () => { const prevRootState = makePrevRootState({ labwareLocationUpdate: { [existingLabwareId]: '1', }, }) const result = savedStepForms(prevRootState, action) expect( result[INITIAL_DECK_SETUP_STEP_ID].labwareLocationUpdate ).toEqual({ [existingLabwareId]: '1', [newLabwareId]: newSlot, }) }) }) }) describe('move deck item', () => { const testCases: Array<{ testName: string sourceSlot: DeckSlot destSlot: DeckSlot makeStateArgs: MakeDeckSetupStepArgs deckSetup?: any labwareIsCompatible?: boolean expectedLabwareLocations?: Record<string, any> expectedModuleLocations?: Record<string, any> }> = [ { testName: 'move labware to empty slot -> simple move', sourceSlot: '1', destSlot: '3', makeStateArgs: { labwareLocationUpdate: { [existingLabwareId]: '1', }, }, expectedLabwareLocations: { [existingLabwareId]: '3', }, }, { testName: 'move labware to slot with labware -> swap labware', sourceSlot: '1', destSlot: '3', makeStateArgs: { labwareLocationUpdate: { [existingLabwareId]: '1', [otherLabwareId]: '3', }, }, expectedLabwareLocations: { [existingLabwareId]: '3', [otherLabwareId]: '1', }, }, { testName: 'move labware empty module -> labware added to module', sourceSlot: '1', destSlot: moduleId, makeStateArgs: { labwareLocationUpdate: { [existingLabwareId]: '1', }, moduleLocationUpdate: { [moduleId]: '3', }, }, expectedLabwareLocations: { [existingLabwareId]: moduleId, }, expectedModuleLocations: { [moduleId]: '3', }, }, { // NOTE: if labware is incompatible, it's up to the UI to block this. testName: 'move labware to slot with occupied module -> swap labware, module stays', sourceSlot: '1', destSlot: moduleId, makeStateArgs: { labwareLocationUpdate: { [existingLabwareId]: '1', [labwareOnModuleId]: moduleId, }, moduleLocationUpdate: { [moduleId]: '3', }, }, expectedLabwareLocations: { [existingLabwareId]: moduleId, [labwareOnModuleId]: '1', }, expectedModuleLocations: { [moduleId]: '3', }, }, { testName: 'move empty module to empty slot -> simple move', sourceSlot: '1', destSlot: '3', makeStateArgs: { labwareLocationUpdate: {}, moduleLocationUpdate: { [moduleId]: '1', }, }, expectedLabwareLocations: {}, expectedModuleLocations: { [moduleId]: '3', }, }, { testName: 'move empty module to slot with incompatible labware -> swap slots, do not add labware to module', sourceSlot: '1', destSlot: '3', makeStateArgs: { labwareLocationUpdate: { [existingLabwareId]: '3', }, moduleLocationUpdate: { [moduleId]: '1', }, }, deckSetup: { labware: { [existingLabwareId]: { id: existingLabwareId, slot: '3', def: { foo: 'fake def', }, }, }, pipettes: {}, modules: { [moduleId]: { id: moduleId, type: MAGNETIC_MODULE_TYPE, model: MAGNETIC_MODULE_V2, slot: '1', }, }, }, labwareIsCompatible: false, expectedLabwareLocations: { [existingLabwareId]: '1', }, expectedModuleLocations: { [moduleId]: '3', }, }, { testName: 'move empty module to slot with compatible labware -> put module under labware', sourceSlot: '1', destSlot: '3', makeStateArgs: { labwareLocationUpdate: { [existingLabwareId]: '3', }, moduleLocationUpdate: { [moduleId]: '1', }, }, deckSetup: { labware: { [existingLabwareId]: { id: existingLabwareId, slot: '3', def: { foo: 'fake def', }, }, }, pipettes: {}, modules: { [moduleId]: { id: moduleId, type: MAGNETIC_MODULE_TYPE, model: MAGNETIC_MODULE_V2, slot: '1', }, }, }, labwareIsCompatible: true, expectedLabwareLocations: { [existingLabwareId]: moduleId, }, expectedModuleLocations: { [moduleId]: '3', }, }, { testName: 'move occupied module to slot with labware -> swap slots, do not change labware on module (even if compatible)', sourceSlot: '1', destSlot: '3', makeStateArgs: { labwareLocationUpdate: { [existingLabwareId]: '3', [labwareOnModuleId]: moduleId, }, moduleLocationUpdate: { [moduleId]: '1', }, }, deckSetup: { labware: { [existingLabwareId]: { id: existingLabwareId, slot: '3', def: { foo: 'fake def', }, }, [labwareOnModuleId]: { id: labwareOnModuleId, slot: moduleId, def: { foo: 'fake def', }, }, }, pipettes: {}, modules: { [moduleId]: { id: moduleId, type: MAGNETIC_MODULE_TYPE, model: MAGNETIC_MODULE_V2, slot: '1', }, }, }, labwareIsCompatible: true, expectedLabwareLocations: { [existingLabwareId]: '1', [labwareOnModuleId]: moduleId, }, expectedModuleLocations: { [moduleId]: '3', }, }, { testName: 'move labware off of module to empty slot', sourceSlot: moduleId, destSlot: '3', makeStateArgs: { labwareLocationUpdate: { [labwareOnModuleId]: moduleId, }, moduleLocationUpdate: { [moduleId]: '1', }, }, expectedLabwareLocations: { [labwareOnModuleId]: '3', }, expectedModuleLocations: { [moduleId]: '1', }, }, { testName: 'move empty module to occupied module -> swap, keep pairings', sourceSlot: '1', destSlot: '3', makeStateArgs: { labwareLocationUpdate: { [labwareOnModuleId]: moduleId, }, moduleLocationUpdate: { [moduleId]: '1', [otherModuleId]: '3', }, }, expectedLabwareLocations: { [labwareOnModuleId]: moduleId, }, expectedModuleLocations: { [moduleId]: '3', [otherModuleId]: '1', }, }, { testName: 'empty module to empty module -> swap', sourceSlot: '1', destSlot: '3', makeStateArgs: { labwareLocationUpdate: {}, moduleLocationUpdate: { [moduleId]: '1', [otherModuleId]: '3', }, }, expectedLabwareLocations: {}, expectedModuleLocations: { [moduleId]: '3', [otherModuleId]: '1', }, }, { testName: 'occupied module to occupied module -> swap, keep pairings', sourceSlot: '1', destSlot: '3', makeStateArgs: { labwareLocationUpdate: { [labwareOnModuleId]: moduleId, [otherLabwareId]: otherModuleId, }, moduleLocationUpdate: { [moduleId]: '1', [otherModuleId]: '3', }, }, expectedLabwareLocations: { [labwareOnModuleId]: moduleId, [otherLabwareId]: otherModuleId, }, expectedModuleLocations: { [moduleId]: '3', [otherModuleId]: '1', }, }, { testName: 'occupied module to empty module -> swap, keep pairings', sourceSlot: '1', destSlot: '3', makeStateArgs: { labwareLocationUpdate: { [labwareOnModuleId]: moduleId, }, moduleLocationUpdate: { [moduleId]: '1', [otherModuleId]: '3', }, }, expectedLabwareLocations: { [labwareOnModuleId]: moduleId, }, expectedModuleLocations: { [moduleId]: '3', [otherModuleId]: '1', }, }, ] testCases.forEach( ({ testName, sourceSlot, destSlot, makeStateArgs, deckSetup, labwareIsCompatible, expectedLabwareLocations, expectedModuleLocations, }) => { it(testName, () => { mock_getInitialDeckSetupRootState.mockReturnValue(deckSetup) getLabwareIsCompatibleMock.mockReturnValue( labwareIsCompatible as boolean ) const prevRootState = makePrevRootState(makeStateArgs) const action = moveDeckItem(sourceSlot, destSlot) const result = savedStepForms(prevRootState, action) if (expectedLabwareLocations != null) { expect( result[INITIAL_DECK_SETUP_STEP_ID].labwareLocationUpdate ).toEqual(expectedLabwareLocations) } if (expectedModuleLocations != null) { expect( result[INITIAL_DECK_SETUP_STEP_ID].moduleLocationUpdate ).toEqual(expectedModuleLocations) } }) } ) }) it('delete labware -> removes labware from initial deck setup step', () => { const labwareToDeleteId = '__labwareToDelete' const prevRootState = makePrevRootState({ labwareLocationUpdate: { [existingLabwareId]: '1', [labwareToDeleteId]: '2', }, }) const action: DeleteContainerAction = { type: 'DELETE_CONTAINER', payload: { labwareId: labwareToDeleteId, }, } const result = savedStepForms(prevRootState, action) expect(result[INITIAL_DECK_SETUP_STEP_ID].labwareLocationUpdate).toEqual({ [existingLabwareId]: '1', }) }) it('delete pipettes -> removes pipette(s) from initial deck setup step', () => { const leftPipetteId = '__leftPipette' const rightPipetteId = '__rightPipette' const prevRootState = makePrevRootState({ pipetteLocationUpdate: { [leftPipetteId]: 'left', [rightPipetteId]: 'right', }, }) const testCases = [ { pipettesToDelete: [leftPipetteId], expected: { [rightPipetteId]: 'right', }, }, { pipettesToDelete: [leftPipetteId, rightPipetteId], expected: {}, }, ] testCases.forEach(({ pipettesToDelete, expected }) => { const action: DeletePipettesAction = { type: 'DELETE_PIPETTES', payload: pipettesToDelete, } const result = savedStepForms(prevRootState, action) expect(result[INITIAL_DECK_SETUP_STEP_ID].pipetteLocationUpdate).toEqual( expected ) }) }) describe('create module', () => { describe('NO existing steps', () => { const destSlot = '3' const testCases = [ { testName: 'create module in empty deck slot (labware in unrelated slot unaffected)', makeStateArgs: { labwareLocationUpdate: { [existingLabwareId]: '6', }, }, expectedLabwareLocations: { [existingLabwareId]: '6', }, expectedModuleLocations: { [moduleId]: destSlot, }, }, { testName: 'create module in deck slot occupied with labware -> move that labware to the new module', makeStateArgs: { labwareLocationUpdate: { [existingLabwareId]: destSlot, }, }, expectedLabwareLocations: { [existingLabwareId]: moduleId, }, expectedModuleLocations: { [moduleId]: destSlot, }, }, ] testCases.forEach( ({ testName, makeStateArgs, expectedLabwareLocations, expectedModuleLocations, }) => { it(testName, () => { const action: CreateModuleAction = { type: 'CREATE_MODULE', payload: { id: moduleId, slot: destSlot, type: TEMPERATURE_MODULE_TYPE, // @ts-expect-error(sa, 2021-6-14): not a valid module model model: 'someTempModel', }, } const prevRootState = makePrevRootState(makeStateArgs) const result = savedStepForms(prevRootState, action) expect( result[INITIAL_DECK_SETUP_STEP_ID].labwareLocationUpdate ).toEqual(expectedLabwareLocations) expect( result[INITIAL_DECK_SETUP_STEP_ID].moduleLocationUpdate ).toEqual(expectedModuleLocations) }) } ) }) describe('existing steps', () => { let prevRootStateWithMagAndTCSteps: any beforeEach(() => { prevRootStateWithMagAndTCSteps = { savedStepForms: { ...makePrevRootState().savedStepForms, ...{ mag_step_form_id: { stepType: 'magnet', moduleId: 'magdeckId', }, }, ...{ TC_step_form_id: { stepType: 'thermocycler', moduleId: 'TCId', }, }, }, } }) const magneticStepCases: Array<{ testName: string action: SavedStepFormsActions expectedModuleId: string }> = [ { testName: 'create mag mod -> override mag step module id', // @ts-expect-error(sa, 2021-6-14): not a valid module model action: { type: 'CREATE_MODULE', payload: { id: 'newMagdeckId', slot: '1', type: MAGNETIC_MODULE_TYPE, model: 'someMagModel', }, }, expectedModuleId: 'newMagdeckId', }, { testName: 'create temp mod -> DO NOT override mag step module id', // @ts-expect-error(sa, 2021-6-14): not a valid module model action: { type: 'CREATE_MODULE', payload: { id: 'tempdeckId', slot: '1', type: TEMPERATURE_MODULE_TYPE, model: 'someTempModel', }, }, expectedModuleId: 'magdeckId', }, { testName: 'create TC -> DO NOT override mag step module id', // @ts-expect-error(sa, 2021-6-14): not a valid module model action: { type: 'CREATE_MODULE', payload: { id: 'ThermocyclerId', slot: '1', type: THERMOCYCLER_MODULE_TYPE, model: 'someThermoModel', }, }, expectedModuleId: 'magdeckId', }, ] const TCStepCases: Array<{ testName: string action: SavedStepFormsActions expectedModuleId: string }> = [ { testName: 'create TC -> override TC step module id', // @ts-expect-error(sa, 2021-6-14): not a valid module model action: { type: 'CREATE_MODULE', payload: { id: 'NewTCId', slot: SPAN7_8_10_11_SLOT, type: THERMOCYCLER_MODULE_TYPE, model: 'someTCModel', }, }, expectedModuleId: 'NewTCId', }, { testName: 'create temp mod -> DO NOT override TC step module id', // @ts-expect-error(sa, 2021-6-14): not a valid module model action: { type: 'CREATE_MODULE', payload: { id: 'tempdeckId', slot: '1', type: TEMPERATURE_MODULE_TYPE, model: 'someTempModel', }, }, expectedModuleId: 'TCId', }, { testName: 'create magnetic mod -> DO NOT override TC step module id', // @ts-expect-error(sa, 2021-6-14): not a valid module model action: { type: 'CREATE_MODULE', payload: { id: 'newMagdeckId', slot: '1', type: MAGNETIC_MODULE_TYPE, model: 'someMagModel', }, }, expectedModuleId: 'TCId', }, ] magneticStepCases.forEach(({ testName, action, expectedModuleId }) => { it(testName, () => { const result = savedStepForms(prevRootStateWithMagAndTCSteps, action) // @ts-expect-error(sa, 2021-6-14): null check if (action.payload.type) expect(result.mag_step_form_id.moduleId).toBe(expectedModuleId) }) }) TCStepCases.forEach(({ testName, action, expectedModuleId }) => { it(testName, () => { const result = savedStepForms(prevRootStateWithMagAndTCSteps, action) // @ts-expect-error(sa, 2021-6-14): null check if (action.payload.type) expect(result.TC_step_form_id.moduleId).toBe(expectedModuleId) }) }) }) }) describe('delete module -> removes module from initial deck setup step', () => { const testCases: Array<{ testName: string makeStateArgs: MakeDeckSetupStepArgs expectedLabwareLocations?: Record<string, any> expectedModuleLocations?: Record<string, any> }> = [ { testName: 'delete unoccupied module', makeStateArgs: { moduleLocationUpdate: { [moduleId]: '1', [otherModuleId]: '2', }, }, expectedLabwareLocations: {}, expectedModuleLocations: { [otherModuleId]: '2', }, }, { testName: 'delete occupied module -> labware goes into its slot', makeStateArgs: { labwareLocationUpdate: { [labwareOnModuleId]: moduleId, }, moduleLocationUpdate: { [moduleId]: '3', }, }, expectedLabwareLocations: { [labwareOnModuleId]: '3', }, expectedModuleLocations: {}, }, { testName: 'delete occupied module in span7_8_10_11 slot -> labware goes into slot 7', makeStateArgs: { labwareLocationUpdate: { [labwareOnModuleId]: moduleId, }, moduleLocationUpdate: { [moduleId]: SPAN7_8_10_11_SLOT, }, }, expectedLabwareLocations: { [labwareOnModuleId]: '7', }, expectedModuleLocations: {}, }, ] testCases.forEach( ({ testName, makeStateArgs, expectedLabwareLocations, expectedModuleLocations, }) => { it(testName, () => { const action: DeleteModuleAction = { type: 'DELETE_MODULE', payload: { id: moduleId, }, } const prevRootState = makePrevRootState(makeStateArgs) const result = savedStepForms(prevRootState, action) expect( result[INITIAL_DECK_SETUP_STEP_ID].moduleLocationUpdate ).toEqual(expectedModuleLocations) expect( result[INITIAL_DECK_SETUP_STEP_ID].labwareLocationUpdate ).toEqual(expectedLabwareLocations) }) } ) }) describe('delete module -> removes references to module from step forms', () => { const stepId = '_stepId' const action: DeleteModuleAction = { type: 'DELETE_MODULE', payload: { id: moduleId, }, } const getPrevRootStateWithStep = ( step: FormData // @ts-expect-error(sa, 2021-6-14): make this actually return RootState (add the rest of the state properties) ): RootState => ({ savedStepForms: { [INITIAL_DECK_SETUP_STEP_ID]: makeDeckSetupStep({ moduleLocationUpdate: { [moduleId]: '1', [otherModuleId]: '2', }, }), [stepId]: step, }, }) const testCases: Array<{ testName: string; step: FormData }> = [ { testName: 'pause -> wait until temperature step', step: { id: stepId, stepType: 'pause', stepName: 'pause until 4C', stepDetails: 'some details', pauseAction: PAUSE_UNTIL_TEMP, pauseHour: null, pauseMinute: null, pauseSecond: null, pauseMessage: '', moduleId, pauseTemperature: '4', }, }, { testName: 'set temperature step', step: { id: stepId, stepType: 'temperature', stepName: 'temperature to 4', stepDetails: 'some details', moduleId, setTemperature: 'true', targetTemperature: '4', }, }, { testName: 'magnet step', step: { id: stepId, stepType: 'magnet', stepName: 'engage magnet', stepDetails: 'some details', moduleId, magnetAction: 'engage', engageHeight: '4', }, }, ] testCases.forEach(({ testName, step }) => { it(testName, () => { const result = savedStepForms(getPrevRootStateWithStep(step), action) expect(result[stepId]).toEqual({ ...step, moduleId: null }) }) }) }) describe('deleting steps', () => { let savedStepFormsState: { [id: string]: { stepType: StepType id: string } } beforeEach(() => { savedStepFormsState = { [INITIAL_DECK_SETUP_STEP_ID]: makeDeckSetupStep({ moduleLocationUpdate: { [moduleId]: '1', [otherModuleId]: '2', }, }), // @ts-expect-error(sa, 2021-6-14): add stepTypes to these test fixtures id1: { id: 'id1', }, // @ts-expect-error(sa, 2021-6-14): add stepTypes to these test fixtures id2: { id: 'id2', }, // @ts-expect-error(sa, 2021-6-14): add stepTypes to these test fixtures id3: { id: 'id3', }, } }) it('should delete one step', () => { const action = { type: 'DELETE_STEP', payload: 'id1', } const expectedState = { ...savedStepFormsState } delete expectedState.id1 expect( savedStepForms( // @ts-expect-error(sa, 2021-6-14): add missing keys to savedStepFormsState { savedStepForms: savedStepFormsState, }, action ) ).toEqual(expectedState) }) it('should delete multiple steps', () => { const action = { type: 'DELETE_MULTIPLE_STEPS', payload: ['id1', 'id2'], } const expectedState = { ...savedStepFormsState } delete expectedState.id1 delete expectedState.id2 expect( savedStepForms( // @ts-expect-error(sa, 2021-6-14): add missing keys to savedStepFormsState { savedStepForms: savedStepFormsState, }, action ) ).toEqual(expectedState) }) }) describe('duplicating steps', () => { let savedStepFormsState: { [id: string]: { stepType: StepType id: string } } beforeEach(() => { savedStepFormsState = { [INITIAL_DECK_SETUP_STEP_ID]: makeDeckSetupStep({ moduleLocationUpdate: { [moduleId]: '1', [otherModuleId]: '2', }, }), // @ts-expect-error(sa, 2021-6-14): add stepTypes to these test fixtures id1: { id: 'id1', }, // @ts-expect-error(sa, 2021-6-14): add stepTypes to these test fixtures id2: { id: 'id2', }, // @ts-expect-error(sa, 2021-6-14): add stepTypes to these test fixtures id3: { id: 'id3', }, } }) it('should duplicate one step', () => { const action: DuplicateStepAction = { type: 'DUPLICATE_STEP', payload: { stepId: 'id1', duplicateStepId: 'dup_1', }, } const expectedState = { ...savedStepFormsState, dup_1: { id: 'dup_1', }, } expect( savedStepForms( // @ts-expect-error(sa, 2021-6-14): add missing keys to savedStepFormsState { savedStepForms: savedStepFormsState, }, action ) ).toEqual(expectedState) }) it('should duplicate multiple steps', () => { const action = { type: 'DUPLICATE_MULTIPLE_STEPS', payload: { steps: [ { stepId: 'id1', duplicateStepId: 'dup_1', }, { stepId: 'id2', duplicateStepId: 'dup_2', }, { stepId: 'id3', duplicateStepId: 'dup_3', }, ], indexToInsert: 0, // this does not matter for this reducer }, } const expectedState = { ...savedStepFormsState, dup_1: { id: 'dup_1', }, dup_2: { id: 'dup_2', }, dup_3: { id: 'dup_3', }, } expect( savedStepForms( // @ts-expect-error(sa, 2021-6-14): add missing keys to savedStepFormsState { savedStepForms: savedStepFormsState, }, action ) ).toEqual(expectedState) }) }) describe('EDIT_MODULE', () => { it('should set engageHeight to null for all Magnet > Engage steps when a magnet module has its model changed, unless height matches default', () => { mock_getInitialDeckSetupRootState.mockReturnValue({ labware: { magPlateId: { id: 'magPlateId', slot: 'magModuleId', def: { // @ts-expect-error(sa, 2021-6-14): add missing parameters to fixture parameters: { magneticModuleEngageHeight: 12, }, }, }, }, pipettes: {}, modules: { // @ts-expect-error(sa, 2021-6-14): add missing parameters to fixture magModuleId: { id: 'magModuleId', type: MAGNETIC_MODULE_TYPE, model: MAGNETIC_MODULE_V1, slot: '1', }, }, }) const action: EditModuleAction = { type: 'EDIT_MODULE', payload: { id: 'magModuleId', model: 'magneticModuleV2', }, } const prevRootState: RootState = { savedStepForms: { // @ts-expect-error(sa, 2021-6-14): add id to fixture magnetEngageStepId: { stepType: 'magnet', magnetAction: 'engage', moduleId: 'magModuleId', engageHeight: '24', // = 12 * 2 b/c we're going V1 -> V2 }, // @ts-expect-error(sa, 2021-6-14): add id to fixture magnetDisengageStepId: { stepType: 'magnet', magnetAction: 'disengage', engageHeight: null, moduleId: 'magModuleId', }, // @ts-expect-error(sa, 2021-6-14): add id to fixture nonDefaultMagnetEngageStepId: { stepType: 'magnet', magnetAction: 'engage', moduleId: 'magModuleId', engageHeight: '8', }, // @ts-expect-error(sa, 2021-6-14): add id to fixture unrelatedMagnetEngageStepId: { stepType: 'magnet', magnetAction: 'engage', moduleId: 'otherMagModuleId', // not 'magModuleId' engageHeight: '8', }, }, } const result = savedStepForms(prevRootState, action) expect(result).toEqual({ magnetEngageStepId: { stepType: 'magnet', magnetAction: 'engage', engageHeight: '12', // V2 units default moduleId: 'magModuleId', }, magnetDisengageStepId: prevRootState.savedStepForms.magnetDisengageStepId, nonDefaultMagnetEngageStepId: { stepType: 'magnet', magnetAction: 'engage', moduleId: 'magModuleId', engageHeight: null, }, // module id not matching, unchanged unrelatedMagnetEngageStepId: prevRootState.savedStepForms.unrelatedMagnetEngageStepId, }) }) }) describe('saving multiple steps', () => { it('should apply the form patch to all of the step ids', () => { const prevState: RootState = { savedStepForms: { // @ts-expect-error(sa, 2021-6-14): add id to fixture some_transfer_step_id: { stepType: 'moveLiquid', blowout_location: 'someLocation', dispense_mix_checkbox: true, dispense_mix_volume: '10', }, // @ts-expect-error(sa, 2021-6-14): add id to fixture another_transfer_step_id: { stepType: 'moveLiquid', blowout_location: 'anotherLocation', dispense_mix_checkbox: true, dispense_mix_volume: '20', }, }, } const action: SaveStepFormsMultiAction = { type: 'SAVE_STEP_FORMS_MULTI', payload: { editedFields: { blowout_location: 'newLocation', dispense_mix_volume: '30', }, stepIds: ['some_transfer_step_id', 'another_transfer_step_id'], }, } const expectedSavedStepFormState = { some_transfer_step_id: { stepType: 'moveLiquid', blowout_location: 'newLocation', dispense_mix_checkbox: true, dispense_mix_volume: '30', }, another_transfer_step_id: { stepType: 'moveLiquid', blowout_location: 'newLocation', dispense_mix_checkbox: true, dispense_mix_volume: '30', }, } expect(savedStepForms(prevState, action)).toEqual( expectedSavedStepFormState ) }) }) }) describe('unsavedForm reducer', () => { const someState: any = { unsavedForm: 'foo', } it('should take on the payload of the POPULATE_FORM action', () => { const payload = { formStuff: 'example', } const result = unsavedForm(someState, { type: 'POPULATE_FORM', // @ts-expect-error(sa, 2021-6-14): not a valid FormData payload payload, }) expect(result).toEqual(payload) }) it('should use handleFormChange to update the state with CHANGE_FORM_INPUT action', () => { const rootState: any = { unsavedForm: { existingField: 123, }, } const action: ChangeFormInputAction = { type: 'CHANGE_FORM_INPUT', payload: { update: { someField: -1, }, }, } handleFormChangeMock.mockReturnValue({ someField: 42, }) mock_getPipetteEntitiesRootState.mockReturnValue( // @ts-expect-error(sa, 2021-6-14): not a valid PipetteEntities Type 'pipetteEntitiesPlaceholder' ) mock_getLabwareEntitiesRootState.mockReturnValue( // @ts-expect-error(sa, 2021-6-14): not a valid LabwareEntities Type 'labwareEntitiesPlaceholder' ) const result = unsavedForm(rootState, action) expect(mock_getPipetteEntitiesRootState.mock.calls).toEqual([[rootState]]) expect(mock_getLabwareEntitiesRootState.mock.calls).toEqual([[rootState]]) expect(handleFormChangeMock.mock.calls).toEqual([ [ action.payload.update, rootState.unsavedForm, 'pipetteEntitiesPlaceholder', 'labwareEntitiesPlaceholder', ], ]) expect(result).toEqual({ existingField: 123, someField: 42, }) }) it("should switch out pipettes via handleFormChange in response to SUBSTITUTE_STEP_FORM_PIPETTES if the unsaved form's ID is in range", () => { const action: SubstituteStepFormPipettesAction = { type: 'SUBSTITUTE_STEP_FORM_PIPETTES', payload: { substitutionMap: { oldPipetteId: 'newPipetteId', }, startStepId: '3', endStepId: '5', }, } const rootState: RootState = { orderedStepIds: ['1', '3', '4', '5', '6'], // @ts-expect-error(sa, 2021-6-14): add stepType to fixture unsavedForm: { pipette: 'oldPipetteId', id: '4', otherField: 'blah', }, } handleFormChangeMock.mockReturnValue({ pipette: 'newPipetteId', }) mock_getPipetteEntitiesRootState.mockReturnValue( // @ts-expect-error(sa, 2021-6-14): not a valid PipetteEntities Type 'pipetteEntitiesPlaceholder' ) mock_getLabwareEntitiesRootState.mockReturnValue( // @ts-expect-error(sa, 2021-6-14): not a valid LabwareEntities Type 'labwareEntitiesPlaceholder' ) const result = unsavedForm(rootState, action) expect(mock_getPipetteEntitiesRootState.mock.calls).toEqual([[rootState]]) expect(mock_getLabwareEntitiesRootState.mock.calls).toEqual([[rootState]]) expect(handleFormChangeMock.mock.calls).toEqual([ [ { pipette: 'newPipetteId', }, rootState.unsavedForm, 'pipetteEntitiesPlaceholder', 'labwareEntitiesPlaceholder', ], ]) expect(result).toEqual({ id: '4', pipette: 'newPipetteId', otherField: 'blah', }) }) const actionTypes: Array<UnsavedFormActions['type']> = [ 'CANCEL_STEP_FORM', 'CREATE_MODULE', 'DELETE_MODULE', 'DELETE_STEP', 'DELETE_MULTIPLE_STEPS', 'EDIT_MODULE', 'SAVE_STEP_FORM', 'SELECT_TERMINAL_ITEM', 'SELECT_MULTIPLE_STEPS', ] actionTypes.forEach(actionType => { it(`should clear the unsaved form when any ${actionType} action is dispatched`, () => { const result = unsavedForm(someState, { type: actionType, } as any) expect(result).toEqual(null) }) }) it('should return the result createPresavedStepForm util upon ADD_STEP action', () => { mockCreatePresavedStepForm.mockReturnValue( // @ts-expect-error(sa, 2021-6-14): not a valid FormData Type 'createPresavedStepFormMockResult' ) // @ts-expect-error(sa, 2021-6-14): not valid InitialDeckSetup state mock_getInitialDeckSetupRootState.mockReturnValue('initalDeckSetupValue') const stateMock: RootState = { // @ts-expect-error(sa, 2021-6-14): not valid savedStepForms state savedStepForms: 'savedStepFormsValue', // @ts-expect-error(sa, 2021-6-14): not valid orderedStepIds state orderedStepIds: 'orderedStepIdsValue', } const result = unsavedForm(stateMock, { type: 'ADD_STEP', payload: { id: 'stepId123', stepType: 'moveLiquid', }, meta: { // @ts-expect-error(sa, 2021-6-14): not valid Timeline state robotStateTimeline: 'robotStateTimelineValue', }, }) expect(result).toEqual('createPresavedStepFormMockResult') expect(mockCreatePresavedStepForm.mock.calls).toEqual([ [ { stepId: 'stepId123', stepType: 'moveLiquid', pipetteEntities: 'pipetteEntitiesPlaceholder', labwareEntities: 'labwareEntitiesPlaceholder', savedStepForms: 'savedStepFormsValue', orderedStepIds: 'orderedStepIdsValue', initialDeckSetup: 'initalDeckSetupValue', robotStateTimeline: 'robotStateTimelineValue', }, ], ]) }) it('should add a profile cycle item upon ADD_PROFILE_CYCLE action', () => { const action: AddProfileCycleAction = { type: 'ADD_PROFILE_CYCLE', payload: null, } const id = 'newCycleId' const profileStepId = 'newProfileStepId' // NOTE: because we're using uuid() to create multiple different ids, // this test is sensitive to the order that uuid is called in and // assumes it's first for cycle id, then next for profile step id mockUuid.mockReturnValueOnce(id) mockUuid.mockReturnValueOnce(profileStepId) const state: RootState = { // @ts-expect-error(sa, 2021-6-14): add id to fixture unsavedForm: { stepType: 'thermocycler', orderedProfileItems: [], profileItemsById: {}, }, } const result = unsavedForm(state, action) expect(result).toEqual({ stepType: 'thermocycler', orderedProfileItems: [id], profileItemsById: { [id]: createInitialProfileCycle(id, profileStepId), }, }) }) it('should add a profile step item to the specified cycle upon ADD_PROFILE_STEP action with cycleId payload', () => { const cycleId = 'someCycleId' const stepId = 'newStepId' const action: AddProfileStepAction = { type: 'ADD_PROFILE_STEP', payload: { cycleId, }, } mockUuid.mockReturnValue(stepId) const state: RootState = { // @ts-expect-error(sa, 2021-6-14): add id to fixture unsavedForm: { stepType: 'thermocycler', orderedProfileItems: [cycleId], profileItemsById: { [cycleId]: { type: PROFILE_CYCLE, id: cycleId, repetitions: '1', steps: [], }, }, }, } const result = unsavedForm(state, action) expect(result).toEqual({ stepType: 'thermocycler', orderedProfileItems: [cycleId], profileItemsById: { [cycleId]: { // @ts-expect-error(sa, 2021-6-14): possibly null ...state.unsavedForm.profileItemsById[cycleId], steps: [ { id: stepId, type: PROFILE_STEP, title: '', temperature: '', durationMinutes: '', durationSeconds: '', }, ], }, }, }) }) it('should remove a profile step item on DELETE_PROFILE_STEP', () => { const id = 'stepItemId' const action: DeleteProfileStepAction = { type: 'DELETE_PROFILE_STEP', payload: { id, }, } const state: RootState = { // @ts-expect-error(sa, 2021-6-14): add missing id to fixture unsavedForm: { stepType: 'thermocycler', orderedProfileItems: [id], profileItemsById: { [id]: { type: PROFILE_STEP, id, title: '', temperature: '', durationMinutes: '', durationSeconds: '', }, }, }, } const result = unsavedForm(state, action) expect(result).toEqual({ stepType: 'thermocycler', orderedProfileItems: [], profileItemsById: {}, }) }) it('should remove a step item inside a cycle on DELETE_PROFILE_STEP', () => { const stepId = 'stepItemId' const cycleId = 'cycleId' const action: DeleteProfileStepAction = { type: 'DELETE_PROFILE_STEP', payload: { id: stepId, }, } const state: RootState = { // @ts-expect-error(sa, 2021-6-14): add id to fixture unsavedForm: { stepType: 'thermocycler', orderedProfileItems: [cycleId], profileItemsById: { [cycleId]: { type: PROFILE_CYCLE, id: cycleId, steps: [ { type: PROFILE_STEP, id: stepId, title: '', temperature: '', durationMinutes: '', durationSeconds: '', }, ], repetitions: '1', }, }, }, } const result = unsavedForm(state, action) expect(result).toEqual({ stepType: 'thermocycler', orderedProfileItems: [cycleId], profileItemsById: { [cycleId]: { type: PROFILE_CYCLE, id: cycleId, steps: [], repetitions: '1', }, }, }) }) it('should do nothing on DELETE_PROFILE_STEP when the id is a cycle', () => { const id = 'cycleItemId' const action: DeleteProfileStepAction = { type: 'DELETE_PROFILE_STEP', payload: { id, }, } const state: RootState = { // @ts-expect-error(sa, 2021-6-14): add id to fixture unsavedForm: { stepType: 'thermocycler', orderedProfileItems: [id], profileItemsById: { [id]: { type: PROFILE_CYCLE, id, steps: [], repetitions: '1', }, }, }, } const result = unsavedForm(state, action) expect(result).toEqual(state.unsavedForm) }) it('should delete cycle on DELETE_PROFILE_CYCLE', () => { const id = 'cycleItemId' const action: DeleteProfileCycleAction = { type: 'DELETE_PROFILE_CYCLE', payload: { id, }, } const state: RootState = { // @ts-expect-error(sa, 2021-6-14): add id to fixture unsavedForm: { stepType: 'thermocycler', orderedProfileItems: [id], profileItemsById: { [id]: { type: PROFILE_CYCLE, id, steps: [], repetitions: '1', }, }, }, } const result = unsavedForm(state, action) expect(result).toEqual({ stepType: 'thermocycler', orderedProfileItems: [], profileItemsById: {}, }) }) it('should edit a profile step on the top level with EDIT_PROFILE_STEP', () => { const stepId = 'profileStepId' const action: EditProfileStepAction = { type: 'EDIT_PROFILE_STEP', payload: { id: stepId, fields: { title: 'x', }, }, } const state: RootState = { // @ts-expect-error(sa, 2021-6-14): add id to fixture unsavedForm: { stepType: 'thermocycler', orderedProfileItems: [stepId], profileItemsById: { [stepId]: { type: PROFILE_STEP, id: stepId, title: '', temperature: '', durationMinutes: '', durationSeconds: '', }, }, }, } const result = unsavedForm(state, action) expect(result).toEqual({ stepType: 'thermocycler', orderedProfileItems: [stepId], profileItemsById: { [stepId]: { type: PROFILE_STEP, id: stepId, title: 'x', temperature: '', durationMinutes: '', durationSeconds: '', }, }, }) }) it('should edit a profile step that is inside a cycle with EDIT_PROFILE_STEP', () => { const cycleId = 'cycleId' const stepId = 'profileStepId' const action: EditProfileStepAction = { type: 'EDIT_PROFILE_STEP', payload: { id: stepId, fields: { title: 'x', }, }, } const state: RootState = { // @ts-expect-error(sa, 2021-6-14): add id to fixture unsavedForm: { stepType: 'thermocycler', orderedProfileItems: [cycleId], profileItemsById: { [cycleId]: { type: PROFILE_CYCLE, id: cycleId, steps: [ { type: PROFILE_STEP, id: stepId, title: '', temperature: '', durationMinutes: '', durationSeconds: '', }, ], repetitions: '1', }, }, }, } const result = unsavedForm(state, action) expect(result).toEqual({ stepType: 'thermocycler', orderedProfileItems: [cycleId], profileItemsById: { [cycleId]: { type: PROFILE_CYCLE, id: cycleId, steps: [ { type: PROFILE_STEP, id: stepId, title: 'x', temperature: '', durationMinutes: '', durationSeconds: '', }, ], repetitions: '1', }, }, }) }) it('should edit a profile cycle on EDIT_PROFILE_CYCLE', () => { const cycleId = 'cycleId' const action: EditProfileCycleAction = { type: 'EDIT_PROFILE_CYCLE', payload: { id: cycleId, fields: { repetitions: '5', }, }, } const state: RootState = { // @ts-expect-error(sa, 2021-6-14): add id to fixture unsavedForm: { stepType: 'thermocycler', orderedProfileItems: [cycleId], profileItemsById: { [cycleId]: { type: PROFILE_CYCLE, id: cycleId, steps: [], repetitions: '1', }, }, }, } const result = unsavedForm(state, action) expect(result).toEqual({ stepType: 'thermocycler', orderedProfileItems: [cycleId], profileItemsById: { [cycleId]: { type: PROFILE_CYCLE, id: cycleId, steps: [], repetitions: '5', }, }, }) }) }) describe('presavedStepForm reducer', () => { it('should populate when a new step is added', () => { const addStepAction: AddStepAction = { type: 'ADD_STEP', payload: { id: 'someId', // @ts-expect-error(sa, 2021-6-14): transfer is not a valid stepType, change to moveLiquid stepType: 'transfer', }, } const result = presavedStepForm(null, addStepAction) expect(result).toEqual({ stepType: 'transfer', }) }) it('should not update when the PRESAVED_STEP_ID terminal item is selected', () => { const prevState: PresavedStepFormState = { // @ts-expect-error(sa, 2021-6-14): transfer is not a valid stepType, change to moveLiquid stepType: 'transfer', } const action: SelectTerminalItemAction = { type: 'SELECT_TERMINAL_ITEM', payload: PRESAVED_STEP_ID, } expect(presavedStepForm(prevState, action)).toBe(prevState) }) it('should clear when a different terminal item is selected', () => { const prevState: PresavedStepFormState = { // @ts-expect-error(sa, 2021-6-14): transfer is not a valid stepType, change to moveLiquid stepType: 'transfer', } const action: SelectTerminalItemAction = { type: 'SELECT_TERMINAL_ITEM', // @ts-expect-error(sa, 2021-6-14): transfer is not a valid TerminalItemId payload: 'otherId', } expect(presavedStepForm(prevState, action)).toEqual(null) }) const clearingActions: Array<PresavedStepFormAction['type']> = [ 'CANCEL_STEP_FORM', 'DELETE_STEP', 'DELETE_MULTIPLE_STEPS', 'SAVE_STEP_FORM', 'SELECT_STEP', 'SELECT_MULTIPLE_STEPS', ] clearingActions.forEach(actionType => { it(`should clear upon ${actionType}`, () => { const prevState: PresavedStepFormState = { id: 'someId', // @ts-expect-error(sa, 2021-6-14): transfer is not a valid stepType, change to moveLiquid stepType: 'transfer', } expect( // @ts-expect-error(sa, 2021-6-14): missing payload presavedStepForm(prevState, { type: actionType, }) ).toEqual(null) }) }) }) describe('batchEditFormChanges reducer', () => { it('should add the new fields into empty state on CHANGE_BATCH_EDIT_FIELD', () => { const state = {} const action: ChangeBatchEditFieldAction = { type: 'CHANGE_BATCH_EDIT_FIELD', payload: { someFieldName: 'someFieldValue', }, } expect(batchEditFormChanges(state, { ...action })).toEqual({ someFieldName: 'someFieldValue', }) }) it('should add the new fields into existing state on CHANGE_BATCH_EDIT_FIELD', () => { const state = { someFieldName: 'someFieldValue', } const action: ChangeBatchEditFieldAction = { type: 'CHANGE_BATCH_EDIT_FIELD', payload: { anotherFieldName: 'anotherFieldValue', }, } expect(batchEditFormChanges(state, { ...action })).toEqual({ someFieldName: 'someFieldValue', anotherFieldName: 'anotherFieldValue', }) }) it('should reset state on RESET_BATCH_EDIT_FIELD_CHANGES', () => { const state = { someFieldName: 'someFieldValue', } const action: ResetBatchEditFieldChangesAction = { type: 'RESET_BATCH_EDIT_FIELD_CHANGES', } expect(batchEditFormChanges(state, { ...action })).toEqual({}) }) it('should reset state on SAVE_STEP_FORMS_MULTI', () => { const state = { someFieldName: 'someFieldValue', } // @ts-expect-error(sa, 2021-6-14): missing payload const action: SaveStepFormsMultiAction = { type: 'SAVE_STEP_FORMS_MULTI', } expect(batchEditFormChanges(state, { ...action })).toEqual({}) }) it('should reset state on SELECT_STEP', () => { const state = { someFieldName: 'someFieldValue', } // @ts-expect-error(sa, 2021-6-14): missing payload const action: SelectStepAction = { type: 'SELECT_STEP', } expect(batchEditFormChanges(state, { ...action })).toEqual({}) }) it('should reset state on SELECT_MULTIPLE_STEPS', () => { const state = { someFieldName: 'someFieldValue', } // @ts-expect-error(sa, 2021-6-14): missing payload const action: SelectMultipleStepsAction = { type: 'SELECT_MULTIPLE_STEPS', } expect(batchEditFormChanges(state, { ...action })).toEqual({}) }) it('should reset state on DUPLICATE_MULTIPLE_STEPS', () => { const state = { someFieldName: 'someFieldValue', } // @ts-expect-error(sa, 2021-6-14): missing payload const action: DuplicateMultipleStepsAction = { type: 'DUPLICATE_MULTIPLE_STEPS', } expect(batchEditFormChanges(state, { ...action })).toEqual({}) }) it('should reset state on DELETE_MULTIPLE_STEPS', () => { const state = { someFieldName: 'someFieldValue', } // @ts-expect-error(sa, 2021-6-14): missing payload const action: DeleteMultipleStepsAction = { type: 'DELETE_MULTIPLE_STEPS', } expect(batchEditFormChanges(state, { ...action })).toEqual({}) }) })
the_stack
import { SpreadsheetHelper } from '../util/spreadsheethelper.spec'; import { defaultData } from '../util/datasource.spec'; import { Spreadsheet, dialog as dlg, DialogBeforeOpenEventArgs, BeforeSelectEventArgs, getRangeIndexes, getCell, CellModel } from '../../../src/index'; import { SheetModel } from '../../../src/index'; import { ListView, SelectedCollection } from '@syncfusion/ej2-lists'; import { Dialog, Overlay } from '../../../src/spreadsheet/services/index'; describe('Protect sheet ->', () => { const helper: SpreadsheetHelper = new SpreadsheetHelper('spreadsheet'); describe('public method ->', () => { beforeAll((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }] }] }, done); }); afterAll(() => { helper.invoke('destroy'); }); it('', (done: Function) => { helper.invoke('protectSheet', ['Sheet1', {}]); expect(getComputedStyle(helper.getElementFromSpreadsheet('.e-active-cell')).display).toBe('none'); expect(helper.getElements('.e-overlay').length).toBeGreaterThanOrEqual(23); helper.invoke('unprotectSheet', ['Sheet1']); setTimeout(() => { expect(getComputedStyle(helper.getElementFromSpreadsheet('.e-active-cell')).display).toBe('block'); expect(helper.getElements('.e-overlay').length).toBeLessThanOrEqual(5); done(); }); }); }); describe('UI Interaction ->', () => { beforeAll((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }] }] }, done); }); afterAll(() => { helper.invoke('destroy'); }); it('Protect sheet', (done: Function) => { (helper.getElementFromSpreadsheet('.e-tab-header').children[0].children[5] as HTMLElement).click(); helper.click('#' + helper.id + '_protect'); setTimeout(() => { helper.setAnimationToNone('.e-protect-dlg'); helper.click('.e-protect-dlg .e-primary'); expect(helper.getInstance().sheets[0].isProtected).toBeTruthy(); helper.invoke('selectRange', ['D4']); expect(helper.getInstance().sheets[0].selectedRange).toBe('D4:D4'); // helper.editInUI('Test'); // This case need to be fixed setTimeout(() => { // expect(helper.getElementFromSpreadsheet('#' + helper.id + '_protect').textContent).toBe('Unprotect Sheet'); // Check this now // expect(helper.getElementFromSpreadsheet('.e-editAlert-dlg')).not.toBeNull(); // This case need to be fixed // helper.setAnimationToNone('.e-editAlert-dlg'); // helper.click('.e-editAlert-dlg .e-primary'); // expect(helper.invoke('getCell', [2, 3]).textContent).toBe('20'); done(); }); }); }); it('Delete in locked cell', (done: Function) => { helper.triggerKeyNativeEvent(46); setTimeout(() => { helper.setAnimationToNone('.e-editAlert-dlg'); expect(helper.getElement('.e-editAlert-dlg')).not.toBeNull(); helper.click('.e-editAlert-dlg .e-footer-content button:nth-child(1)'); expect(JSON.stringify(helper.getInstance().sheets[0].rows[0].cells[0])).toBe('{"value":"Item Name"}'); done(); }); }); it('Delete in unlocked cell', (done: Function) => { helper.invoke('lockCells', ['B2', false]); helper.invoke('selectRange', ['B2']); helper.triggerKeyNativeEvent(46); setTimeout(() => { expect(helper.getElement('.e-editAlert-dlg')).toBeNull(); expect(JSON.stringify(helper.getInstance().sheets[0].rows[1].cells[1])).toBe('{"format":"mm-dd-yyyy","isLocked":false}'); done(); }); }); it('Set unlocked to whole column', (done: Function) => { helper.invoke('selectRange', ['D1:D100']); helper.invoke('lockCells', [null, false]); expect(helper.getInstance().sheets[0].columns[3].isLocked).toBeFalsy(); helper.triggerKeyNativeEvent(46); setTimeout(() => { expect(helper.getElement('.e-editAlert-dlg')).toBeNull(); done(); }); }); it('Protect workbook', (done: Function) => { helper.click('#' + helper.id + '_protectworkbook'); setTimeout(() => { //helper.setAnimationToNone('.e-protectworkbook-dlg'); (helper.getElementFromSpreadsheet('.e-protectworkbook-dlg input') as HTMLInputElement).value = 'T1@/a'; (helper.getElements('.e-protectworkbook-dlg input')[1] as HTMLInputElement).value = 'T1@/a'; helper.click('.e-protectworkbook-dlg .e-primary'); // This case need to be fixed. setTimeout(()=>{ done(); }); }); }); it('Un protect sheet', (done: Function) => { helper.click('#' + helper.id + '_protect'); expect(helper.getInstance().sheets[0].isProtected).toBeFalsy(); done(); }); }); describe('CR-Issues ->', () => { describe('I275297 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: [{ 'Employee ID': '2963633', 'Employee Name': 'Kylie Phettis', 'Gender': 'Female', 'Department': 'Marketing', 'Date of Joining': '03/18/2011', 'Salary': '$26038.56', 'City': 'Huangzhai' }] }], selectedRange: 'E2:E2' }], created: (): void => { const spreadsheet: Spreadsheet = helper.getInstance(); spreadsheet.cellFormat({ fontWeight: 'bold', textAlign: 'center', verticalAlign: 'middle' }, 'A1:F1'); spreadsheet.cellFormat({ fontWeight: 'bold' }, 'E31:F31'); spreadsheet.cellFormat({ textAlign: 'right' }, 'E31'); spreadsheet.numberFormat('$#,##0.00', 'F2:F31'); spreadsheet.protectSheet( 'Sheet1', { selectCells: true, formatCells: false, formatRows: false, formatColumns: false, insertLink: false }); } }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('Unable to lock a cell without protecting the sheet ~ from 275269', (done: Function) => { let cell: HTMLElement = helper.invoke('getCell', [1, 4]); helper.triggerMouseAction('dblclick', { x: cell.getBoundingClientRect().left + 2, y: cell.getBoundingClientRect().top + 2 }, null, cell); setTimeout((): void => { let dialog: HTMLElement = helper.getElement('.e-editAlert-dlg'); expect(!!dialog).toBeTruthy(); expect(dialog.classList.contains('e-popup-open')).toBeTruthy(); const editor: HTMLElement = helper.getElement('#' + helper.id + '_edit'); expect(editor.style.display).toBe(''); const spreadsheet: Spreadsheet = helper.getInstance(); (spreadsheet.serviceLocator.getService(dlg) as Dialog).hide(); setTimeout((): void => { helper.invoke('lockCells', ['A2:AZ100', false]); cell = helper.invoke('getCell', [1, 4]); helper.triggerMouseAction('dblclick', { x: cell.getBoundingClientRect().left + 10, y: cell.getBoundingClientRect().top + 5 }, null, cell); setTimeout((): void => { expect(editor.style.display).toBe('block'); helper.invoke('lockCells', ['E2:E4', true]); helper.invoke('endEdit', []); helper.triggerMouseAction('dblclick', { x: cell.getBoundingClientRect().left + 2, y: cell.getBoundingClientRect().top + 2 }, null, cell); setTimeout((): void => { dialog = helper.getElement('.e-editAlert-dlg'); expect(!!dialog).toBeTruthy(); expect(dialog.classList.contains('e-popup-open')).toBeTruthy(); expect(dialog.querySelector('.e-dlg-content').textContent).toBe( "The cell you're trying to change is protected. To make change, unprotect the sheet."); expect(editor.style.display).toBe(''); (spreadsheet.serviceLocator.getService(dlg) as Dialog).hide(); done(); }); }); }); }); }); }); describe('I321143, F161227, FB23867 ->', () => { beforeAll((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ rows: [{ cells: [{ value: 'spreadsheet' }] }], isProtected: true }] }, done); }); afterAll(() => { helper.invoke('destroy'); }); it('Deleting values from locked cells and warning dialog', (done: Function) => { helper.getElement().focus(); helper.triggerKeyEvent('keydown', 46, null, null, null, helper.invoke('getCell', [0, 0])); const spreadsheet: Spreadsheet = helper.getInstance(); expect(spreadsheet.sheets[0].rows[0].cells[0].value).toBe('spreadsheet'); setTimeout((): void => { helper.setAnimationToNone('.e-editAlert-dlg'); expect(helper.getElement('.e-editAlert-dlg')).not.toBeNull(); helper.click('.e-editAlert-dlg .e-footer-content button:nth-child(1)'); done(); }); }); it('Cancel button in hyperlink popup is not working in protected sheet', (done: Function) => { helper.invoke('protectSheet', ['Sheet1', { selectCells: true, insertLink: true }]); let td: HTMLTableCellElement = helper.invoke('getCell', [0, 0]); const coords: DOMRect = <DOMRect>td.getBoundingClientRect(); helper.triggerMouseAction('contextmenu', { x: coords.x, y: coords.y }, null, td); setTimeout(() => { helper.click('#' + helper.id + '_contextmenu li:nth-child(9)'); setTimeout(() => { helper.triggerKeyEvent('keydown', 65, null, null, null, helper.getElements('.e-hyperlink-dlg .e-webpage input')[1]); setTimeout(() => { expect(helper.getElement('.e-editAlert-dlg')).toBeNull(); helper.setAnimationToNone('.e-hyperlink-dlg'); helper.click('.e-hyperlink-dlg .e-footer-content button:nth-child(2)'); expect(helper.getElement('.e-hyperlink-dlg')).toBeNull(); done(); }); }); }); }); }); describe('I282699 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ rows: [{ cells: [{ value: 'spreadsheet' }] }], isProtected: true }] }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('Prevent protected sheet dialog box', (done: Function) => { helper.getElement().focus(); const spreadsheet: Spreadsheet = helper.getInstance(); spreadsheet.dialogBeforeOpen = (args: DialogBeforeOpenEventArgs): void => { args.cancel = true; }; spreadsheet.dataBind(); helper.triggerKeyEvent('keydown', 46, null, null, null, helper.invoke('getCell', [0, 0])); expect(spreadsheet.sheets[0].rows[0].cells[0].value).toBe('spreadsheet'); setTimeout((): void => { expect(helper.getElement('#' + helper.id + ' .e-editAlert-dlg')).toBeNull(); done(); }); }); }); describe('F161227, I264291 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({}, done); }); afterEach(() => { helper.invoke('destroy'); }); // it('Aggregate after open from json throw error issue and cell cannot be copy/paste after using openFromJson', (done: Function) => { // const json: object = { "Workbook": { "sheets": [{ "rows": [{ "cells": [{ "value": "20" }, { "value": "10" }] }, { "cells": // [{ "value": "5" }, { "value": "7" }] }], "selectedRange": "A1:B2" }] } }; // const spreadsheet: Spreadsheet = helper.getInstance(); // spreadsheet.openFromJson({ file: json }); // setTimeout((): void => { // helper.getElement('#' + helper.id + '_aggregate').click(); // const aggregatePopup: HTMLElement = helper.getElement('#' + helper.id + '_aggregate-popup'); // expect(aggregatePopup.classList).toContain('e-popup-open'); // expect(aggregatePopup.firstElementChild.childElementCount).toBe(5); // expect(aggregatePopup.querySelector('.e-item').textContent).toBe('Count: 4'); // helper.invoke('copy').then((): void => { // helper.invoke('paste', ['C3']); // setTimeout((): void => { // expect(spreadsheet.sheets[0].rows[2].cells[2].value.toString()).toBe('20'); // expect(spreadsheet.sheets[0].rows[3].cells[3].value.toString()).toBe('7'); // done(); // }); // }); // }); // }); }); describe('F161227 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({ allowResizing: false, enableContextMenu: false, allowUndoRedo: false, allowScrolling: false, allowFindAndReplace: false, showRibbon: false, showFormulaBar: false, showSheetTabs: false, allowOpen: false, allowSave: false, allowSorting: false, allowFiltering: false, allowNumberFormatting: false, allowHyperlink: false, allowInsert: false, allowDelete: false, allowDataValidation: false, allowChart: false, allowConditionalFormat: false, height: 1500, sheets: [{ isProtected: true, protectSettings: { selectCells: true, formatCells: false, formatRows: false, insertLink: false, formatColumns: false }, rowCount: 16, rows: [{ cells: [{ image: [{ src: "https://ravennaareachamber.com/wp-content/uploads/2017/03/your-company-lsiting.png", height: 70, width: 100, top: 2, left: 10 }] }, { index: 2, value: 'LOCKED' }, { value: 'LOCKED' }] }, { cells: [{index: 2, value: 'LOCKED' }, { value: 'UNLOCKED' }] }, { cells: [{ value: 'LOCKED' }, { value: 'LOCKED' }, { value: 'LOCKED' }, { value: 'LOCKED' }, { value: 'LOCKED' }] }, { index: 15, cells: [{ value: 'LOCKED' }, { index: 4, value: 'LOCKED' }] }] }], beforeSelect: (args: BeforeSelectEventArgs): void => { const range: number[] = getRangeIndexes(args.range); const sheet: SheetModel = helper.getInstance().getActiveSheet(); const cell: CellModel = getCell(range[0], range[1], sheet); if (sheet.isProtected) args.cancel = true; if (cell && cell.isLocked == false) args.cancel = false; }, created: (): void => { const spreadsheet: Spreadsheet = helper.getInstance(); spreadsheet.merge("D2:E2"); spreadsheet.merge("A1:B3"); spreadsheet.merge("A4:E4"); spreadsheet.lockCells("D1", false); spreadsheet.lockCells("D3", false); spreadsheet.lockCells("A6:E15", false); spreadsheet.lockCells("A17", false); } }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('Preventing delete when a range contains locked cell', (done: Function) => { helper.getElement().focus(); helper.invoke('selectRange', ['A6:D1']) setTimeout((): void => { helper.triggerKeyNativeEvent(46); const spreadsheet: Spreadsheet = helper.getInstance(); expect(spreadsheet.sheets[0].rows[0].cells[0].image).toBeDefined(); expect(spreadsheet.sheets[0].rows[0].cells[2].value).toBe('LOCKED'); expect(spreadsheet.sheets[0].rows[1].cells[3].value).toBe('UNLOCKED'); expect(spreadsheet.sheets[0].rows[2].cells[0].rowSpan).toBe(-2); expect(spreadsheet.sheets[0].rows[2].cells[3].value).toBe('LOCKED'); expect(spreadsheet.sheets[0].rows[2].cells[3].isLocked).toBeFalsy(); (helper.getInstance().serviceLocator.getService('shape') as Overlay).destroy();// Need to remove once destory of overlay service handled in image. done(); }); }); }); describe('EJ2-56489 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ isProtected: true }] }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('To disable some toolbar items for protect sheet and customize the edit alert dialog content', (done: Function) => { helper.getElement().focus(); const spreadsheet: Spreadsheet = helper.getInstance(); const id: string = '#' + helper.id; spreadsheet.dialogBeforeOpen = (args: DialogBeforeOpenEventArgs): void => { if (args.dialogName == "EditAlertDialog") { args.content = "Custom Alert"; } }; const overlayClass: string = "e-overlay"; expect((helper.getElement(id + '_undo') as any).parentElement.classList).toContain(overlayClass); expect((helper.getElement(id + '_redo') as any).parentElement.classList).toContain(overlayClass); expect((helper.getElement(id + '_cut') as any).parentElement.classList).toContain(overlayClass); expect((helper.getElement(id + '_copy') as any).parentElement.classList).toContain(overlayClass); expect((helper.getElement(id + '_bold') as any).parentElement.classList).toContain(overlayClass); expect((helper.getElement(id + '_italic') as any).parentElement.classList).toContain(overlayClass); expect((helper.getElement(id + '_line-through') as any).parentElement.classList).toContain(overlayClass);; expect((helper.getElement(id + '_underline') as any).parentElement.classList).toContain(overlayClass); expect((helper.getElement(id + '_font_color_picker') as any).parentElement.classList).toContain(overlayClass); expect((helper.getElement(id+ '_fill_color_picker') as any).parentElement.classList).toContain(overlayClass); expect((helper.getElement(id + '_borders') as any).parentElement.classList).toContain(overlayClass); expect((helper.getElement(id + '_text_align') as any).parentElement.classList).toContain(overlayClass); expect((helper.getElement(id + '_vertical_align') as any).parentElement.classList).toContain("e-overlay"); expect((helper.getElement(id + '_wrap') as any).parentElement.classList).toContain(overlayClass); (helper.getElement(id).getElementsByClassName('e-toolbar-item')[2] as any).click(); expect((helper.getElement(id + '_hyperlink') as any).parentElement.classList).toContain(overlayClass); expect((helper.getElement(id + '_image') as any).parentElement.classList).toContain(overlayClass); expect((helper.getElement(id + '_chart-btn') as any).parentElement.classList).toContain(overlayClass); (helper.getElement(id).getElementsByClassName('e-toolbar-item')[3] as any).click(); expect((helper.getElement(id + '_insert_function') as any).parentElement.classList).toContain(overlayClass); (helper.getElement(id).getElementsByClassName('e-toolbar-item')[4] as any).click(); expect((helper.getElement(id + '_datavalidation') as any).parentElement.classList).toContain(overlayClass); helper.triggerKeyEvent('keydown', 46, null, null, null, helper.invoke('getCell', [0, 0])); setTimeout((): void => { expect((helper.getElement(id + ' .e-editAlert-dlg' + ' .e-dlg-content') as any).innerText).toBe("Custom Alert"); done(); }); }); }); describe('EJ2-56133 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({ sheets: [] }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('Check first two checkboxs in protect sheet dialog is selected initally', (done: Function) => { helper.getElement().focus(); let listView: ListView; (helper.getElement('#' + helper.id).getElementsByClassName('e-toolbar-item')[4] as any).click(); (helper.getElement('#' + helper.id + '_protect') as any).click(); setTimeout((): void => { listView = helper.getElements('.e-listview')[0].ej2_instances[0]; setTimeout((): void => { const selectedItems: SelectedCollection = listView.getSelectedItems() as SelectedCollection; expect(selectedItems.text.indexOf('Select Locked cells')).toBeGreaterThan(-1); expect(selectedItems.text.indexOf('Select Unlocked Cells')).toBeGreaterThan(-1); done(); }); },1000); }); it('If Select Cells option is selected then Select Unlocked Cells option need to be selected automatically', (done: Function) => { helper.getElement().focus(); (helper.getElement('#' + helper.id).getElementsByClassName('e-toolbar-item')[4] as any).click(); (helper.getElement('#' + helper.id + '_protect') as any).click(); debugger; let lisView: ListView; setTimeout((): void => { lisView = helper.getElements('.e-listview')[0].ej2_instances[0]; lisView.selectItem({ id: '1'}); setTimeout((): void => { const selectedItems: SelectedCollection = lisView.getSelectedItems() as SelectedCollection; expect(selectedItems.text.indexOf('Select Unlocked Cells')).toBeGreaterThan(-1); done(); }); },1000); }); it('If Select Unlocked Cells option is unselected then Select locked Cells option need to be unselected ', (done: Function) => { helper.getElement().focus(); (helper.getElement('#' + helper.id).getElementsByClassName('e-toolbar-item')[4] as any).click(); (helper.getElement('#' + helper.id + '_protect') as any).click(); let lisView: ListView; setTimeout((): void => { lisView = helper.getElements('.e-listview')[0].ej2_instances[0]; lisView.uncheckItem({id: '6'}); setTimeout((): void => { const selectedItems: SelectedCollection = lisView.getSelectedItems() as SelectedCollection; expect(selectedItems.text.indexOf('Select Unlocked Cells')).toEqual(-1); done(); }); },1000); }); it('Selection need to hide while select both locked and unlocked cells options ', (done: Function) => { helper.getElement().focus(); setTimeout((): void => { expect(helper.getElements('.e-protected')[0]).toBeUndefined(); done(); }); }); }); }); });
the_stack
import { API, PasteEvent } from "@editorjs/editorjs"; import { Alignment, ALIGNMENTS, TextAlign, ALIGNMENT_ICONS } from "../utils"; import { HTMLPasteEventDetail } from "@editorjs/editorjs/types/tools/paste-events"; /** * @typedef {object} ParagraphConfig * @property {string} placeholder - placeholder for the empty paragraph * @property {boolean} preserveBlank - Whether or not to keep blank paragraphs when saving editor data` */ interface ParagraphConfig { placeholder: string; preserveBlank: boolean; typography?: Typography; } /** * @typedef {Object} ParagraphData * @description Tool's input and output data format * @property {String} text — Paragraph's content. Can include HTML tags: <a><b><i> */ interface ParagraphData { text: string; textAlign: TextAlign; className?: string; } interface Typography { [key: string]: { label: string; component: string; className: string; }; } interface ParagraphArgs { data: ParagraphData; config: ParagraphConfig; api: any; readOnly: boolean; } class Paragraph { private readonly api: API; private readonly readOnly: boolean; private readonly _CSS: any; // private readonly _settings: any; private _data: ParagraphData; private readonly _element: any; private readonly _placeholder: string; private readonly _preserveBlank: boolean; private readonly alignments: Alignment[]; private readonly settingsButtons: HTMLElement[]; private readonly typography: Typography | null; /** * Render plugin`s main Element and fill it with saved data * * @param {object} params - constructor params * @param {ParagraphData} params.data - previously saved data * @param {ParagraphConfig} params.config - user config for Tool * @param {object} params.api - editor.js api * @param {boolean} readOnly - read only mode flag */ public constructor({ data, config, api, readOnly }: ParagraphArgs) { this.api = api; this.readOnly = readOnly; this.typography = config.typography || null; this._CSS = { block: this.api.styles.block, settingsButton: this.api.styles.settingsButton, settingsButtonActive: this.api.styles.settingsButtonActive, wrapper: "ce-paragraph" }; if (!this.readOnly) { this.onKeyUp = this.onKeyUp.bind(this); } /** * Placeholder for paragraph if it is first Block * @type {string} */ this._placeholder = config.placeholder ? config.placeholder : Paragraph.DEFAULT_PLACEHOLDER; this._data = this.normalizeData(data); this._element = this.drawView(); this._preserveBlank = config.preserveBlank !== undefined ? config.preserveBlank : false; this.settingsButtons = []; this.alignments = ALIGNMENTS; // Call the `data` setter, to properly render the view element. this.data = this._data; } /** * Default placeholder for Paragraph Tool * * @return {string} * @constructor */ public static get DEFAULT_PLACEHOLDER(): string { return ""; } /** * Enable Conversion Toolbar. Paragraph can be converted to/from other tools */ public static get conversionConfig() { return { export: "text", // to convert Paragraph to other block, use 'text' property of saved data import: "text" // to covert other block's exported string to Paragraph, fill 'text' property of tool data }; } /** * Sanitizer rules */ public static get sanitize() { return { text: { br: true } }; } /** * Returns true to notify the core that read-only mode is supported * * @return {boolean} */ public static get isReadOnlySupported(): boolean { return true; } /** * Get current Tools`s data * @returns {ParagraphData} Current data * @private */ public get data(): ParagraphData { const text = this._element.innerHTML; // this._data.text = text; return { ...this._data, text }; } /** * Store data in plugin: * - at the this._data property * - at the HTML * * @param {ParagraphData} data — data to set * @private */ public set data(data: ParagraphData) { this._data = data || ({} as ParagraphData); this._element.innerHTML = this._data.text || ""; /** * Add Alignment class */ this.alignments.forEach(alignment => { if (alignment.name === this._data.textAlign) { this._element.classList.add(`ce-header-text--${alignment.name}`); } else { this._element.classList.remove(`ce-header-text--${alignment.name}`); } }); /** * Add Typography class */ if (this._data.className) { this._element.classList.add(...this._data.className.split(" ")); } } /** * Used by Editor paste handling API. * Provides configuration to handle P tags. * * @returns {{tags: string[]}} */ public static get pasteConfig() { return { tags: ["P"] }; } /** * Icon and title for displaying at the Toolbox * * @return {{icon: string, title: string}} */ public static get toolbox() { return { icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0.2 -0.3 9 11.4" width="12" height="14">\n' + ' <path d="M0 2.77V.92A1 1 0 01.2.28C.35.1.56 0 .83 0h7.66c.28.01.48.1.63.28.14.17.21.38.21.64v1.85c0 .26-.08.48-.23.66-.15.17-.37.26-.66.26-.28 0-.5-.09-.64-.26a1 1 0 01-.21-.66V1.69H5.6v7.58h.5c.25 0 .45.08.6.23.17.16.25.35.25.6s-.08.45-.24.6a.87.87 0 01-.62.22H3.21a.87.87 0 01-.61-.22.78.78 0 01-.24-.6c0-.25.08-.44.24-.6a.85.85 0 01.61-.23h.5V1.7H1.73v1.08c0 .26-.08.48-.23.66-.15.17-.37.26-.66.26-.28 0-.5-.09-.64-.26A1 1 0 010 2.77z"/>\n' + "</svg>", title: "Text" }; } /** * Get current alignment * * @returns {alignment} */ public get currentAlignment(): Alignment { let alignment = this.alignments.find(alignment => alignment.name === this._data.textAlign); if (!alignment) { alignment = { name: TextAlign.START, svg: ALIGNMENT_ICONS.start }; } return alignment; } /** * Check if text content is empty and set empty string to inner html. * We need this because some browsers (e.g. Safari) insert <br> into empty contentEditable elements * * @param {KeyboardEvent} e - key up event */ public onKeyUp(e: KeyboardEvent): void { if (e.code !== "Backspace" && e.code !== "Delete") { return; } const { textContent } = this._element; if (textContent === "") { this._element.innerHTML = ""; } } /** * Create Tool's view * @return {HTMLElement} * @private */ public drawView(): HTMLElement { const div: HTMLDivElement = document.createElement("div"); div.classList.add(this._CSS.wrapper, this._CSS.block); // Add custom className to view. if (this._data.className) { div.classList.add(this._data.className); } div.contentEditable = "false"; div.dataset["placeholder"] = this.api.i18n.t(this._placeholder); if (!this.readOnly) { div.contentEditable = "true"; div.addEventListener("keyup", this.onKeyUp); } return div; } /** * Return Tool's view */ public render(): HTMLDivElement { return this._element; } /** * Create Block's settings block */ public renderSettings(): HTMLElement { const holder: HTMLDivElement = document.createElement("div"); // Add alignment selectors this.alignments.forEach(alignment => { const selectTypeButton: HTMLSpanElement = document.createElement("span"); selectTypeButton.classList.add(this._CSS.settingsButton); /** * Highlight current level button */ if (this.currentAlignment.name === alignment.name) { selectTypeButton.classList.add(this._CSS.settingsButtonActive); } /** * Add SVG icon */ selectTypeButton.innerHTML = alignment.svg; /** * Save alignment to its button */ selectTypeButton.dataset["textAlign"] = alignment.name; /** * Set up click handler */ selectTypeButton.addEventListener("click", () => { this.setAlignment(alignment); }); /** * Append settings button to holder */ holder.appendChild(selectTypeButton); /** * Save settings buttons */ this.settingsButtons.push(selectTypeButton); }); // Add `Typography` selector if (this.typography) { const typographyForParagraph = Object.values(this.typography).filter( item => item.component === "p" ); const selectTypeButton = document.createElement("SELECT") as HTMLSelectElement; // Add editor's default input style selectTypeButton.classList.add(this.api.styles.input); // Add typography options typographyForParagraph.forEach(item => { const option = new Option(item.label, item.className); selectTypeButton.appendChild(option); }); // Add "onclick" handler selectTypeButton.onclick = event => { const { value } = event.target as HTMLSelectElement; this.setTypographyClass(value); }; /** * Append settings button to holder */ holder.appendChild(selectTypeButton); /** * Save settings buttons */ this.settingsButtons.push(selectTypeButton); } return holder; } /** * Method that specified how to merge two Text blocks. * Called by Editor.js by backspace at the beginning of the Block * @param {ParagraphData} data * @public */ public merge(data: ParagraphData): void { this.data = { ...this.data, text: this.data.text + data.text }; } /** * Validate Paragraph block data: * - check for emptiness * * @param {ParagraphData} savedData — data received after saving * @returns {boolean} false if saved data is not correct, otherwise true * @public */ public validate(savedData: ParagraphData): boolean { return !(savedData.text.trim() === "" && !this._preserveBlank); } /** * Extract Tool's data from the view * @param {HTMLDivElement} toolsContent - Paragraph tools rendered view * @returns {ParagraphData} - saved data * @public */ public save(toolsContent: HTMLElement) { return { text: toolsContent.innerHTML, textAlign: this.getTextAlign(toolsContent.className), className: this.data.className }; } /** * Extract textAlign from className * * @param {string} className - heading element className * @returns {TextAlign} textAlign */ public getTextAlign(className: string): TextAlign { let textAlign = TextAlign.START; // Match className with alignment this.alignments.forEach(alignment => { if (className.includes(`ce-header-text--${alignment.name}`)) { textAlign = alignment.name; } }); return textAlign; } /** * On paste callback fired from Editor. * * @param {PasteEvent} event - event with pasted data */ public onPaste(event: PasteEvent): void { const detail = event.detail as HTMLPasteEventDetail; this.data = { ...this.data, text: detail.data.innerHTML }; } /** * Callback for Block's settings buttons * * @param {number} alignment - level to set */ public setAlignment(alignment: Alignment): void { this.data = { textAlign: alignment.name, text: this.data.text }; /** * Highlight button by selected level */ this.settingsButtons.forEach(button => { button.classList.toggle( this._CSS.settingsButtonActive, button.dataset["textAlign"] === alignment.name ); }); } /** * Callback for Block's settings buttons * * @param {string} className - name of typography class */ public setTypographyClass(className: string): void { this.data = { textAlign: this.data.textAlign, text: this.data.text, className: className }; } /** * Normalize input data * * @param {HeaderData} data - saved data to process * * @returns {HeaderData} * @private */ public normalizeData(data?: Partial<ParagraphData>): ParagraphData { const newData: Partial<ParagraphData> = {}; if (typeof data !== "object") { data = {}; } newData.text = data.text || ""; newData.textAlign = data.textAlign || TextAlign.START; newData.className = data.className || ""; return newData as ParagraphData; } } export default Paragraph;
the_stack
import { InjectionMode, IStyleSheetConfig, Stylesheet } from './Stylesheet'; describe('Stylesheet', () => { let _stylesheet: Stylesheet; const resetStylesheetInstanceSetup = () => { (window as Window & { __stylesheet__?: Stylesheet }).__stylesheet__ = undefined; }; const cacheClassNameSetup = (stylesheet: Stylesheet) => { const className = stylesheet.getClassName(); const key = 'kobzol'; const args = [{ background: 'red' }]; const rules = ['a { background: red };']; stylesheet.cacheClassName(className, key, args, rules); return { args, className, key, rules, stylesheet, }; }; beforeEach(() => { resetStylesheetInstanceSetup(); _stylesheet = Stylesheet.getInstance(); // We need to set InjectionMode to none as we are running headless tests and have no element to inject into. _stylesheet.setConfig({ injectionMode: InjectionMode.none }); }); describe('test util', () => { it('resetStylesheetInstanceSetup works', () => { const instance = Stylesheet.getInstance(); expect(instance).toBe(_stylesheet); resetStylesheetInstanceSetup(); const newInstance = Stylesheet.getInstance(); expect(newInstance).not.toBe(_stylesheet); }); it('cacheClassNameSetup works', () => { const setupReturn = cacheClassNameSetup(_stylesheet); const classNameCache = _stylesheet.getClassNameCache(); expect(setupReturn).toEqual({ args: [{ background: 'red' }], className: 'css-0', key: 'kobzol', rules: ['a { background: red };'], stylesheet: _stylesheet, }); expect(classNameCache).toEqual({ [setupReturn.key]: setupReturn.className, }); }); }); describe('config', () => { it('can override the default prefix', () => { _stylesheet.setConfig({ defaultPrefix: 'myCss' }); const className = _stylesheet.getClassName(); expect(className).toEqual('myCss-0'); }); it('can provide className namespace', () => { _stylesheet.setConfig({ namespace: 'kobzol' }); const className = _stylesheet.getClassName(); expect(className).toEqual('kobzol-css-0'); }); }); describe('public API', () => { describe('getInstance', () => { it('returns same instance of Stylesheet', () => { const instance = Stylesheet.getInstance(); expect(instance).toBe(_stylesheet); }); it('returns a new instance on mismatched global', () => { // We need to modify internals in order to mock this behaviour. (_stylesheet as any)._lastStyleElement = { ownerDocument: {} }; const newInstance = Stylesheet.getInstance(); expect(newInstance).not.toBe(_stylesheet); }); }); describe('setConfig', () => { it('accepts IStyleSheetConfig and returns void', () => { const config: IStyleSheetConfig = { defaultPrefix: 'myCss', namespace: 'kobzol', }; const returnVal = _stylesheet.setConfig(config); expect(returnVal).toBe(undefined); }); }); describe('reset', () => { it('fully resets stylesheet', () => { _stylesheet.getClassName(); _stylesheet.insertRule('a { background: red };'); _stylesheet.reset(); const classNameCache = _stylesheet.getClassNameCache(); const rules = _stylesheet.getRules(); const className = _stylesheet.getClassName(); expect(classNameCache).toEqual({}); expect(rules).toEqual(''); // Check for counter reset. expect(className).toEqual('css-0'); }); it('does not reset preserved rules', () => { _stylesheet.insertRule('a { background: red };', true); _stylesheet.reset(); const rules = _stylesheet.getRules(true); expect(rules).toEqual('a { background: red };'); }); }); describe('resetKeys', () => { it('resets keys of cached classNames', () => { cacheClassNameSetup(_stylesheet); _stylesheet.resetKeys(); const classNameCache = _stylesheet.getClassNameCache(); expect(classNameCache).toEqual({}); }); it('does not call an onReset() callback', () => { const onResetFn = jest.fn(); _stylesheet.onReset(onResetFn); _stylesheet.resetKeys(); expect(onResetFn).toHaveBeenCalledTimes(0); }); }); describe('onReset', () => { it('gets called with callbacks when reset() is called', () => { const onResetFn = jest.fn(); _stylesheet.onReset(onResetFn); _stylesheet.reset(); expect(onResetFn).toHaveBeenCalledTimes(1); }); it('provides a way to unregister a callback', () => { const onResetFn1 = jest.fn(); const onResetFn2 = jest.fn(); const unregister1 = _stylesheet.onReset(onResetFn1); _stylesheet.onReset(onResetFn2); _stylesheet.reset(); expect(onResetFn1).toHaveBeenCalledTimes(1); expect(onResetFn2).toHaveBeenCalledTimes(1); unregister1(); _stylesheet.reset(); expect(onResetFn1).toHaveBeenCalledTimes(1); expect(onResetFn2).toHaveBeenCalledTimes(2); }); }); describe('getClassName', () => { it('generates indexed names', () => { const class1 = _stylesheet.getClassName(); const class2 = _stylesheet.getClassName(); const class3 = _stylesheet.getClassName(); expect(class1).toEqual('css-0'); expect(class2).toEqual('css-1'); expect(class3).toEqual('css-2'); }); it('gets default prefix from config', () => { _stylesheet.setConfig({ defaultPrefix: 'myCss' }); const className = _stylesheet.getClassName(); expect(className).toEqual('myCss-0'); }); it('gets namespace from config', () => { _stylesheet.setConfig({ namespace: 'kobzol' }); const className = _stylesheet.getClassName(); expect(className).toEqual('kobzol-css-0'); }); it('accepts displayName override over default prefix', () => { const className = _stylesheet.getClassName('kobzol'); expect(className).toEqual('kobzol-0'); }); }); describe('cacheClassName', () => { it('preserves className in a cache', () => { const { className, key } = cacheClassNameSetup(_stylesheet); const classNameCache = _stylesheet.getClassNameCache(); expect(classNameCache).toEqual({ [key]: className, }); }); }); describe('classNameFromKey', () => { it('fetches preserved className from cache', () => { const { className, key } = cacheClassNameSetup(_stylesheet); const result = _stylesheet.classNameFromKey(key); expect(result).toEqual(className); }); }); describe('argsFromClassName', () => { it('gets args from a cached className', () => { const { args, className } = cacheClassNameSetup(_stylesheet); const result = _stylesheet.argsFromClassName(className); expect(result).toEqual(args); }); it('returns "undefined" if classNames is not in cache', () => { cacheClassNameSetup(_stylesheet); const result = _stylesheet.argsFromClassName('uncached-className'); expect(result).toBeUndefined(); }); }); describe('insertedRulesFromClassName', () => { it('gets rules from a cached className', () => { const { rules, className } = cacheClassNameSetup(_stylesheet); const result = _stylesheet.insertedRulesFromClassName(className); expect(result).toEqual(rules); }); it('returns "undefined" if classNames is not in cache', () => { cacheClassNameSetup(_stylesheet); const result = _stylesheet.insertedRulesFromClassName('uncached-className'); expect(result).toBeUndefined(); }); }); describe('insertRule', () => { it('inserts a rule into a stylesheet', () => { _stylesheet.insertRule('a { background: red };'); const rules = _stylesheet.getRules(); expect(rules).toEqual('a { background: red };'); }); it('can insert a preserved rule into a stylesheet', () => { _stylesheet.insertRule('a { background: red };', true); _stylesheet.reset(); const rules = _stylesheet.getRules(true); expect(rules).toEqual('a { background: red };'); }); it('DEPRECATED: calls onInsertRuleCallback from config upon rule insertion', () => { const onInsertRuleFn = jest.fn(); _stylesheet.setConfig({ onInsertRule: onInsertRuleFn }); _stylesheet.insertRule('a { background: red };'); expect(onInsertRuleFn).toHaveBeenCalledTimes(1); expect(onInsertRuleFn).toHaveBeenCalledWith('a { background: red };'); }); }); describe('onInsertRule', () => { it('gets called with callbacks when insertRule() is called', () => { const onInsertRuleFn = jest.fn(); _stylesheet.onInsertRule(onInsertRuleFn); _stylesheet.insertRule('a { background: red };'); expect(onInsertRuleFn).toHaveBeenCalledTimes(1); }); it('provides a way to unregister a callback', () => { const onInsertRuleFn1 = jest.fn(); const onInsertRuleFn2 = jest.fn(); const unregister1 = _stylesheet.onInsertRule(onInsertRuleFn1); _stylesheet.onInsertRule(onInsertRuleFn2); _stylesheet.insertRule('a { background: red };'); expect(onInsertRuleFn1).toHaveBeenCalledTimes(1); expect(onInsertRuleFn2).toHaveBeenCalledTimes(1); unregister1(); _stylesheet.insertRule('a { background: red };'); expect(onInsertRuleFn1).toHaveBeenCalledTimes(1); expect(onInsertRuleFn2).toHaveBeenCalledTimes(2); }); }); describe('getRules', () => { it('gets rules defined in stylesheet', () => { _stylesheet.insertRule('a { background: red };'); _stylesheet.insertRule('h1 { background: blue };'); const rules = _stylesheet.getRules(); expect(rules).toEqual('a { background: red };h1 { background: blue };'); }); it('gets preserved rules defined in stylesheet when "includePreservedRules" is true', () => { _stylesheet.insertRule('a { background: red };', true); _stylesheet.insertRule('h1 { background: blue };', true); const rules = _stylesheet.getRules(true); expect(rules).toEqual( 'a { background: red };h1 { background: blue };a { background: red };h1 { background: blue };', ); }); it('omits preserved rules defined in stylesheet when "includePreservedRules" is undefined', () => { _stylesheet.insertRule('a { background: red };', true); _stylesheet.insertRule('h1 { background: blue };', true); const rules = _stylesheet.getRules(); expect(rules).toEqual('a { background: red };h1 { background: blue };'); }); it('omits preserved rules defined in stylesheet when "includePreservedRules" is false', () => { _stylesheet.insertRule('a { background: red };', true); _stylesheet.insertRule('h1 { background: blue };', true); const rules = _stylesheet.getRules(false); expect(rules).toEqual('a { background: red };h1 { background: blue };'); }); it('prepends preserved rules before other rules', () => { _stylesheet.insertRule('a { background: red };'); _stylesheet.insertRule('h1 { background: blue };', true); const rules = _stylesheet.getRules(true); expect(rules).toEqual('h1 { background: blue };a { background: red };h1 { background: blue };'); }); }); describe('serialization', () => { it('can be serialized (empty)', () => { const serializedStylesheet = _stylesheet.serialize(); expect(serializedStylesheet).toEqual( '{"classNameToArgs":{},"counter":0,"keyToClassName":{},"preservedRules":[],"rules":[]}', ); }); it('can be serialized (with data)', () => { _stylesheet.getClassName(); _stylesheet.insertRule('a { background: red };'); cacheClassNameSetup(_stylesheet); const serializedStylesheet = _stylesheet.serialize(); expect(serializedStylesheet).toEqual( // eslint-disable-next-line @fluentui/max-len '{"classNameToArgs":{"css-1":{"args":[{"background":"red"}],"rules":["a { background: red };"]}},"counter":2,"keyToClassName":{"kobzol":"css-1"},"preservedRules":[],"rules":["a { background: red };"]}', ); }); it('can be deserialized', () => { const rehydrationData = JSON.parse( // eslint-disable-next-line @fluentui/max-len '{"classNameToArgs":{"css-1":{"args":[{"background":"red"}],"rules":["a { background: red };"]}},"counter":2,"keyToClassName":{"kobzol":"css-1"},"preservedRules":[],"rules":["a { background: red };"]}', ); expect(rehydrationData).toStrictEqual({ classNameToArgs: { 'css-1': { args: [ { background: 'red', }, ], rules: ['a { background: red };'], }, }, counter: 2, keyToClassName: { kobzol: 'css-1', }, preservedRules: [], rules: ['a { background: red };'], }); }); }); }); });
the_stack
import * as assert from "assert"; const DeepEqual = require('deep-equal'); const CHAR_CODE_A = 65; const CHAR_CODE_Z = 90; const CHAR_CODE_a = 97; const CHAR_CODE_z = 122; const CHAR_CODE__ = 95; const CHAR_CODE_0 = 48; const CHAR_CODE_9 = 57; const CHAR_CODE_SPACE = 32; const CHAR_CODE_TAB = 9; const CHAR_CODE_MINUS = 45; const CHAR_CODE_DOT = 46; const CHAR_CODE_NEWLINE = 10; const CHAR_CODE_WIN_NEWLINE = 13; interface Node { Visit : any, Generate: (w: DynamicBuffer, v: Verse) => void, } interface Elem { tok: {number: boolean}, done: boolean, pos: number, inc: number } interface Brk { open: number, clos: number, pos: number, } class DynamicBuffer { private len: number; private buffer: Buffer; private offset: number; constructor(len?: number) { this.len = len ? len : 1024; this.buffer = Buffer.alloc(this.len); this.offset = 0; } Write(p: Buffer) { if (this.offset + p.length > this.len) { this.buffer = Buffer.concat([this.buffer, Buffer.alloc(this.len)]); this.len = this.len * 2; } p.copy(this.buffer, this.offset); this.offset += p.length; } Bytes(): Buffer { return this.buffer.slice(0, this.offset); } } function makeDict(s : Buffer): {string: {}} { // @ts-ignore let res : {string: {}} = {}; // @ts-ignore res[s.toString()] = {}; return res; } function randTerm(v: Verse, dict: {string: {}}): Buffer { const terms = Object.keys(dict); return Buffer.from(terms[v.Rand(terms.length)]); } function singleTerm(dict: {string: {}}): string { for (let k in dict) { return k; } return 'BAD' } export class BlockNode { public nodes : Node[]; constructor(nodes: Node[]) { this.nodes = nodes; } Visit(f: (n: Node)=>void) { f(this); for (let i of this.nodes) { i.Visit(f); } } Generate(w: DynamicBuffer, v: Verse) { let nodes = this.nodes; if (v.Rand(10) == 0) { while (nodes.length > 0 && v.Rand(2) == 0) { const idx = v.Rand(nodes.length); nodes.copyWithin(0, idx+1, Math.min(idx, nodes.length - (idx+1))); nodes = nodes.slice(0, nodes.length-1); } } if (v.Rand(10) == 0) { while (nodes.length > 0 && v.Rand(2) == 0) { const idx = v.Rand(nodes.length); nodes.copyWithin(idx+1, idx) } } if (v.Rand(10) == 0) { while (nodes.length > 0 && v.Rand(2) == 0) { const idx1 = v.Rand(nodes.length); const idx2 = v.Rand(nodes.length); [nodes[idx1], nodes[idx2]] = [nodes[idx2], nodes[idx1]] } } for (let n of this.nodes) { if (v.Rand(20) == 0) { continue } if (v.Rand(20) == 0) { } n.Generate(w, v); } } } export function BuildVerse(oldv: Verse | null, data: Buffer): Verse | null { let printable = 0; for (let b of data) { if ( b >= 0x20 && b < 0x7f) { printable++; } } if (printable < (data.length*9/10)) { return oldv } const newv = new Verse(); if (oldv != null) { newv.blocks = oldv.blocks; newv.allNodes = oldv.allNodes } let n = tokenize(data); n = structure(n); const b = new BlockNode(n); newv.blocks = newv.blocks.concat(b); b.Visit((n) => { newv.allNodes = newv.allNodes.concat(n); }); return newv; } export class Verse { public blocks : BlockNode[] = []; public allNodes : Node[] = []; Rhyme(): Buffer { let buf = new DynamicBuffer(); this.blocks[this.Rand(this.blocks.length)].Generate(buf, this); return buf.Bytes(); } Rand(n: number): number { return Math.floor(Math.random() * Math.floor(n)); } } class WsNode { public dict: {string: any}; constructor(dict: {string: any}) { this.dict = dict; } Visit(f: (n: Node)=>void) { f(this); } Generate(w: DynamicBuffer, v: Verse) { if (v.Rand(5) != 0) { w.Write(randTerm(v, this.dict)) } else { while (true) { const r = v.Rand(3); if (r === 0) { break; } else if (r === 1) { w.Write(Buffer.from(' ')) } else if (r === 2) { w.Write(Buffer.from('\t')) } } } } } class AlphaNumNode { public dict: {string: {}}; constructor(dict: {string: {}}) { this.dict = dict; } Visit(f: (n: Node)=>void) { f(this); } Generate(w: DynamicBuffer, v: Verse) { if (v.Rand(5) != 0) { w.Write(randTerm(v, this.dict)); } else { let len = 0; const r = v.Rand(3); if (r === 0) { len = v.Rand(4); } else if (r === 1) { len = v.Rand(20); } else if (r === 2) { len = v.Rand(100); } const res = Buffer.alloc(len); for (let i=0; i<res.length; i++) { const r = v.Rand(4); if (r === 0) { res[i] = '_'.charCodeAt(0); } else if (r === 1) { res[i] = '0'.charCodeAt(0) + v.Rand(10); } else if (r === 2) { res[i] = 'a'.charCodeAt(0) + v.Rand(26); } else if (r === 3) { res[i] = 'A'.charCodeAt(0) + v.Rand(26) } } w.Write(res) } } } class NumNode { public dict: {string: {}}; private hex: boolean; constructor(dict: {string: {}}, hex: boolean) { this.dict = dict; this.hex = hex; } Visit(f: (n: Node)=>void) { f(this); } Generate(w: DynamicBuffer, v: Verse) { if (v.Rand(2) === 0) { w.Write(randTerm(v, this.dict)) } else { const randNum = function () { const base = [8, 10, 16][v.Rand(3)]; let len = 0; const r = v.Rand(3); if (r === 0) { len = v.Rand(4); } else if (r === 1) { len = v.Rand(16); } else if (r === 2) { len = v.Rand(40); } let num = Buffer.alloc(len + 1); for (let i = 0; i < num.length; i++) { switch (base) { case 8: num[i] = '0'.charCodeAt(0) + v.Rand(8); break; case 10: num[i] = '0'.charCodeAt(0) + v.Rand(10); break; case 16: const r = v.Rand(3); switch (r) { case 0: num[i] = '0'.charCodeAt(0) + v.Rand(10); break; case 1: num[i] = 'a'.charCodeAt(0) + v.Rand(6); break; case 2: num[i] = 'A'.charCodeAt(0) + v.Rand(6); } } } switch (base) { case 8: num = Buffer.concat([Buffer.from('0'), num]); break; case 10: case 16: num = Buffer.concat([Buffer.from('0x'), num]); break; default: assert.fail("bad"); } if (v.Rand(2) == 0) { num = Buffer.concat([Buffer.from('-'), num]) } return num; }; switch (v.Rand(3)) { case 0: w.Write(randNum()); break; case 1: w.Write(randNum()); w.Write(Buffer.from('.')); w.Write(randNum()); break; case 2: w.Write(randNum()); w.Write(Buffer.from('e')); w.Write(randNum()); break; } } } } class ControlNode { public ch: number; constructor(ch: number) { this.ch = ch; } Visit(f: (n: Node)=>void) { f(this); } Generate(w: DynamicBuffer, v: Verse) { if (v.Rand(10) !== 0) { w.Write(Buffer.alloc(1, this.ch)); } else { while (true) { const b = v.Rand(128); if ((b >= CHAR_CODE_0 && b <= CHAR_CODE_9) || (b >= CHAR_CODE_a && b <= CHAR_CODE_z) || (b >= CHAR_CODE_A && b <= CHAR_CODE_Z)) { continue; } w.Write(Buffer.alloc(1, b)); break } } } } class BracketNode { public b: BlockNode; private clos: number; private open: number; constructor(open: number, clos: number, b: BlockNode) { this.open = open; this.clos = clos; this.b = b; } Visit(f: (n: Node)=>void) { f(this); this.b.Visit(f) } Generate(w: DynamicBuffer, v: Verse) { if (v.Rand(10) != 0) { w.Write(Buffer.alloc(1, this.open)); this.b.Generate(w, v); w.Write(Buffer.alloc(1, this.clos)); } else { const brk = ['<', '[', '(', '{', '\'', '"', '`']; const open = brk[v.Rand(brk.length)]; // @ts-ignore let clos = brackets[open]; if (v.Rand(5) == 0) { // @ts-ignore clos = brackets[brk[v.Rand(brk.length)]]; } w.Write(Buffer.from(open)); this.b.Generate(w, v); w.Write(Buffer.from(clos)) } } } class KeyValNode { public value: AlphaNumNode; public key: AlphaNumNode; private delim: number; constructor(delim: number, key: AlphaNumNode, value: AlphaNumNode) { this.delim = delim; this.key = key; this.value = value; } Visit(f: (n: Node)=>void) { f(this); this.key.Visit(f); this.value.Visit(f); } Generate(w: DynamicBuffer, v: Verse) { const delim = ['='.charCodeAt(0), ':'.charCodeAt(0)]; this.delim = delim[v.Rand(delim.length)]; this.key.Generate(w, v); w.Write(Buffer.alloc(1, this.delim)); this.value.Generate(w, v); } } class ListNode { public delim: number; public blocks: BlockNode[]; constructor(delim: number, blocks: BlockNode[]) { this.delim = delim; this.blocks = blocks; } Visit(f: (n: Node)=>void) { f(this); for (let b of this.blocks) { b.Visit(f) } } Generate(w: DynamicBuffer, v: Verse) { let blocks = this.blocks; if (v.Rand(5) === 0) { blocks = []; while (v.Rand(3) !== 0) { blocks = blocks.concat([this.blocks[v.Rand(this.blocks.length)]]); } } for (let i=0; i<this.blocks.length; i++) { if (i != 0) { w.Write(Buffer.alloc(1, this.delim)); } this.blocks[i].Generate(w, v); } } } class LineNode { public r: boolean; public b: BlockNode; constructor(r: boolean, b: BlockNode) { this.r = r; this.b = b; } Visit(f: (n: Node)=>void) { f(this); this.b.Visit(f) } Generate(w: DynamicBuffer, v: Verse) { this.b.Generate(w, v); if (this.r) { w.Write(Buffer.from('\r\n')); } else { w.Write(Buffer.from('\n')); } } } function DecodeRune(data: any): any { return [1, 2]; } function tokenize(data: Buffer) { let res : Node[] = []; enum StateType { stateControl, stateWs , stateAlpha, stateNum, } let state = StateType.stateControl; let start = 0; for (let i=0; i < data.length; i++) { const [r,s] = DecodeRune(data.slice(i)); if ( (r >= CHAR_CODE_a && r <= CHAR_CODE_z) || (r >= CHAR_CODE_A && r <= CHAR_CODE_Z) || r === CHAR_CODE__) { if (state === StateType.stateControl) { start = i; state = StateType.stateAlpha } else if (state === StateType.stateWs) { res.push(new WsNode(makeDict(data.slice(start, i)))); start = i; state = StateType.stateAlpha; } else if (state === StateType.stateAlpha || state == StateType.stateNum) { state = StateType.stateAlpha; } } else if (r >= CHAR_CODE_0 && r <= CHAR_CODE_9) { if (state === StateType.stateControl) { start = i; state = StateType.stateNum; } else if (state === StateType.stateWs) { res.push(new WsNode(makeDict(data.slice(start ,i)))); start = i; state = StateType.stateNum; } } else if ( r === CHAR_CODE_SPACE || r === CHAR_CODE_TAB) { if (state === StateType.stateControl) { start = i; state = StateType.stateWs; } else if (state === StateType.stateAlpha) { res.push(new AlphaNumNode(makeDict(data.slice(start, i)))); start = i; state = StateType.stateWs; } else if (state == StateType.stateNum) { res.push(new NumNode(makeDict(data.slice(start, i)), false)); start = i; state = StateType.stateWs; } } else { if (state === StateType.stateControl || state === StateType.stateWs) { res.push(new WsNode(makeDict(data.slice(start, i)))); } else if (state === StateType.stateAlpha) { res.push(new AlphaNumNode(makeDict(data.slice(start, i)))) } else if (state === StateType.stateNum) { res.push(new NumNode(makeDict(data.slice(start, i)), false)) } state = StateType.stateControl; res.push(new ControlNode(r)); } i += s; } if (state === StateType.stateAlpha) { res.push(new AlphaNumNode(makeDict(data.slice(start)))); } else if (state === StateType.stateNum) { res.push(new NumNode(makeDict(data.slice(start)), false)); } return res; } function structure(nn : Node[]): Node[] { nn = extractNumbers(nn); nn = structureBrackets(nn); nn = structureKeyValue(nn); nn = structureLists(nn); nn = structureLines(nn); return nn } function isHexNum(s: string): boolean { if (s.length) { return false; } for (let i=0; i<s.length; i++) { const c = s[i]; if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) { continue } return false; } return true; } function isDecNum(s: string) : boolean { if (s.length === 0) { return false; } for (let i = 0; i < s.length; i++) { if (s[i] >= '0' && s[i] <= '9') { continue; } return false; } return true; } function extractNumbers(nn : Node[]): Node[] { let changed = true; while (changed) { changed = false; for (let i = 0; i < nn.length; i++) { const n = nn[i]; if (n instanceof AlphaNumNode) { const v = singleTerm(n.dict); if (v.length >= 3) { if (v[0] === '0' && v[1] === 'x' && isHexNum(v.slice(2))) { nn[i] = new NumNode(n.dict, true); changed = true; } const e = v.indexOf('e'); if (e !== -1) { if (isDecNum(v.slice(0, e)) && isDecNum(v.slice(e+1))) { nn[i] = new NumNode(n.dict, false); changed = true; continue; } if (e == (v.length-1) && i !== (nn.length-1)) { const num1 = nn[i+1]; if (num1 instanceof NumNode) { nn[i+1] = new NumNode(makeDict(Buffer.from(v + singleTerm(num1.dict))), false); nn.copyWithin(i, i+1); changed = true; continue; } } } } } if (n instanceof ControlNode && n.ch === CHAR_CODE_MINUS && i !== nn.length-1) { const num = nn[i+1]; if (num instanceof NumNode) { let prev = undefined; if (i != 0) { prev = nn[i-1] } if (prev instanceof AlphaNumNode && singleTerm(prev.dict).length > 1 && singleTerm(prev.dict)[singleTerm(prev.dict).length-1] == 'e') { nn.copyWithin(i, i+1); changed=true; continue; } } } if (n instanceof ControlNode && n.ch === CHAR_CODE_DOT && i != 0 && i != nn.length-1) { const num1 = nn[i-1]; const num2 = nn[i+1]; if (num1 instanceof NumNode && num2 instanceof NumNode) { nn[i+1] = new NumNode( makeDict( Buffer.from(singleTerm(num1.dict) + "." + singleTerm(num2.dict))), false); nn.copyWithin(i-1, i+1); changed = true; continue; } } } } return nn } function structureKeyValue(nn : Node[]) : Node[]{ const delims = {'=': true, ':': true}; for (let n of nn) { if (n instanceof BracketNode) { n.b.nodes = structureKeyValue(n.b.nodes); } } for (let i=0; i<nn.length; i++) { const n = nn[i]; if (!(n instanceof ControlNode)) { continue } // @ts-ignore if (delims[n.ch] && !(i == 0 || i == nn.length-1 )) { const key = nn[i-1]; if (!(key instanceof AlphaNumNode)) { continue; } const value = nn[i+1]; if (!(value instanceof AlphaNumNode)) { continue; } nn[i+1] = new KeyValNode(n.ch, key, value); nn.copyWithin(i-1, i+1); nn = nn.slice(0, nn.length-2); } } return nn; } const brackets = { '<': '>', '[': ']', '(': ')', '{': '}', '\'': '\'', '"': '"', '`': '`', }; function structureBrackets(nn: Node[]) : Node[]{ let stk: Brk[] = []; loop: for (let i=0; i<nn.length; i++) { const n = nn[i]; if (!(n instanceof ControlNode)) { continue; } for (let si=stk.length - 1; si >= 0; si--) { if (n.ch === stk[si].clos) { const b = new BracketNode( stk[si].open, stk[si].clos, new BlockNode(nn.slice(stk[si].pos+1, i)) ); nn[stk[si].pos] = b; nn.copyWithin(stk[si].pos+1, i+1); nn = nn.slice(0, nn.length - i + stk[si].pos); i = stk[si].pos; stk = stk.slice(0, si); continue loop; } } // @ts-ignore const clos = brackets[String.fromCharCode(n.ch)]; if (clos) { stk.push( { clos: clos, open: n.ch, pos: i, }) } } return nn; } function structureLists(nn: Node[]) : Node[] { const delims = {',': true, ';': true}; for (let n of nn) { if (n instanceof BracketNode) { n.b.nodes = structureLists(n.b.nodes); } } // TODO: fails on: // "f1": "v1", "f2": "v2", "f3": "v3" // the first detected list is "v2", "f3" for (let i=nn.length-1; i>=0; i--) { const n = nn[i]; // @ts-ignore if (n instanceof ControlNode && delims[n.ch]) { const elems = [ {tok: {}, done: false, pos: i-1, inc: -1}, {tok: {}, done: false, pos: i+1, inc: 1} ]; while (true) { for (let e of elems) { if (e.done || e.pos < 0 || e.pos >= nn.length) { e.done = true; continue; } const ctrl1 = nn[e.pos]; if (ctrl1 instanceof ControlNode) { if (ctrl1.ch == n.ch) { e.done = true; continue; } // @ts-ignore e.tok[ctrl1.ch] = true; } const brk1 = nn[e.pos]; if (brk1 instanceof BracketNode) { // @ts-ignore e.tok[brk1.open] = true; // @ts-ignore e.tok[brk1.clos] = true; } e.pos += e.inc; } if (elems[0].done && elems[1].done) { break; } const union = {}; for (let k in elems[0].tok) { // @ts-ignore union[k] = true; } for (let k in elems[1].tok) { // @ts-ignore union[k] = true; } if (DeepEqual(elems[0].tok, union) || DeepEqual(elems[1].tok, union)) { break } } for (let k in elems[1].tok) { // @ts-ignore elems[0].tok[k] = true; } elemLoop: for (let e of elems) { for(; e.pos >=0 && e.pos < nn.length; e.pos += e.inc) { const ctrl1 = nn[e.pos]; // @ts-ignore if (ctrl1 instanceof ControlNode && !elems[0].tok[ctrl1.ch]) { continue elemLoop; } const brk1 = nn[e.pos]; // @ts-ignore if (brk1 instanceof ControlNode && !elems[0].tok[brk1.ch]) { continue elemLoop; } } } for (let e of elems) { while (true) { if (e.done || e.pos < 0 || e.pos >= nn.length) { break; } const ctrl1 = nn[e.pos]; if (ctrl1 instanceof ControlNode) { if (ctrl1.ch == n.ch) { break } // @ts-ignore if (!elems[0].tok[ctrl1.ch]) { break } } const brk1 = nn[e.pos]; if (brk1 instanceof BracketNode) { // @ts-ignore if (!elems[0].tok[brk1.open] || !elems[0].tok[brk1.clos]) { break } } e.pos += e.inc } } const lst = new ListNode(n.ch, [ new BlockNode(nn.slice(elems[0].pos+1, i)), new BlockNode(nn.slice(i+1, elems[1].pos)) ]); let start = elems[0].pos; const end = elems[1].pos; while (true) { if (start < 0) { break; } const ctrl1 = nn[start]; if (!(ctrl1 instanceof ControlNode) || ctrl1.ch != n.ch) { break } let pos = start - 1; while (true) { if (pos < 0) { break; } const ctrl1 = nn[pos]; if (ctrl1 instanceof ControlNode) { if (ctrl1.ch == n.ch) { break; } // @ts-ignore if (!elems[0].tok[ctrl1.ch]) { break; } } const brk1 = nn[pos]; if (brk1 instanceof BracketNode) { // @ts-ignore if (!elems[0].tok[brk1.open] || !elems[0].tok[brk1.clos]) { break } } pos--; } lst.blocks = [new BlockNode(nn.slice(pos+1, start))].concat(lst.blocks); start = pos; } nn[start+1] = lst; nn.copyWithin(start+2, end); nn = nn.slice(0, nn.length-end+start+2); i = start + 1; } } return nn; } function structureLines(nn: Node[]): Node[] { let res: Node[] = []; for (let i=0; i<nn.length; i++) { const n = nn[i]; if (n instanceof BracketNode) { n.b.nodes = structureLines(n.b.nodes); continue; } if (!(n instanceof ControlNode) || n.ch != CHAR_CODE_NEWLINE) { continue; } let r = false; let end = i; if (i != 0) { const prev = nn[i-1]; if (prev instanceof ControlNode && prev.ch == CHAR_CODE_WIN_NEWLINE) { r = true; end--; } } res = res.concat(new LineNode(r, new BlockNode(nn.slice(0, end)))); nn = nn.slice(i+1,nn.length); i = -1; } if (nn.length != 0) { res = res.concat(nn); } return res; }
the_stack
// Bootstrap an installation of Almond Cloud by creating the // database schema and adding the requisite initial data import assert from 'assert'; import * as argparse from 'argparse'; import * as path from 'path'; import { promises as pfs } from 'fs'; import * as mysql from 'mysql'; import * as Url from 'url'; import * as ThingTalk from 'thingtalk'; import * as db from '../util/db'; import * as user from '../util/user'; import * as I18n from '../util/i18n'; import * as userModel from '../model/user'; import * as organization from '../model/organization'; import * as entityModel from '../model/entity'; import * as stringModel from '../model/strings'; import * as nlpModelsModel from '../model/nlp_models'; import { makeRandom } from '../util/random'; import * as Importer from '../util/import_device'; import { clean } from '../util/tokenize'; import * as execSql from '../util/exec_sql'; import * as Config from '../config'; const req : { _(x : string) : string; user ?: Express.User } = { _(x : string) { return x; }, }; const DEFAULT_TRAINING_CONFIG = JSON.stringify({ dataset_target_pruning_size: 1000, dataset_contextual_target_pruning_size: 100, dataset_quoted_probability: 0.1, dataset_eval_probability: 0.5, dataset_split_strategy: 'sentence', synthetic_depth: 7, train_iterations: 50000, train_batch_tokens: 400, val_batch_size: 3000, model: 'TransformerSeq2Seq', pretrained_model: 'facebook/bart-large', gradient_accumulation_steps: 20, warmup: 40, lr_multiply: 0.01, }); async function createRootOrg(dbClient : db.Client) { return organization.create(dbClient, { name: 'Site Administration', comment: '', id_hash: makeRandom(8), developer_key: Config.WITH_THINGPEDIA === 'external' ? (Config.ROOT_THINGPEDIA_DEVELOPER_KEY || makeRandom()) : makeRandom(), is_admin: true }); } type BasicOrgRow = { id : number }; async function createDefaultUsers(dbClient : db.Client, rootOrg : BasicOrgRow) { req.user = await user.register(dbClient, req, { username: 'root', password: 'rootroot', email: 'root@localhost', email_verified: true, locale: 'en-US', timezone: 'America/Los_Angeles', developer_org: rootOrg.id, developer_status: user.DeveloperStatus.ORG_ADMIN, roles: user.Role.ROOT, profile_flags: user.ProfileFlags.VISIBLE_ORGANIZATION_PROFILE, }); await user.register(dbClient, req, { username: 'anonymous', password: 'rootroot', email: 'anonymous@localhost', email_verified: true, locale: 'en-US', timezone: 'America/Los_Angeles', developer_org: rootOrg.id, profile_flags: 0 }); for (const locale of Config.SUPPORTED_LANGUAGES) { const lang = I18n.localeToLanguage(locale); if (lang === 'en') continue; await user.register(dbClient, req, { username: 'anonymous-' + lang, password: 'rootroot', email: 'anonymous-' + lang + '@localhost', email_verified: true, locale: locale, timezone: 'America/Los_Angeles', developer_org: rootOrg.id, profile_flags: 0 }); } } async function importStandardEntities(dbClient : db.Client) { const ENTITIES : Record<string, string> = { 'tt:contact': 'Contact Identity', 'tt:contact_name': 'Contact Name', 'tt:device': 'Device Name', 'tt:device_id': 'Device Unique Identifier', 'tt:email_address': 'Email Address', 'tt:flow_token': 'Flow Identifier', 'tt:function': 'Function Name', 'tt:hashtag': 'Hashtag', 'tt:path_name': 'Unix Path', 'tt:phone_number': 'Phone Number', 'tt:picture': 'Picture', 'tt:program': 'Program', 'tt:url': 'URL', 'tt:username': 'Username' }; await entityModel.createMany(dbClient, Object.keys(ENTITIES).map((id) => { return { id: id, name: ENTITIES[id], language: 'en', is_well_known: true, has_ner_support: false }; })); // this entity types are not a well known entity // you must import the values separately await entityModel.create(dbClient, { id: 'org.freedesktop:app_id', name: 'Freedesktop App Identifier', is_well_known: false, has_ner_support: true }); await entityModel.create(dbClient, { id: 'tt:command_id', name: 'Thingpedia Command ID', is_well_known: false, has_ner_support: false }); await entityModel.create(dbClient, { id: 'tt:iso_lang_code', name: 'Language Identifier', is_well_known: false, has_ner_support: true }); await entityModel.create(dbClient, { id: 'tt:timezone', name: 'Timezone Identifier', is_well_known: false, has_ner_support: true }); } async function importStandardStringTypes(dbClient : db.Client, rootOrg : BasicOrgRow) { const STRING_TYPES : Record<string, string> = { 'tt:search_query': 'Web Search Query', 'tt:short_free_text': 'General Text (short phrase)', 'tt:long_free_text': 'General Text (paragraph)', 'tt:person_first_name': 'First names of people', 'tt:path_name': 'File and directory names', 'tt:location': 'Cities, points on interest and addresses', 'tt:word': 'Individual words' }; await stringModel.createMany(dbClient, Object.keys(STRING_TYPES).map((id) => { const obj : db.WithoutID<stringModel.Row> = { type_name: id, name: STRING_TYPES[id], language: 'en', license: 'public-domain', attribution: '', }; if (id === 'tt:long_free_text' || id === 'tt:short_free_text') { obj.license = 'non-commercial'; obj.attribution = 'The Brown Corpus <http://www.hit.uib.no/icame/brown/bcm.html>'; } if (id === 'tt:person_first_name') obj.attribution = 'United States Census and Social Security data'; if (id === 'tt:location') { obj.license = 'free-copyleft'; obj.attribution = 'Copyright © OpenStreetMap contributors <https://www.openstreemap.org/copyright>. Distributed under the Open Data Commons Open Database License.'; } return obj; })); } async function importStandardSchemas(dbClient : db.Client, rootOrg : BasicOrgRow) { const CATEGORIES = ['online-account', 'data-source', 'thingengine-system', 'communication', 'data-management', 'health', 'home', 'media', 'service', 'social-network']; // the category and subcategory markers are not used by Thingpedia // anymore, but they are still used by the client in certain cases, // and still exposed by BaseDevice.hasKind() // (for example, the platform layers call device.hasKind('thingengine-system') // to filter out system devices) // so we register them as types to avoid users creating regular // types with the same name, which would be dangerous (eg it would // let the user call @online-account in ThingTalk) // these types are very special in the system, so we use a raw // SQL query to create them await db.query(dbClient, `insert into device_schema(kind, kind_type, owner, developer_version, approved_version, kind_canonical) values ?`, [CATEGORIES.map((c) => [c, 'category', rootOrg.id, 0, 0, clean(c)])]); } function getBuiltinIcon(kind : string) { switch (kind) { case 'org.thingpedia.builtin.bluetooth.generic': case 'org.thingpedia.builtin.matrix': return kind + '/icon.png'; default: return 'icon.png'; } } async function importBuiltinDevices(dbClient : db.Client, rootOrg : BasicOrgRow) { const BUILTIN_DEVICES = [ // interfaces 'messaging', 'org.thingpedia.volume-control', // devices 'org.thingpedia.builtin.thingengine', 'org.thingpedia.builtin.thingengine.builtin', 'org.thingpedia.builtin.thingengine.gnome', 'org.thingpedia.builtin.thingengine.phone', 'org.thingpedia.builtin.test', 'org.thingpedia.builtin.bluetooth.generic', ] as const; for (const primaryKind of BUILTIN_DEVICES) { console.log(`Loading builtin device ${primaryKind}`); const directory = path.resolve(path.dirname(module.filename), '../../data/' + primaryKind); const manifest = await pfs.readFile(path.join(directory, 'manifest.tt'), { encoding: 'utf8' }); const library = ThingTalk.Syntax.parse(manifest, ThingTalk.Syntax.SyntaxType.Normal, { locale: 'en-US', timezone: 'UTC' }); assert(library instanceof ThingTalk.Ast.Library); const classDef = library.classes[0]; const dataset = await pfs.readFile(path.join(directory, 'dataset.tt'), { encoding: 'utf8' }); const data = { class: manifest, dataset, thingpedia_name: classDef.nl_annotations.thingpedia_name, thingpedia_description: classDef.nl_annotations.thingpedia_description, subcategory: classDef.getImplementationAnnotation<string>('subcategory') ?? 'service', license: classDef.getImplementationAnnotation<string>('license') ?? 'Apache-2.0', license_gplcompatible: classDef.getImplementationAnnotation<boolean>('license_gplcompatible') ?? true, website: classDef.getImplementationAnnotation<string>('website'), repository: classDef.getImplementationAnnotation<string>('repository'), issue_tracker: classDef.getImplementationAnnotation<string>('issue_tracker'), }; const iconPath = path.resolve(path.dirname(module.filename), '../../data/' + getBuiltinIcon(primaryKind)); await Importer.importDevice(dbClient, req, primaryKind, data, { owner: rootOrg.id, iconPath: iconPath }); } } async function importDefaultNLPModels(dbClient : db.Client, rootOrg : BasicOrgRow) { await nlpModelsModel.create(dbClient, { language: 'en', tag: 'org.thingpedia.models.default', owner: rootOrg.id, flags: JSON.stringify([ 'aggregation', 'bookkeeping', 'configure_actions', 'multifilters', 'policies', 'projection', 'projection_with_filter', 'remote_commands', 'schema_org', 'screen_selection', 'timer', 'undefined_filter', ]), config: DEFAULT_TRAINING_CONFIG, contextual: true, all_devices: true, use_approved: true, use_exact: true }); await nlpModelsModel.create(dbClient, { language: 'en', tag: 'org.thingpedia.models.developer', owner: rootOrg.id, flags: JSON.stringify([ 'aggregation', 'bookkeeping', 'configure_actions', 'extended_timers', 'multifilters', 'policies', 'projection', 'projection_with_filter', 'remote_commands', 'schema_org', 'screen_selection', 'timer', 'undefined_filter', ]), config: DEFAULT_TRAINING_CONFIG, contextual: true, all_devices: true, use_approved: false, use_exact: true }); } async function isAlreadyBootstrapped() { try { return await db.withClient(async (dbClient) => { // check if we have a root user, and consider us bootstrapped if so const [root] = await userModel.getByName(dbClient, 'root'); return !!root; }); } catch(e) { // on error, we likely do not even have the necessary tables return false; } } export function initArgparse(subparsers : argparse.SubParser) { const parser = subparsers.add_parser('bootstrap', { description: 'Bootstrap an installation of Almond Cloud' }); parser.add_argument('--force', { action: 'store_true', default: false, help: 'Force bootstrapping even if it appears to have occurred already.' }); } async function waitForDB() { // FIXME This is terrible code, written hastily. Needs clean up. console.log(`Waiting for the database to come up...`); const parsed = Url.parse(Config.DATABASE_URL!); const [user, pass] = parsed.auth!.split(':'); const options = { host: parsed.hostname!, port: parseInt(parsed.port!), database: parsed.pathname!.substring(1), user: user, password: pass, multipleStatements: true }; Object.assign(options, parsed.query); const TIMEOUT_MS = 30000; // 30 seconds const SLEEP_MS = 1000; // 1 second const start_time = Date.now(); const sleep = (ms : number) => { return new Promise((resolve) => { setTimeout(resolve, ms); }); }; while (Date.now() - start_time < TIMEOUT_MS) { console.log(`Attempting to connect to the db...`); const ok = await new Promise<boolean>((resolve, _reject) => { const connection = mysql.createConnection(options); connection.query(`SHOW TABLES;`, (error : any) => { if (error) { console.error(`FAILED to connect to the db: ${error}`); resolve(false); } else { connection.end((error : any) => { if (error) { console.error( `FAILED to end connection to the db: ${error}` ); resolve(false); } else { console.log(`SUCCESS connected to db!`); resolve(true); } }); } }); }); if (ok) return; console.log(`Going to sleep for ${SLEEP_MS}ms...`); await sleep(SLEEP_MS); } throw new Error(`Failed to connect to db after ${TIMEOUT_MS}ms`); } export async function main(argv : any) { await waitForDB(); // Check if we bootstrapped already if (!argv.force) { if (await isAlreadyBootstrapped()) { console.error(`Almond appears to be already bootstrapped, refusing to bootstrap again.`); await db.tearDown(); return; } } // initialize the schema await execSql.exec(path.resolve(path.dirname(module.filename), '../../model/schema.sql')); // initialize the default data in the database await db.withTransaction(async (dbClient) => { const rootOrg = await createRootOrg(dbClient); await createDefaultUsers(dbClient, rootOrg); if (Config.WITH_LUINET === 'embedded') await importDefaultNLPModels(dbClient, rootOrg); if (Config.WITH_THINGPEDIA === 'embedded') { await importStandardEntities(dbClient); await importStandardStringTypes(dbClient, rootOrg); await importStandardSchemas(dbClient, rootOrg); await importBuiltinDevices(dbClient, rootOrg); } }); await db.tearDown(); }
the_stack
import Sound from "openfl/media/Sound"; import SoundChannel from "openfl/media/SoundChannel"; import SoundTransform from "openfl/media/SoundTransform"; import ByteArray from "openfl/utils/ByteArray"; import Vector from "openfl/Vector"; import EventDispatcher from "./../events/EventDispatcher"; import BitmapFont from "./../text/BitmapFont"; import Texture from "./../textures/Texture"; import TextureAtlas from "./../textures/TextureAtlas"; import TextureOptions from "./../textures/TextureOptions"; import AssetFactory from "./AssetFactory"; import DataLoader from "./DataLoader"; declare namespace starling.assets { /** Dispatched when all textures have been restored after a context loss. */ // @:meta(Event(name="texturesRestored", type="starling.events.Event")) /** The AssetManager handles loading and accessing a variety of asset types. You can * add assets directly (via the 'add...' methods) or asynchronously via a queue. This allows * you to deal with assets in a unified way, no matter if they are loaded from a file, * directory, URL, or from an embedded object. * * <p>The class can deal with the following media types: * <ul> * <li>Texture, either from Bitmaps or ATF data</li> * <li>Texture atlases</li> * <li>Bitmap Fonts</li> * <li>Sounds</li> * <li>XML data</li> * <li>JSON data</li> * <li>ByteArrays</li> * <li>other AssetManagers</li> * </ul> * </p> * * <p>For more information on how to add assets from different sources, read the documentation * of the "enqueue()" method.</p> * * <strong>Context Loss</strong> * * <p>When the stage3D context is lost, the AssetManager will automatically restore all * loaded textures. To save memory, it will get them from their original sources. Since * this is done asynchronously, your images might not reappear all at once, but during * a time frame of several seconds. If you want, you can pause your game during that time; * the AssetManager dispatches an "Event.TEXTURES_RESTORED" event when all textures have * been restored.</p> * * <strong>Error Handling</strong> * * <p>Loading of some assets may fail while the queue is being processed. In that case, the * AssetManager will call the 'onError' callback that you can optional provide to the * 'loadQueue' method. Queue processing will continue after an error, so it's always * guaranteed that the 'onComplete' callback is executed, too.</p> * * <strong>Texture Properties</strong> * * <p>When you enqueue a texture, its properties for "format", "scale", "mipMapping", and * "repeat" will reflect the settings of the AssetManager at the time they were enqueued. * This means that you can enqueue a bunch of textures, then change the settings and enqueue * some more. Like this:</p> * * <listing> * appDir:File = File.applicationDirectory; * assets:AssetManager = new AssetManager(); * * assets.textureOptions.format = Context3DTextureFormat.BGRA; * assets.enqueue(appDir.resolvePath("textures/32bit")); * * assets.textureOptions.format = Context3DTextureFormat.BGRA_PACKED; * assets.enqueue(appDir.resolvePath("textures/16bit")); * * assets.loadQueue(...);</listing> * * <strong>Nesting</strong> * * <p>When you enqueue one or more AssetManagers to another one, the "loadQueue" method will * oad the Assets of the "child" AssetManager, as well. Later, when accessing assets, * the "parent" AssetManager will return the "child" assets as well - just like it returns, * say, the SubTextures from a contained TextureAtlas.</p> * * <p>The main advantage of grouping your assets like this is something else, though: it * allows to remove (and dispose) a complete group of assets in one step. The example * below loads the assets from two directories. When the contents of one of them are no * longer needed, all its assets are removed together.</p> * * <listing> * manager:AssetManager = new AssetManager(); * appDir:File = File.applicationDirectory; * * redAssets:AssetManager = new AssetManager(); * manager.enqueueSingle(appDir.resolvePath("textures/red/", "redAssets"); * * greenAssets:AssetManager = new AssetManager(); * manager.enqueueSingle(appDir.resolvePath("textures/green/", "greenAssets"); * * manager.loadQueue(...); // loads both "red" and "green" assets * * // ... later, remove all "red" assets together * manager.removeAssetManager("redAssets");</listing> * * <strong>Customization</strong> * * <p>You can customize how assets are created by extending the 'AssetFactory' class and * registering an instance of your new class at the AssetManager via 'registerFactory'. * Factories are probed by priority; any factory with a priority > 0 will be executed * before the built-in factories.</p> * * <p>An asset type is identified by a unique String. You can add your own asset types * by creating a custom 'AssetFactory' and having it add the asset with custom string * identifier.</p> * * <p>By overriding the methods 'getNameFromUrl', 'getExtensionFromUrl', 'disposeAsset', * and 'log', you can customize how assets are named and disposed, and you can forward * any logging to an external logger. To customize the way data is loaded from URLs or * files, you can assign a custom 'DataLoader' instance to the AssetManager.</p> * * @see starling.assets.AssetFactory * @see starling.assets.AssetType * @see starling.assets.DataLoader */ export class AssetManager extends EventDispatcher { /** Create a new instance with the given scale factor. */ public constructor(scaleFactor?:number); /** Disposes all assets and purges the queue. * * <p>Beware that all references to the assets will remain intact, even though the assets * are no longer valid. Call 'purge' if you want to remove all resources and reuse * the AssetManager later.</p> */ public dispose():void; /** Removes assets of all types (disposing them along the way), empties the queue and * aborts any pending load operations. */ public purge():void; // queue processing /** Enqueues one or more raw assets; they will only be available after successfully * executing the "loadQueue" method. This method accepts a variety of different objects: * * <ul> * <li>Strings or URLRequests containing an URL to a local or remote resource. Supported * types: <code>png, jpg, gif, atf, mp3, xml, fnt, json, binary</code>.</li> * <li>Instances of the File class (AIR only) pointing to a directory or a file. * Directories will be scanned recursively for all supported types.</li> * <li>Classes that contain <code>static</code> embedded assets.</li> * <li>If the file extension is not recognized, the data is analyzed to see if * contains XML or JSON data. If it's neither, it is stored as ByteArray.</li> * </ul> * * <p>Suitable object names are extracted automatically: A file named "image.png" will be * accessible under the name "image". When enqueuing embedded assets via a class, * the variable name of the embedded object will be used as its name. An exception * are texture atlases: they will have the same name as the actual texture they are * referencing.</p> * * <p>XMLs are made available via "getXml()"; this includes XMLs containing texture * atlases or bitmap fonts, which are processed along the way. Bitmap fonts are also * registered at the TextField class.</p> * * <p>If you pass in JSON data, it will be parsed into an object and will be available via * "getObject()".</p> */ public enqueue(assets:Array<any>):void; /** Enqueues a single asset with a custom name that can be used to access it later. * If the asset is a texture, you can also add custom texture options. * * @param asset The asset that will be enqueued; accepts the same objects as the * 'enqueue' method. * @param name The name under which the asset will be found later. If you pass null or * omit the parameter, it's attempted to generate a name automatically. * @param options Custom options that will be used if 'asset' points to texture data. * @return the name with which the asset was registered. */ public enqueueSingle(asset:any, name?:string, options?:TextureOptions):string; /** Empties the queue and aborts any pending load operations. */ public purgeQueue():void; /** Loads all enqueued assets asynchronously. The 'onComplete' callback will be executed * once all assets have been loaded - even when there have been errors, which are * forwarded to the optional 'onError' callback. The 'onProgress' will be called * with a 'ratio' between '0.0' and '1.0' and is also optional. * * <p>When you call this method, the manager will save a reference to "Starling.current"; * all textures that are loaded will be accessible only from within this instance. Thus, * if you are working with more than one Starling instance, be sure to call * "makeCurrent()" on the appropriate instance before processing the queue.</p> * * @param onComplete <code>function(manager:AssetManager):void;</code> - parameter is optional! * @param onError <code>function(error:string):void;</code> * @param onProgress <code>function(ratio:Number):void;</code> */ public loadQueue(onComplete:()=>void, onError?:(string)=>void, onProgress?:(number)=>void):void; // basic accessing methods /** Add an asset with a certain name and type. * * <p>Beware: if the slot (name + type) was already taken, the existing object will be * disposed and replaced by the new one.</p> * * @param name The name with which the asset can be retrieved later. Must be * unique within this asset type. * @param asset The actual asset to add (e.g. a texture, a sound, etc). * @param type The type of the asset. If omitted, the type will be determined * automatically (which works for all standard types defined within * the 'AssetType' class). */ public addAsset(name:string, asset:any, type?:string):void; /** Retrieves an asset of the given type, with the given name. If 'recursive' is true, * the method will traverse included texture atlases and asset managers. * * <p>Typically, you will use one of the type-safe convenience methods instead, like * 'getTexture', 'getSound', etc.</p> */ public getAsset(type:string, name:string, recursive?:boolean):any; /** Retrieves an alphabetically sorted list of all assets that have the given type and * start with the given prefix. If 'recursive' is true, the method will traverse included * texture atlases and asset managers. */ public getAssetNames(assetType:string, prefix?:string, recursive?:boolean, out?:Vector<string>):Vector<string>; /** Removes the asset with the given name and type, and will optionally dispose it. */ public removeAsset(assetType:string, name:string, dispose?:boolean):void; // convenience access methods /** Returns a texture with a certain name. Includes textures stored inside atlases. */ public getTexture(name:string):Texture; /** Returns all textures that start with a certain string, sorted alphabetically * (especially useful for "MovieClip"). Includes textures stored inside atlases. */ public getTextures(prefix?:string, out?:Vector<Texture>):Vector<Texture>; /** Returns all texture names that start with a certain string, sorted alphabetically. * Includes textures stored inside atlases. */ public getTextureNames(prefix?:string, out?:Vector<string>):Vector<string>; /** Returns a texture atlas with a certain name, or null if it's not found. */ public getTextureAtlas(name:string):TextureAtlas; /** Returns all texture atlas names that start with a certain string, sorted alphabetically. * If you pass an <code>out</code>-vector, the names will be added to that vector. */ public getTextureAtlasNames(prefix?:string, out?:Vector<string>):Vector<string>; /** Returns a sound with a certain name, or null if it's not found. */ public getSound(name:string):Sound; /** Returns all sound names that start with a certain string, sorted alphabetically. * If you pass an <code>out</code>-vector, the names will be added to that vector. */ public getSoundNames(prefix?:string, out?:Vector<string>):Vector<string>; /** Generates a new SoundChannel object to play back the sound. This method returns a * SoundChannel object, which you can access to stop the sound and to control volume. */ public playSound(name:string, startTime?:number, loops?:number, transform?:SoundTransform):SoundChannel; /** Returns an XML with a certain name, or null if it's not found. */ public getXml(name:string):any/*Xml*/; /** Returns all XML names that start with a certain string, sorted alphabetically. * If you pass an <code>out</code>-vector, the names will be added to that vector. */ public getXmlNames(prefix?:string, out?:Vector<string>):Vector<string>; /** Returns an object with a certain name, or null if it's not found. Enqueued JSON * data is parsed and can be accessed with this method. */ public getObject(name:string):any; /** Returns all object names that start with a certain string, sorted alphabetically. * If you pass an <code>out</code>-vector, the names will be added to that vector. */ public getObjectNames(prefix?:string, out?:Vector<string>):Vector<string>; /** Returns a byte array with a certain name, or null if it's not found. */ public getByteArray(name:string):ByteArray; /** Returns all byte array names that start with a certain string, sorted alphabetically. * If you pass an <code>out</code>-vector, the names will be added to that vector. */ public getByteArrayNames(prefix?:string, out?:Vector<string>):Vector<string>; /** Returns a bitmap font with a certain name, or null if it's not found. */ public getBitmapFont(name:string):BitmapFont; /** Returns all bitmap font names that start with a certain string, sorted alphabetically. * If you pass an <code>out</code>-vector, the names will be added to that vector. */ public getBitmapFontNames(prefix?:string, out?:Vector<string>):Vector<string>; /** Returns an asset manager with a certain name, or null if it's not found. */ public getAssetManager(name:string):AssetManager; /** Returns all asset manager names that start with a certain string, sorted alphabetically. * If you pass an <code>out</code>-vector, the names will be added to that vector. */ public getAssetManagerNames(prefix?:string, out?:Vector<string>):Vector<string>; /** Removes a certain texture, optionally disposing it. */ public removeTexture(name:string, dispose?:boolean):void; /** Removes a certain texture atlas, optionally disposing it. */ public removeTextureAtlas(name:string, dispose?:boolean):void; /** Removes a certain sound. */ public removeSound(name:string):void; /** Removes a certain Xml object, optionally disposing it. */ public removeXml(name:string, dispose?:boolean):void; /** Removes a certain object. */ public removeObject(name:string):void; /** Removes a certain byte array, optionally disposing its memory right away. */ public removeByteArray(name:string, dispose?:boolean):void; /** Removes a certain bitmap font, optionally disposing it. */ public removeBitmapFont(name:string, dispose?:boolean):void; /** Removes a certain asset manager and optionally disposes it right away. */ public removeAssetManager(name:string, dispose?:boolean):void; // registration of factories /** Registers a custom AssetFactory. If you use any priority > 0, the factory will * be called before the default factories. The final factory to be invoked is the * 'ByteArrayFactory', which is using a priority of '-100'. */ public registerFactory(factory:AssetFactory, priority?:number):void; // properties /** When activated, the class will trace information about added/enqueued assets. * @default true */ public verbose:boolean; protected get_verbose():boolean; protected set_verbose(value:boolean):boolean; /** Returns the number of raw assets that have been enqueued, but not yet loaded. */ public readonly numQueuedAssets:number; protected get_numQueuedAssets():number; /** The maximum number of parallel connections that are spawned when loading the queue. * More connections can reduce loading times, but require more memory. @default 3. */ public numConnections:number; protected get_numConnections():number; protected set_numConnections(value:number):number; /** Textures will be created with the options set up in this object at the time of * enqueuing. */ public textureOptions:TextureOptions; protected get_textureOptions():TextureOptions; protected set_textureOptions(value:TextureOptions):TextureOptions; /** The DataLoader is used to load any data from files or URLs. If you need to customize * its behavior (e.g. to add a caching mechanism), assign your custom instance here. */ public dataLoader:DataLoader; protected get_dataLoader():DataLoader; protected set_dataLoader(value:DataLoader):DataLoader; /** Indicates if bitmap fonts should be registered with their "face" attribute from the * font XML file. Per default, they are registered with the name of the texture file. * @default false */ public registerBitmapFontsWithFontFace:boolean; protected get_registerBitmapFontsWithFontFace():boolean; protected set_registerBitmapFontsWithFontFace(value:boolean):boolean; } export class AssetPostProcessor { public constructor(callback:(AssetManager)=>void, priority:number); public readonly priority:number; protected get_priority():number; } } export default starling.assets.AssetManager;
the_stack
import { assert, expect } from "chai"; import { SchemaContext } from "../../Context"; import { ECObjectsError } from "../../Exception"; import { Phenomenon } from "../../Metadata/Phenomenon"; import { Schema } from "../../Metadata/Schema"; import { Unit } from "../../Metadata/Unit"; import { UnitSystem } from "../../Metadata/UnitSystem"; import { createSchemaJsonWithItems } from "../TestUtils/DeserializationHelpers"; import { createEmptyXmlDocument } from "../TestUtils/SerializationHelper"; /* eslint-disable @typescript-eslint/naming-convention */ describe("Unit", () => { function createSchemaJson(unitJson: any): any { return createSchemaJsonWithItems({ TestUnit: { schemaItemType: "Unit", ...unitJson, }, TestPhenomenon: { schemaItemType: "Phenomenon", definition: "LENGTH(1)", }, TestUnitSystem: { schemaItemType: "UnitSystem", }, }); } it("should get fullName", async () => { const fullyDefinedUnit = createSchemaJson({ label: "Millimeter", description: "A unit defining the millimeter metric unit of length", phenomenon: "TestSchema.TestPhenomenon", unitSystem: "TestSchema.TestUnitSystem", definition: "[MILLI]*Units.MM", numerator: 5, denominator: 1, offset: 4, }); const ecSchema = await Schema.fromJson(fullyDefinedUnit, new SchemaContext()); assert.isDefined(ecSchema); const unit = await ecSchema.getItem<Unit>("TestUnit"); assert.isDefined(unit); expect(unit!.fullName).eq("TestSchema.TestUnit"); }); describe("deserialization", () => { const fullyDefinedUnit = createSchemaJson({ label: "Millimeter", description: "A unit defining the millimeter metric unit of length", phenomenon: "TestSchema.TestPhenomenon", unitSystem: "TestSchema.TestUnitSystem", definition: "[MILLI]*Units.MM", numerator: 5, denominator: 1, offset: 4, }); it("async - should succeed with fully defined", async () => { const ecSchema = await Schema.fromJson(fullyDefinedUnit, new SchemaContext()); const unit = await ecSchema.getItem<Unit>("TestUnit"); assert.isDefined(unit); const phen = await ecSchema.getItem<Phenomenon>("TestPhenomenon"); assert.isDefined(phen); assert.isTrue((await unit!.phenomenon) === phen); const unitSystem = await ecSchema.getItem<UnitSystem>("TestUnitSystem"); assert.isDefined(unitSystem); assert.isTrue((await unit!.unitSystem) === unitSystem); expect(unit!.definition).to.eql("[MILLI]*Units.MM"); expect(unit!.denominator).to.equal(1); expect(unit!.numerator).to.equal(5); expect(unit!.offset).to.equal(4); }); it("sync - should succeed with fully defined", () => { const ecSchema = Schema.fromJsonSync(fullyDefinedUnit, new SchemaContext()); const unit = ecSchema.getItemSync<Unit>("TestUnit"); assert.isDefined(unit); const phen = ecSchema.getItemSync<Phenomenon>("TestPhenomenon"); assert.isDefined(phen); assert.strictEqual(phen, ecSchema.getItemSync<Phenomenon>(unit!.phenomenon!.name)); const unitSystem = ecSchema.getItemSync<UnitSystem>("TestUnitSystem"); assert.isDefined(unitSystem); assert.strictEqual(unitSystem, ecSchema.getItemSync<UnitSystem>(unit!.unitSystem!.name)); expect(unit!.definition).to.eql("[MILLI]*Units.MM"); expect(unit!.denominator).to.equal(1); expect(unit!.numerator).to.equal(5); expect(unit!.offset).to.equal(4); }); // Check order of schema items shouldn't matter const reverseOrderJson = createSchemaJsonWithItems({ M: { schemaItemType: "Unit", phenomenon: "TestSchema.Length", unitSystem: "TestSchema.Metric", definition: "[MILLI]*M", }, Length: { schemaItemType: "Phenomenon", definition: "LENGTH(1)", label: "length", }, Metric: { schemaItemType: "UnitSystem", label: "metric", }, }); it("async - order shouldn't matter", async () => { const ecSchema = await Schema.fromJson(reverseOrderJson, new SchemaContext()); assert.isDefined(ecSchema); assert.isDefined(await ecSchema.getItem<Phenomenon>("Length")); assert.isDefined(await ecSchema.getItem<UnitSystem>("Metric")); assert.isDefined(await ecSchema.getItem<Unit>("M")); }); it("sync - should succeed with dependency order", () => { const ecSchema = Schema.fromJsonSync(reverseOrderJson, new SchemaContext()); assert.isDefined(ecSchema); assert.isDefined(ecSchema.getItemSync<Phenomenon>("Length")); assert.isDefined(ecSchema.getItemSync<UnitSystem>("Metric")); assert.isDefined(ecSchema.getItemSync<Unit>("M")); }); // Missing phenomenon const missingPhenomenonJson = { unitSystem: "TestSchema.TestUnitSystem", definition: "[MILLI]*Units.M", }; it("async - should throw for missing phenomenon", async () => { await expect(Schema.fromJson(createSchemaJson(missingPhenomenonJson), new SchemaContext())).to.be.rejectedWith(ECObjectsError, `The Unit TestSchema.TestUnit does not have the required 'phenomenon' attribute.`); }); it("sync - should throw for missing phenomenon", () => { assert.throws(() => Schema.fromJsonSync(createSchemaJson(missingPhenomenonJson), new SchemaContext()), ECObjectsError, `The Unit TestSchema.TestUnit does not have the required 'phenomenon' attribute.`); }); // Invalid phenomenon const invalidPhenomenonJson = { phenomenon: 5, unitSystem: "TestSchema.TestUnitSystem", definition: "[MILLI]*Units.M", }; it("async - should throw for invalid phenomenon", async () => { await expect(Schema.fromJson(createSchemaJson(invalidPhenomenonJson), new SchemaContext())).to.be.rejectedWith(ECObjectsError, `The Unit TestSchema.TestUnit has an invalid 'phenomenon' attribute. It should be of type 'string'`); }); it("sync - should throw for invalid phenomenon", () => { assert.throws(() => Schema.fromJsonSync(createSchemaJson(invalidPhenomenonJson), new SchemaContext()), ECObjectsError, `The Unit TestSchema.TestUnit has an invalid 'phenomenon' attribute. It should be of type 'string'`); }); // Missing UnitSystem const missingUnitSystemJson = { phenomenon: "TestSchema.TestPhenomenon", definition: "[MILLI]*Units.M", }; it("async - should throw for missing unit system", async () => { await expect(Schema.fromJson(createSchemaJson(missingUnitSystemJson), new SchemaContext())).to.be.rejectedWith(ECObjectsError, `The Unit TestSchema.TestUnit does not have the required 'unitSystem' attribute.`); }); it("sync - should throw for missing unit system", () => { assert.throws(() => Schema.fromJsonSync(createSchemaJson(missingUnitSystemJson), new SchemaContext()), ECObjectsError, `The Unit TestSchema.TestUnit does not have the required 'unitSystem' attribute.`); }); // Invalid UnitSystem const invalidUnitSystemJson = { unitSystem: 5, phenomenon: "TestSchema.TestPhenomenon", definition: "[MILLI]*Units.M", }; it("async - should throw for invalid unit system", async () => { await expect(Schema.fromJson(createSchemaJson(invalidUnitSystemJson), new SchemaContext())).to.be.rejectedWith(ECObjectsError, `The Unit TestSchema.TestUnit has an invalid 'unitSystem' attribute. It should be of type 'string'`); }); it("sync - should throw for invalid unit system", () => { assert.throws(() => Schema.fromJsonSync(createSchemaJson(invalidUnitSystemJson), new SchemaContext()), ECObjectsError, `The Unit TestSchema.TestUnit has an invalid 'unitSystem' attribute. It should be of type 'string'`); }); // Missing Definition const missingDefinitionJson = { phenomenon: "TestSchema.TestPhenomenon", unitSystem: "TestSchema.TestUnitSystem", }; it("async - should throw for missing definition", async () => { await expect(Schema.fromJson(createSchemaJson(missingDefinitionJson), new SchemaContext())).to.be.rejectedWith(ECObjectsError, `The Unit TestSchema.TestUnit does not have the required 'definition' attribute.`); }); it("sync - should throw for missing definition", () => { assert.throws(() => Schema.fromJsonSync(createSchemaJson(missingDefinitionJson), new SchemaContext()), ECObjectsError, `The Unit TestSchema.TestUnit does not have the required 'definition' attribute.`); }); // Missing Definition const invalidDefinitionJson = { definition: 5, phenomenon: "TestSchema.TestPhenomenon", unitSystem: "TestSchema.TestUnitSystem", }; it("async - should throw for invalid definition", async () => { await expect(Schema.fromJson(createSchemaJson(invalidDefinitionJson), new SchemaContext())).to.be.rejectedWith(ECObjectsError, `The Unit TestSchema.TestUnit has an invalid 'definition' attribute. It should be of type 'string'`); }); it("sync - should throw for invalid definition", () => { assert.throws(() => Schema.fromJsonSync(createSchemaJson(invalidDefinitionJson), new SchemaContext()), ECObjectsError, `The Unit TestSchema.TestUnit has an invalid 'definition' attribute. It should be of type 'string'`); }); // Invalid numerator const invalidNumeratorJson = { phenomenon: "TestSchema.TestPhenomenon", unitSystem: "TestSchema.TestUnitSystem", definition: "[MILLI]*Units.MM", numerator: "5", }; it("async - should throw for invalid numerator", async () => { await expect(Schema.fromJson(createSchemaJson(invalidNumeratorJson), new SchemaContext())).to.be.rejectedWith(ECObjectsError, `The Unit TestSchema.TestUnit has an invalid 'numerator' attribute. It should be of type 'number'.`); }); it("sync - should throw for invalid numerator", () => { assert.throws(() => Schema.fromJsonSync(createSchemaJson(invalidNumeratorJson), new SchemaContext()), ECObjectsError, `The Unit TestSchema.TestUnit has an invalid 'numerator' attribute. It should be of type 'number'.`); }); // Invalid denominator const invalidDenominatorJson = { phenomenon: "TestSchema.TestPhenomenon", unitSystem: "TestSchema.TestUnitSystem", definition: "[MILLI]*Units.MM", denominator: "5", }; it("async - should throw for invalid denominator", async () => { await expect(Schema.fromJson(createSchemaJson(invalidDenominatorJson), new SchemaContext())).to.be.rejectedWith(ECObjectsError, `The Unit TestSchema.TestUnit has an invalid 'denominator' attribute. It should be of type 'number'.`); }); it("sync - should throw for invalid denominator", () => { assert.throws(() => Schema.fromJsonSync(createSchemaJson(invalidDenominatorJson), new SchemaContext()), ECObjectsError, `The Unit TestSchema.TestUnit has an invalid 'denominator' attribute. It should be of type 'number'.`); }); // Invalid offset const invalidOffsetJson = { phenomenon: "TestSchema.TestPhenomenon", unitSystem: "TestSchema.TestUnitSystem", definition: "[MILLI]*Units.MM", offset: "5", }; it("async - should throw for invalid offset", async () => { await expect(Schema.fromJson(createSchemaJson(invalidOffsetJson), new SchemaContext())).to.be.rejectedWith(ECObjectsError, `The Unit TestSchema.TestUnit has an invalid 'offset' attribute. It should be of type 'number'.`); }); it("sync - should throw for invalid offset", () => { assert.throws(() => Schema.fromJsonSync(createSchemaJson(invalidOffsetJson), new SchemaContext()), ECObjectsError, `The Unit TestSchema.TestUnit has an invalid 'offset' attribute. It should be of type 'number'.`); }); }); describe("toJSON", () => { const fullyDefinedUnit = createSchemaJson({ label: "Millimeter", description: "A unit defining the millimeter metric unit of length", phenomenon: "TestSchema.TestPhenomenon", unitSystem: "TestSchema.TestUnitSystem", definition: "[MILLI]*Units.MM", numerator: 5, denominator: 1, offset: 4, }); it("async - should succeed with fully defined", async () => { const ecSchema = await Schema.fromJson(fullyDefinedUnit, new SchemaContext()); const unit = await ecSchema.getItem<Unit>("TestUnit"); assert.isDefined(unit); const unitSerialization = unit!.toJSON(true, true); expect(unitSerialization.phenomenon).to.eql("TestSchema.TestPhenomenon"); expect(unitSerialization.unitSystem).to.eql("TestSchema.TestUnitSystem"); expect(unitSerialization.definition).to.eql("[MILLI]*Units.MM"); expect(unitSerialization.denominator).to.equal(1); expect(unitSerialization.numerator).to.equal(5); expect(unitSerialization.offset).to.equal(4); }); it("sync - should succeed with fully defined", () => { const ecSchema = Schema.fromJsonSync(fullyDefinedUnit, new SchemaContext()); const unit = ecSchema.getItemSync<Unit>("TestUnit"); assert.isDefined(unit); const unitSerialization = unit!.toJSON(true, true); expect(unitSerialization.phenomenon).to.eql("TestSchema.TestPhenomenon"); expect(unitSerialization.unitSystem).to.eql("TestSchema.TestUnitSystem"); expect(unitSerialization.definition).to.eql("[MILLI]*Units.MM"); expect(unitSerialization.denominator).to.equal(1); expect(unitSerialization.numerator).to.equal(5); expect(unitSerialization.offset).to.equal(4); }); it("async - JSON stringify serialization, should succeed with fully defined", async () => { const ecSchema = await Schema.fromJson(fullyDefinedUnit, new SchemaContext()); const unit = await ecSchema.getItem<Unit>("TestUnit"); assert.isDefined(unit); const json = JSON.stringify(unit); const unitSerialization = JSON.parse(json); expect(unitSerialization.phenomenon).to.eql("TestSchema.TestPhenomenon"); expect(unitSerialization.unitSystem).to.eql("TestSchema.TestUnitSystem"); expect(unitSerialization.definition).to.eql("[MILLI]*Units.MM"); expect(unitSerialization.denominator).to.equal(1); expect(unitSerialization.numerator).to.equal(5); expect(unitSerialization.offset).to.equal(4); }); it("sync - JSON stringify serialization, should succeed with fully defined", () => { const ecSchema = Schema.fromJsonSync(fullyDefinedUnit, new SchemaContext()); const unit = ecSchema.getItemSync<Unit>("TestUnit"); assert.isDefined(unit); const json = JSON.stringify(unit); const unitSerialization = JSON.parse(json); expect(unitSerialization.phenomenon).to.eql("TestSchema.TestPhenomenon"); expect(unitSerialization.unitSystem).to.eql("TestSchema.TestUnitSystem"); expect(unitSerialization.definition).to.eql("[MILLI]*Units.MM"); expect(unitSerialization.denominator).to.equal(1); expect(unitSerialization.numerator).to.equal(5); expect(unitSerialization.offset).to.equal(4); }); // Check order of schema items shouldn't matter const reverseOrderJson = createSchemaJsonWithItems({ M: { schemaItemType: "Unit", phenomenon: "TestSchema.Length", unitSystem: "TestSchema.Metric", definition: "[MILLI]*M", }, Length: { schemaItemType: "Phenomenon", definition: "LENGTH(1)", label: "length", }, Metric: { schemaItemType: "UnitSystem", label: "metric", }, }); it("async - order shouldn't matter", async () => { const ecSchema = await Schema.fromJson(reverseOrderJson, new SchemaContext()); assert.isDefined(ecSchema); const unit = await ecSchema.getItem<Unit>("M"); assert.isDefined(unit); const unitSerialization = unit!.toJSON(true, true); expect(unitSerialization.phenomenon).to.eql("TestSchema.Length"); expect(unitSerialization.unitSystem).to.eql("TestSchema.Metric"); expect(unitSerialization.definition).to.eql("[MILLI]*M"); }); it("sync - should succeed with dependency order", () => { const ecSchema = Schema.fromJsonSync(reverseOrderJson, new SchemaContext()); assert.isDefined(ecSchema); const unit = ecSchema.getItemSync<Unit>("M"); assert.isDefined(unit); const unitSerialization = unit!.toJSON(true, true); expect(unitSerialization.phenomenon).to.eql("TestSchema.Length"); expect(unitSerialization.unitSystem).to.eql("TestSchema.Metric"); expect(unitSerialization.definition).to.eql("[MILLI]*M"); }); }); describe("toXml", () => { const newDom = createEmptyXmlDocument(); const schemaJson = createSchemaJson({ label: "Millimeter", description: "A unit defining the millimeter metric unit of length", phenomenon: "TestSchema.TestPhenomenon", unitSystem: "TestSchema.TestUnitSystem", definition: "[MILLI]*Units.MM", numerator: 5.1, denominator: 2.4, offset: 4, }); it("should properly serialize", async () => { const ecschema = await Schema.fromJson(schemaJson, new SchemaContext()); const unit = await ecschema.getItem<Unit>("TestUnit"); assert.isDefined(unit); const serialized = await unit!.toXml(newDom); expect(serialized.nodeName).to.eql("Unit"); expect(serialized.getAttribute("typeName")).to.eql("TestUnit"); expect(serialized.getAttribute("phenomenon")).to.eql("TestPhenomenon"); expect(serialized.getAttribute("unitSystem")).to.eql("TestUnitSystem"); expect(serialized.getAttribute("definition")).to.eql("[MILLI]*Units.MM"); expect(serialized.getAttribute("numerator")).to.eql("5.1"); expect(serialized.getAttribute("denominator")).to.eql("2.4"); expect(serialized.getAttribute("offset")).to.eql("4"); }); }); });
the_stack
import * as coreHttp from "@azure/core-http"; export const KeyListResult: coreHttp.CompositeMapper = { type: { name: "Composite", className: "KeyListResult", modelProperties: { items: { serializedName: "items", type: { name: "Sequence", element: { type: { name: "Composite", className: "Key" } } } }, nextLink: { serializedName: "@nextLink", type: { name: "String" } } } } }; export const Key: coreHttp.CompositeMapper = { type: { name: "Composite", className: "Key", modelProperties: { name: { serializedName: "name", readOnly: true, type: { name: "String" } } } } }; export const ErrorModel: coreHttp.CompositeMapper = { type: { name: "Composite", className: "ErrorModel", modelProperties: { type: { serializedName: "type", type: { name: "String" } }, title: { serializedName: "title", type: { name: "String" } }, name: { serializedName: "name", type: { name: "String" } }, detail: { serializedName: "detail", type: { name: "String" } }, status: { serializedName: "status", type: { name: "Number" } } } } }; export const KeyValueListResult: coreHttp.CompositeMapper = { type: { name: "Composite", className: "KeyValueListResult", modelProperties: { items: { serializedName: "items", type: { name: "Sequence", element: { type: { name: "Composite", className: "ConfigurationSetting" } } } }, nextLink: { serializedName: "@nextLink", type: { name: "String" } } } } }; export const ConfigurationSetting: coreHttp.CompositeMapper = { type: { name: "Composite", className: "ConfigurationSetting", modelProperties: { key: { serializedName: "key", required: true, type: { name: "String" } }, label: { serializedName: "label", type: { name: "String" } }, contentType: { serializedName: "content_type", type: { name: "String" } }, value: { serializedName: "value", type: { name: "String" } }, lastModified: { serializedName: "last_modified", type: { name: "DateTime" } }, tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } }, isReadOnly: { serializedName: "locked", type: { name: "Boolean" } }, etag: { serializedName: "etag", type: { name: "String" } } } } }; export const LabelListResult: coreHttp.CompositeMapper = { type: { name: "Composite", className: "LabelListResult", modelProperties: { items: { serializedName: "items", type: { name: "Sequence", element: { type: { name: "Composite", className: "Label" } } } }, nextLink: { serializedName: "@nextLink", type: { name: "String" } } } } }; export const Label: coreHttp.CompositeMapper = { type: { name: "Composite", className: "Label", modelProperties: { name: { serializedName: "name", readOnly: true, type: { name: "String" } } } } }; export const GeneratedClientGetKeysHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", className: "GeneratedClientGetKeysHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const GeneratedClientCheckKeysHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", className: "GeneratedClientCheckKeysHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const GeneratedClientGetKeyValuesHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", className: "GeneratedClientGetKeyValuesHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const GeneratedClientCheckKeyValuesHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", className: "GeneratedClientCheckKeyValuesHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const GeneratedClientGetKeyValueHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", className: "GeneratedClientGetKeyValueHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } }, eTag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "String" } } } } }; export const GeneratedClientPutKeyValueHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", className: "GeneratedClientPutKeyValueHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } }, eTag: { serializedName: "etag", type: { name: "String" } } } } }; export const GeneratedClientDeleteKeyValueHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", className: "GeneratedClientDeleteKeyValueHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } }, eTag: { serializedName: "etag", type: { name: "String" } } } } }; export const GeneratedClientCheckKeyValueHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", className: "GeneratedClientCheckKeyValueHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } }, eTag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "String" } } } } }; export const GeneratedClientGetLabelsHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", className: "GeneratedClientGetLabelsHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const GeneratedClientCheckLabelsHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", className: "GeneratedClientCheckLabelsHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const GeneratedClientPutLockHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", className: "GeneratedClientPutLockHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } }, eTag: { serializedName: "etag", type: { name: "String" } } } } }; export const GeneratedClientDeleteLockHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", className: "GeneratedClientDeleteLockHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } }, eTag: { serializedName: "etag", type: { name: "String" } } } } }; export const GeneratedClientGetRevisionsHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", className: "GeneratedClientGetRevisionsHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const GeneratedClientCheckRevisionsHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", className: "GeneratedClientCheckRevisionsHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const GeneratedClientGetKeysNextHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", className: "GeneratedClientGetKeysNextHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const GeneratedClientGetKeyValuesNextHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", className: "GeneratedClientGetKeyValuesNextHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const GeneratedClientGetLabelsNextHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", className: "GeneratedClientGetLabelsNextHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const GeneratedClientGetRevisionsNextHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", className: "GeneratedClientGetRevisionsNextHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } };
the_stack
import { render, cleanup, PLACEMENTS_NO_CENTER, ExpectBoundsProps, fixViewport } from "./util"; import { Placement } from "../../src"; import { constants } from "../../sandbox/constants"; before(fixViewport); describe("e2e/no-overflow-container", () => { afterEach(cleanup); it("tracks the triggers position", async () => { const tools = render({ overflowContainer: false }); // open the layer tools.clickTrigger(); /** * ---------------------- * | | * | layer | * | | * ---------------------- * * ----------- * | trigger | * ----------- */ await tools.expectBounds({ layerSide: "top", layer: { top: 173, left: 580, bottom: 413, right: 820, width: 240, height: 240 }, arrow: { top: 413, left: 692, bottom: 429, right: 708, width: 16, height: 16 } }); // scroll 100px to bottom tools.scrollContainer(800, 700); /** * ---------------------- * | | * | layer | * | | * ---------------------- * * ----------- * | trigger | * ----------- */ await tools.expectBounds({ layerSide: "top", layer: { top: 73, left: 580, bottom: 313, right: 820, width: 240, height: 240 }, arrow: { top: 313, left: 692, bottom: 329, right: 708, width: 16, height: 16 } }); }); it("tracks the triggers position and adjusts automatically", async () => { const tools = render({ auto: true, overflowContainer: false }); // open the layer tools.clickTrigger(); // scroll to bottom so that "top" fits exacly within window tools.scrollContainer(707, 700); /** * ---------------------- * | | * | layer | * | | * ---------------------- * * ----------- * | trigger | * ----------- */ await tools.expectBounds({ layerSide: "top", layer: { top: 166, left: 580, bottom: 406, right: 820, width: 240, height: 240 }, arrow: { top: 406, left: 692, bottom: 422, right: 708, width: 16, height: 16 } }); // scroll a little bit futher so that layer jumps to another placement tools.scrollContainer(709, 700); /** * ----------- * | trigger | * ----------- * * ---------------------- * | | * | layer | * | | * ---------------------- */ await tools.expectBounds({ layerSide: "bottom", layer: { top: 478, left: 580, bottom: 718, right: 820, width: 240, height: 240 }, arrow: { top: 462, left: 692, bottom: 478, right: 708, width: 16, height: 16 } }); }); it("positions the right placements", async () => { const tools = render({ placement: "bottom-center", overflowContainer: false }); tools.clickTrigger(); const expectedBounds: Record< Exclude<Placement, "center">, ExpectBoundsProps > = { "top-start": { layerSide: "top", layer: { top: 173, left: 650, bottom: 413, right: 890, width: 240, height: 240 }, arrow: { top: 413, left: 692, bottom: 429, right: 708, width: 16, height: 16 } }, "top-center": { layerSide: "top", layer: { top: 173, left: 580, bottom: 413, right: 820, width: 240, height: 240 }, arrow: { top: 413, left: 692, bottom: 429, right: 708, width: 16, height: 16 } }, "top-end": { layerSide: "top", layer: { top: 173, left: 510, bottom: 413, right: 750, width: 240, height: 240 }, arrow: { top: 413, left: 692, bottom: 429, right: 708, width: 16, height: 16 } }, "left-start": { layerSide: "left", layer: { top: 425, left: 398, bottom: 665, right: 638, width: 240, height: 240 }, arrow: { top: 442, left: 638, bottom: 458, right: 654, width: 16, height: 16 } }, "left-center": { layerSide: "left", layer: { top: 330, left: 398, bottom: 570, right: 638, width: 240, height: 240 }, arrow: { top: 442, left: 638, bottom: 458, right: 654, width: 16, height: 16 } }, "left-end": { layerSide: "left", layer: { top: 235, left: 398, bottom: 475, right: 638, width: 240, height: 240 }, arrow: { top: 442, left: 638, bottom: 458, right: 654, width: 16, height: 16 } }, "right-start": { layerSide: "right", layer: { top: 425, left: 762, bottom: 665, right: 1002, width: 240, height: 240 }, arrow: { top: 442, left: 746, bottom: 458, right: 762, width: 16, height: 16 } }, "right-center": { layerSide: "right", layer: { top: 330, left: 762, bottom: 570, right: 1002, width: 240, height: 240 }, arrow: { top: 442, left: 746, bottom: 458, right: 762, width: 16, height: 16 } }, "right-end": { layerSide: "right", layer: { top: 235, left: 762, bottom: 475, right: 1002, width: 240, height: 240 }, arrow: { top: 442, left: 746, bottom: 458, right: 762, width: 16, height: 16 } }, "bottom-start": { layerSide: "bottom", layer: { top: 487, left: 650, bottom: 727, right: 890, width: 240, height: 240 }, arrow: { top: 471, left: 692, bottom: 487, right: 708, width: 16, height: 16 } }, "bottom-center": { layerSide: "bottom", layer: { top: 487, left: 580, bottom: 727, right: 820, width: 240, height: 240 }, arrow: { top: 471, left: 692, bottom: 487, right: 708, width: 16, height: 16 } }, "bottom-end": { layerSide: "bottom", layer: { top: 487, left: 510, bottom: 727, right: 750, width: 240, height: 240 }, arrow: { top: 471, left: 692, bottom: 487, right: 708, width: 16, height: 16 } } }; for (const placement of PLACEMENTS_NO_CENTER) { tools.reRender({ placement, overflowContainer: false }); await tools.expectBounds(expectedBounds[placement]); } }); it("positions the right placements when trigger is bigger", async () => { const tools = render({ placement: "bottom-center", triggerIsBigger: true, overflowContainer: false }); tools.clickTrigger(); const expectedBounds: Record< Exclude<Placement, "center">, ExpectBoundsProps > = { "top-start": { layerSide: "top", layer: { top: 268, left: 580, bottom: 318, right: 680, width: 100, height: 50 }, arrow: { top: 318, left: 622, bottom: 334, right: 638, width: 16, height: 16 } }, "top-center": { layerSide: "top", layer: { top: 268, left: 650, bottom: 318, right: 750, width: 100, height: 50 }, arrow: { top: 318, left: 692, bottom: 334, right: 708, width: 16, height: 16 } }, "top-end": { layerSide: "top", layer: { top: 268, left: 720, bottom: 318, right: 820, width: 100, height: 50 }, arrow: { top: 318, left: 762, bottom: 334, right: 778, width: 16, height: 16 } }, "left-start": { layerSide: "left", layer: { top: 330, left: 468, bottom: 380, right: 568, width: 100, height: 50 }, arrow: { top: 347, left: 568, bottom: 363, right: 584, width: 16, height: 16 } }, "left-center": { layerSide: "left", layer: { top: 425, left: 468, bottom: 475, right: 568, width: 100, height: 50 }, arrow: { top: 442, left: 568, bottom: 458, right: 584, width: 16, height: 16 } }, "left-end": { layerSide: "left", layer: { top: 520, left: 468, bottom: 570, right: 568, width: 100, height: 50 }, arrow: { top: 537, left: 568, bottom: 553, right: 584, width: 16, height: 16 } }, "right-start": { layerSide: "right", layer: { top: 330, left: 832, bottom: 380, right: 932, width: 100, height: 50 }, arrow: { top: 347, left: 816, bottom: 363, right: 832, width: 16, height: 16 } }, "right-center": { layerSide: "right", layer: { top: 425, left: 832, bottom: 475, right: 932, width: 100, height: 50 }, arrow: { top: 442, left: 816, bottom: 458, right: 832, width: 16, height: 16 } }, "right-end": { layerSide: "right", layer: { top: 520, left: 832, bottom: 570, right: 932, width: 100, height: 50 }, arrow: { top: 537, left: 816, bottom: 553, right: 832, width: 16, height: 16 } }, "bottom-start": { layerSide: "bottom", layer: { top: 582, left: 580, bottom: 632, right: 680, width: 100, height: 50 }, arrow: { top: 566, left: 622, bottom: 582, right: 638, width: 16, height: 16 } }, "bottom-center": { layerSide: "bottom", layer: { top: 582, left: 650, bottom: 632, right: 750, width: 100, height: 50 }, arrow: { top: 566, left: 692, bottom: 582, right: 708, width: 16, height: 16 } }, "bottom-end": { layerSide: "bottom", layer: { top: 582, left: 720, bottom: 632, right: 820, width: 100, height: 50 }, arrow: { top: 566, left: 762, bottom: 582, right: 778, width: 16, height: 16 } } }; for (const placement of PLACEMENTS_NO_CENTER) { tools.reRender({ placement, triggerIsBigger: true, overflowContainer: false }); await tools.expectBounds(expectedBounds[placement]); } }); it("handles secondary offsets while preventing to detach the layer from the trigger", async () => { const tools = render({ placement: "bottom-center", auto: true, possiblePlacements: ["bottom-center", "bottom-start", "bottom-end"], overflowContainer: false }); tools.clickTrigger(); // scroll to bottom so layer is positioned all the way to the top tools.scrollContainer(950, 700); /** * ----------- | * | trigger | | * ----------- | * | * ---------------------- | * | | | * | layer | | * | | | * ---------------------- | */ await tools.expectBounds({ layerSide: "bottom", layer: { top: 237, left: 580, bottom: 477, right: 820, width: 240, height: 240 }, arrow: { top: 221, left: 692, bottom: 237, right: 708, width: 16, height: 16 } }); // scroll to left so layer gets "pushed" to the left tools.scrollContainer(950, 500); /** | * ----------- | * | trigger | | * ----------- | * | * ---------------------- | * | | | * | layer | | * | | | * ---------------------- | */ await tools.expectBounds({ layerSide: "bottom", layer: { top: 237, left: 744, bottom: 477, right: 984, width: 240, height: 240 }, arrow: { top: 221, left: 892, bottom: 237, right: 908, width: 16, height: 16 } }); // scroll to left so container-offsets aren't able to be respected // otherwise the layer would detach from its trigger tools.scrollContainer(950, 350); /** | * |----------- * | trigger | * |----------- * | * --------------------|- * | | | * | layer | | * | | | * --------------------|- */ await tools.expectBounds({ layerSide: "bottom", layer: { top: 237, left: 792, bottom: 477, right: 1032, width: 240, height: 240 }, arrow: { top: 221, left: 1008, bottom: 237, right: 1024, width: 16, height: 16 } }); // scroll to right so container-offsets aren't able to be respected // otherwise the layer would detach from its trigger tools.scrollContainer(950, 1060); /** | * ----------| * | trigger || * ----------| * | * |--------------------- * || | * || layer | * || | * |--------------------- */ await tools.expectBounds({ layerSide: "bottom", layer: { top: 237, left: 358, bottom: 477, right: 598, width: 240, height: 240 }, arrow: { top: 221, left: 366, bottom: 237, right: 382, width: 16, height: 16 } }); // Let's try the same with the layer on the right hand side tools.reRender({ placement: "right-center", auto: true, possiblePlacements: ["right-center", "right-start", "right-end"], overflowContainer: false }); // scroll to right so layer is positioned all the way to the left tools.scrollContainer(700, 940); /** * * ---------------------- * ----------- | | * | trigger | | layer | * ----------- | | * ---------------------- * * -------------------------------------------------------------- */ await tools.expectBounds({ layerSide: "right", layer: { top: 330, left: 522, bottom: 570, right: 762, width: 240, height: 240 }, arrow: { top: 442, left: 506, bottom: 458, right: 522, width: 16, height: 16 } }); // scroll to top so layer gets "pushed" to the top tools.scrollContainer(500, 940); /** * * * * * ---------------------- * | | * ----------- | layer | * | trigger | | | * ----------- ---------------------- * -------------------------------------------------------------- */ await tools.expectBounds({ layerSide: "right", layer: { top: 494, left: 522, bottom: 734, right: 762, width: 240, height: 240 }, arrow: { top: 642, left: 506, bottom: 658, right: 522, width: 16, height: 16 } }); // scroll to top so container-offsets aren't able to be respected // otherwise the layer would detach from its trigger tools.scrollContainer(360, 940); /** * * * * * ---------------------- * | | * | layer | * | | * -------------------------------------------------------------- * | trigger | * ----------- */ await tools.expectBounds({ layerSide: "right", layer: { top: 557, left: 522, bottom: 797, right: 762, width: 240, height: 240 }, arrow: { top: 773, left: 506, bottom: 789, right: 522, width: 16, height: 16 } }); // scroll to bottom so container-offsets aren't able to be respected // otherwise the layer would detach from its trigger tools.scrollContainer(1025, 940); /** * * * ----------- * | trigger | * -------------------------------------------------------------- * | | * | layer | * | | * ---------------------- * * */ await tools.expectBounds({ layerSide: "right", layer: { top: 118, left: 522, bottom: 358, right: 762, width: 240, height: 240 }, arrow: { top: 126, left: 506, bottom: 142, right: 522, width: 16, height: 16 } }); }); // This test is exactly the same as above, except for the fact that now the trigger is bigger // and the layer smaller it("handles secondary offsets while preventing to detach the layer from the trigger when trigger is bigger", async () => { const tools = render({ placement: "bottom-center", auto: true, possiblePlacements: ["bottom-center", "bottom-start", "bottom-end"], triggerIsBigger: true, overflowContainer: false }); tools.clickTrigger(); // scroll to bottom so layer is positioned all the way to the top tools.scrollContainer(950, 700); await tools.expectBounds({ layerSide: "bottom", layer: { top: 332, left: 650, bottom: 382, right: 750, width: 100, height: 50 }, arrow: { top: 316, left: 692, bottom: 332, right: 708, width: 16, height: 16 } }); // scroll to left so layer gets "pushed" to the left tools.scrollContainer(950, 420); await tools.expectBounds({ layerSide: "bottom", layer: { top: 332, left: 884, bottom: 382, right: 984, width: 100, height: 50 }, arrow: { top: 316, left: 926, bottom: 332, right: 942, width: 16, height: 16 } }); // scroll to left so container-offsets aren't able to be respected // otherwise the layer would detach from its trigger tools.scrollContainer(950, 275); await tools.expectBounds({ layerSide: "bottom", layer: { top: 332, left: 937, bottom: 382, right: 1037, width: 100, height: 50 }, arrow: { top: 316, left: 1013, bottom: 332, right: 1029, width: 16, height: 16 } }); // scroll to right so container-offsets aren't able to be respected // otherwise the layer would detach from its trigger tools.scrollContainer(950, 1120); await tools.expectBounds({ layerSide: "bottom", layer: { top: 332, left: 368, bottom: 382, right: 468, width: 100, height: 50 }, arrow: { top: 316, left: 376, bottom: 332, right: 392, width: 16, height: 16 } }); // Let's try the same with the layer on the right hand side tools.reRender({ placement: "right-center", auto: true, possiblePlacements: ["right-center", "right-start", "right-end"], triggerIsBigger: true, overflowContainer: false }); // scroll to right so layer is positioned all the way to the left tools.scrollContainer(700, 940); await tools.expectBounds({ layerSide: "right", layer: { top: 425, left: 592, bottom: 475, right: 692, width: 100, height: 50 }, arrow: { top: 442, left: 576, bottom: 458, right: 592, width: 16, height: 16 } }); // scroll to top so layer gets "pushed" to the top tools.scrollContainer(375, 940); await tools.expectBounds({ layerSide: "right", layer: { top: 684, left: 592, bottom: 734, right: 692, width: 100, height: 50 }, arrow: { top: 701, left: 576, bottom: 717, right: 592, width: 16, height: 16 } }); // scroll to top so container-offsets aren't able to be respected // otherwise the layer would detach from its trigger tools.scrollContainer(275, 940); await tools.expectBounds({ layerSide: "right", layer: { top: 737, left: 592, bottom: 787, right: 692, width: 100, height: 50 }, arrow: { top: 763, left: 576, bottom: 779, right: 592, width: 16, height: 16 } }); // scroll to bottom so container-offsets aren't able to be respected // otherwise the layer would detach from its trigger tools.scrollContainer(1125, 940); await tools.expectBounds({ layerSide: "right", layer: { top: 113, left: 592, bottom: 163, right: 692, width: 100, height: 50 }, arrow: { top: 121, left: 576, bottom: 137, right: 592, width: 16, height: 16 } }); }); it("react to scroll events of the window", async () => { const tools = render({ placement: "top-center", auto: true, overflowContainer: false }); tools.clickTrigger(); // scroll window so that the layer has to reposition to the bottom side tools.scrollWindow(170, 0); await tools.expectBounds({ layerSide: "bottom", layer: { top: 317, left: 580, bottom: 557, right: 820, width: 240, height: 240 }, arrow: { top: 301, left: 692, bottom: 317, right: 708, width: 16, height: 16 } }); }); it("snaps between placements when auto & snap are enabled", async () => { const tools = render({ placement: "top-center", auto: true, overflowContainer: false, snap: true }); tools.clickTrigger(); tools.scrollContainer(700, 900); await tools.expectBounds({ layerSide: "top", layer: { top: 173, left: 450, bottom: 413, right: 690, width: 240, height: 240 }, arrow: { top: 413, left: 492, bottom: 429, right: 508, width: 16, height: 16 } }); tools.scrollContainer(700, 530); await tools.expectBounds({ layerSide: "top", layer: { top: 173, left: 680, bottom: 413, right: 920, width: 240, height: 240 }, arrow: { top: 413, left: 862, bottom: 429, right: 878, width: 16, height: 16 } }); }); it("prioritizes correctly based on prefer-y", async () => { const tools = render({ placement: "left-center", auto: true, overflowContainer: false, preferY: "bottom" // default }); tools.clickTrigger(); // since left side did not fit, expect the layer to reside on the bottom await tools.expectBounds({ layerSide: "bottom", layer: { top: 487, left: 510, bottom: 727, right: 750, width: 240, height: 240 }, arrow: { top: 471, left: 692, bottom: 487, right: 708, width: 16, height: 16 } }); tools.reRender({ placement: "left-center", auto: true, overflowContainer: false, preferY: "top" // Now, we change this }); // since we prefer the top-side over bottom, we expect the layer to be positioned on the top side await tools.expectBounds({ layerSide: "top", layer: { top: 173, left: 510, bottom: 413, right: 750, width: 240, height: 240 }, arrow: { top: 413, left: 692, bottom: 429, right: 708, width: 16, height: 16 } }); }); it("reacts to the layerDimensionsProp", async () => { const tools = render({ placement: "left-center", auto: true, overflowContainer: false }); tools.clickTrigger(); // we expect the layer to just not fit on the left side await tools.expectBounds({ layerSide: "bottom", layer: { top: 487, left: 510, bottom: 727, right: 750, width: 240, height: 240 }, arrow: { top: 471, left: 692, bottom: 487, right: 708, width: 16, height: 16 } }); tools.reRender({ placement: "left-center", auto: true, overflowContainer: false, layerDimensions: () => ({ height: constants.layerSize, width: constants.layerSize - 80 // we're tricking here, so that it seems the layer is smaller }) }); // now it will place the layer on the left side await tools.expectBounds({ layerSide: "left", layer: { top: 330, left: 478, bottom: 570, right: 718, width: 240, height: 240 }, arrow: { top: 442, left: 718, bottom: 458, right: 734, width: 16, height: 16 } }); }); });
the_stack
import React, { useEffect, useState } from 'react' import { observer } from 'mobx-react' import { PluginRecord } from '@jbrowse/core/PluginLoader' import { Region } from '@jbrowse/core/util/types' import ViewType from '@jbrowse/core/pluggableElementTypes/ViewType' import PluginManager from '@jbrowse/core/PluginManager' import Plugin from '@jbrowse/core/Plugin' // locals import { createViewState, loadPlugins, JBrowseLinearGenomeView } from '../src' // configs import volvoxConfig from '../public/test_data/volvox/config.json' import volvoxSession from '../public/volvox-session.json' import nextstrainConfig from '../public/nextstrain_covid.json' // eslint-disable-next-line @typescript-eslint/no-explicit-any function addRelativeUris(config: any, baseUri: string) { if (typeof config === 'object') { for (const key of Object.keys(config)) { if (typeof config[key] === 'object') { addRelativeUris(config[key], baseUri) } else if (key === 'uri') { if (!config.baseUri) { config.baseUri = baseUri } } } } } const configPath = 'test_data/volvox/config.json' addRelativeUris(volvoxConfig, new URL(configPath, window.location.href).href) const supportedTrackTypes = [ 'AlignmentsTrack', 'PileupTrack', 'SNPCoverageTrack', 'VariantTrack', 'WiggleTrack', ] const assembly = volvoxConfig.assemblies[0] const tracks = volvoxConfig.tracks.filter(track => supportedTrackTypes.includes(track.type), ) const defaultSession = { name: 'Storybook', view: volvoxConfig.defaultSession.views[0], } const longReadsSession = { ...defaultSession, view: volvoxSession.session.views[0], } export const OneLinearGenomeView = () => { const state = createViewState({ assembly, tracks, defaultSession, // use 1-based coordinates for locstring location: 'ctgA:1105..1221', onChange: patch => { console.log('patch', patch) }, }) return <JBrowseLinearGenomeView viewState={state} /> } export const UsingLocObject = () => { const state = createViewState({ assembly, tracks, defaultSession, // use 0-based coordinates for "location object" here location: { refName: 'ctgA', start: 10000, end: 20000 }, }) return <JBrowseLinearGenomeView viewState={state} /> } export const WithLongReads = () => { const state = createViewState({ assembly, tracks, defaultSession: longReadsSession, location: 'ctgA:1105..1221', }) return <JBrowseLinearGenomeView viewState={state} /> } export const WithOutsideStyling = () => { const state = createViewState({ assembly, tracks, defaultSession, location: 'ctgA:1105..1221', }) return ( <div style={{ textAlign: 'center', fontFamily: 'monospace' }}> <h2> This parent container has textAlign:'center' and a monospace font, but these attributes are not affecting the internal LGV </h2> <JBrowseLinearGenomeView viewState={state} /> </div> ) } export const TwoLinearGenomeViews = () => { const state1 = createViewState({ assembly, tracks, defaultSession, location: 'ctgA:1105..1221', }) const state2 = createViewState({ assembly, tracks, defaultSession: { ...defaultSession, view: { ...defaultSession.view, id: 'linear-genome-view-2' }, }, location: 'ctgA:5560..30589', }) return ( <> <JBrowseLinearGenomeView viewState={state1} /> <JBrowseLinearGenomeView viewState={state2} /> </> ) } export const WithTextSearching = () => { const textSearchConfig = { assembly, aggregateTextSearchAdapters: [ { type: 'TrixTextSearchAdapter', textSearchAdapterId: 'volvox-index', ixFilePath: { uri: 'storybook_data/volvox.ix', locationType: 'UriLocation', }, ixxFilePath: { uri: 'storybook_data/volvox.ixx', locationType: 'UriLocation', }, metaFilePath: { uri: 'storybook_data/volvox_meta.json', locationType: 'UriLocation', }, assemblyNames: ['volvox'], }, ], tracks: [ { type: 'FeatureTrack', trackId: 'gff3tabix_genes', assemblyNames: ['volvox'], name: 'GFF3Tabix genes', category: ['Miscellaneous'], adapter: { type: 'Gff3TabixAdapter', gffGzLocation: { uri: 'volvox.sort.gff3.gz', locationType: 'UriLocation', }, index: { location: { uri: 'volvox.sort.gff3.gz.tbi', locationType: 'UriLocation', }, }, }, }, { type: 'FeatureTrack', trackId: 'single_exon_gene', category: ['Miscellaneous'], name: 'Single exon gene', assemblyNames: ['volvox'], adapter: { type: 'Gff3TabixAdapter', gffGzLocation: { uri: 'single_exon_gene.sorted.gff.gz', locationType: 'UriLocation', }, index: { location: { uri: 'single_exon_gene.sorted.gff.gz.tbi', locationType: 'UriLocation', }, }, }, }, { type: 'VariantTrack', trackId: 'volvox.inv.vcf', name: 'volvox inversions', category: ['VCF'], assemblyNames: ['volvox'], adapter: { type: 'VcfTabixAdapter', vcfGzLocation: { uri: 'volvox.inv.vcf.gz', locationType: 'UriLocation', }, index: { location: { uri: 'volvox.inv.vcf.gz.tbi', locationType: 'UriLocation', }, indexType: 'TBI', }, }, }, ], defaultSession, // use 1-based coordinates for locstring location: 'ctgA:1..800', } addRelativeUris( textSearchConfig, new URL(configPath, window.location.href).href, ) const state = createViewState(textSearchConfig) return <JBrowseLinearGenomeView viewState={state} /> } export const WithPerTrackTextSearching = () => { const textSearchConfig = { assembly, tracks: [ { type: 'FeatureTrack', trackId: 'gff3tabix_genes', assemblyNames: ['volvox'], name: 'GFF3Tabix genes', category: ['Miscellaneous'], adapter: { type: 'Gff3TabixAdapter', gffGzLocation: { uri: 'volvox.sort.gff3.gz', locationType: 'UriLocation', }, index: { location: { uri: 'volvox.sort.gff3.gz.tbi', locationType: 'UriLocation', }, }, }, textSearching: { textSearchAdapter: { type: 'TrixTextSearchAdapter', textSearchAdapterId: 'gff3tabix_genes-index', ixFilePath: { uri: 'storybook_data/gff3tabix_genes.ix', locationType: 'UriLocation', }, ixxFilePath: { uri: 'storybook_data/gff3tabix_genes.ixx', locationType: 'UriLocation', }, metaFilePath: { uri: 'storybook_data/gff3tabix_genes_meta.json', locationType: 'UriLocation', }, assemblyNames: ['volvox'], }, }, }, ], defaultSession, // use 1-based coordinates for locstring location: 'ctgA:1..800', } addRelativeUris( textSearchConfig, new URL(configPath, window.location.href).href, ) const state = createViewState(textSearchConfig) return <JBrowseLinearGenomeView viewState={state} /> } export const CustomTheme = () => { const state = createViewState({ assembly, tracks, defaultSession: { ...defaultSession, view: { ...defaultSession.view, bpPerPx: 0.1, offsetPx: 10000, tracks: [ { id: 'q3UA86xQA', type: 'ReferenceSequenceTrack', configuration: 'volvox_refseq', displays: [ { id: '6JCCxQScPJ', type: 'LinearReferenceSequenceDisplay', configuration: 'volvox_refseq-LinearReferenceSequenceDisplay', height: 210, }, ], }, ], }, }, configuration: { theme: { palette: { primary: { main: '#311b92', }, secondary: { main: '#0097a7', }, tertiary: { main: '#f57c00', }, quaternary: { main: '#d50000', }, bases: { A: { main: '#98FB98' }, C: { main: '#87CEEB' }, G: { main: '#DAA520' }, T: { main: '#DC143C' }, }, }, }, }, }) return <JBrowseLinearGenomeView viewState={state} /> } export const NextstrainExample = () => { const { assembly, tracks, defaultSession } = nextstrainConfig const state = createViewState({ assembly, tracks, defaultSession, location: 'SARS-CoV-2:1..29,903', onChange: patch => { console.log('patch', patch) }, configuration: { theme: { palette: { primary: { main: '#5da8a3', }, secondary: { main: '#333', }, }, }, }, }) return <JBrowseLinearGenomeView viewState={state} /> } const VisibleRegions = observer( ({ state }: { state: ReturnType<typeof createViewState> }) => { const locstrings = state.session.views[0].coarseDynamicBlocks .map( (region: Region) => `${region.refName}:${Math.floor(region.start)}-${Math.floor( region.end, )}`, ) .join(',') return <p>Visible region: {locstrings}</p> }, ) export const VisibleRegionsExample = () => { const state = createViewState({ assembly, tracks, defaultSession, location: 'ctgA:1105..1221', }) return ( <div> <JBrowseLinearGenomeView viewState={state} /> <VisibleRegions state={state} /> </div> ) } export const WithInlinePlugins = () => { // you don't have to necessarily define this inside your react component, it // just helps so that you can see the source code in the storybook to have it // here class HighlightRegionPlugin extends Plugin { name = 'HighlightRegionPlugin' install(pluginManager: PluginManager) { pluginManager.addToExtensionPoint( 'Core-extendPluggableElement', // eslint-disable-next-line @typescript-eslint/no-explicit-any (pluggableElement: any) => { if (pluggableElement.name === 'LinearGenomeView') { const { stateModel } = pluggableElement as ViewType const newStateModel = stateModel.extend(self => { const superRubberBandMenuItems = self.rubberBandMenuItems return { views: { rubberBandMenuItems() { return [ ...superRubberBandMenuItems(), { label: 'Console log selected region', onClick: () => { const { leftOffset, rightOffset } = self const selectedRegions = self.getSelectedRegions( leftOffset, rightOffset, ) // console log the list of potentially multiple // regions that were selected console.log(selectedRegions) }, }, ] }, }, } }) pluggableElement.stateModel = newStateModel } return pluggableElement }, ) } configure() {} } const state = createViewState({ assembly, plugins: [HighlightRegionPlugin], tracks, defaultSession, location: 'ctgA:1105..1221', }) return <JBrowseLinearGenomeView viewState={state} /> } export const WithExternalPlugins = () => { // usage with buildtime plugins // this plugins array is then passed to the createViewState constructor // import UCSCPlugin from 'jbrowse-plugin-ucsc' // const plugins = [UCSCPlugin] // usage with runtime plugins // this plugins array is then passed to the createViewState constructor const [plugins, setPlugins] = useState<PluginRecord[]>() useEffect(() => { async function getPlugins() { const loadedPlugins = await loadPlugins([ { name: 'UCSC', url: 'https://unpkg.com/jbrowse-plugin-ucsc@^1/dist/jbrowse-plugin-ucsc.umd.production.min.js', }, ]) setPlugins(loadedPlugins) } getPlugins() }, [setPlugins]) if (!plugins) { return null } const state = createViewState({ assembly: { name: 'hg19', aliases: ['GRCh37'], sequence: { type: 'ReferenceSequenceTrack', trackId: 'Pd8Wh30ei9R', adapter: { type: 'BgzipFastaAdapter', fastaLocation: { uri: 'https://jbrowse.org/genomes/hg19/fasta/hg19.fa.gz', locationType: 'UriLocation', }, faiLocation: { uri: 'https://jbrowse.org/genomes/hg19/fasta/hg19.fa.gz.fai', locationType: 'UriLocation', }, gziLocation: { uri: 'https://jbrowse.org/genomes/hg19/fasta/hg19.fa.gz.gzi', locationType: 'UriLocation', }, }, }, refNameAliases: { adapter: { type: 'RefNameAliasAdapter', location: { uri: 'https://s3.amazonaws.com/jbrowse.org/genomes/hg19/hg19_aliases.txt', locationType: 'UriLocation', }, }, }, }, plugins: plugins.map(p => p.plugin), tracks: [ { type: 'FeatureTrack', trackId: 'segdups_ucsc_hg19', name: 'UCSC SegDups', category: ['Annotation'], assemblyNames: ['hg19'], adapter: { type: 'UCSCAdapter', track: 'genomicSuperDups', }, }, ], location: '1:2,467,681..2,667,681', defaultSession: { name: 'Runtime plugins', view: { id: 'aU9Nqje1U', type: 'LinearGenomeView', offsetPx: 22654, bpPerPx: 108.93300653594771, displayedRegions: [ { refName: '1', start: 0, end: 249250621, reversed: false, assemblyName: 'hg19', }, ], tracks: [ { id: 'MbiRphmDa', type: 'FeatureTrack', configuration: 'segdups_ucsc_hg19', displays: [ { id: '8ovhuA5cFM', type: 'LinearBasicDisplay', height: 100, configuration: 'segdups_ucsc_hg19-LinearBasicDisplay', }, ], }, ], hideHeader: false, hideHeaderOverview: false, trackSelectorType: 'hierarchical', trackLabels: 'overlapping', showCenterLine: false, }, }, }) return <JBrowseLinearGenomeView viewState={state} /> } const JBrowseLinearGenomeViewStories = { title: 'Linear View', } export default JBrowseLinearGenomeViewStories
the_stack
import { StyleInfo } from 'lit/directives/style-map'; import { CallServiceActionConfig, CustomActionConfig, LovelaceCard, LovelaceCardEditor, MoreInfoActionConfig, NavigateActionConfig, ToggleActionConfig, UrlActionConfig, } from 'custom-card-helpers'; import { z } from 'zod'; import { deepRemoveDefaults } from './zod-util'; declare global { interface HTMLElementTagNameMap { 'frigate-card-editor': LovelaceCardEditor; 'hui-error-card': LovelaceCard; } } /** * Internal types. */ const FRIGATE_CARD_VIEWS_USER_SPECIFIED = [ 'live', // Live view. 'clip', // Most recent clip. 'clips', // Clips gallery. 'snapshot', // Most recent snapshot. 'snapshots', // Snapshots gallery. 'image', // Static image. ] as const; export type FrigateCardView = typeof FRIGATE_CARD_VIEWS_USER_SPECIFIED[number]; const FRIGATE_MENU_MODES = [ 'none', 'hidden-top', 'hidden-left', 'hidden-bottom', 'hidden-right', 'overlay-top', 'overlay-left', 'overlay-bottom', 'overlay-right', 'hover-top', 'hover-left', 'hover-bottom', 'hover-right', 'above', 'below', ] as const; const LIVE_PROVIDERS = ['auto', 'frigate', 'frigate-jsmpeg', 'webrtc'] as const; export type LiveProvider = typeof LIVE_PROVIDERS[number]; export class FrigateCardError extends Error {} /** * Action Types (for "Picture Elements" / Menu) */ // Declare schemas to existing types: // - https://github.com/colinhacks/zod/issues/372#issuecomment-826380330 const schemaForType = <T>() => // eslint-disable-next-line @typescript-eslint/no-explicit-any <S extends z.ZodType<T, any, any>>(arg: S) => { return arg; }; const toggleActionSchema = schemaForType<ToggleActionConfig>()( z.object({ action: z.literal('toggle'), }), ); const callServiceActionSchema = schemaForType<CallServiceActionConfig>()( z.object({ action: z.literal('call-service'), service: z.string(), service_data: z.object({}).passthrough().optional(), }), ); const navigateActionSchema = schemaForType<NavigateActionConfig>()( z.object({ action: z.literal('navigate'), navigation_path: z.string(), }), ); const urlActionSchema = schemaForType<UrlActionConfig>()( z.object({ action: z.literal('url'), url_path: z.string(), }), ); const moreInfoActionSchema = schemaForType<MoreInfoActionConfig>()( z.object({ action: z.literal('more-info'), }), ); const customActionSchema = schemaForType<CustomActionConfig>()( z.object({ action: z.literal('fire-dom-event'), }), ); const frigateCardCustomActionBaseSchema = customActionSchema.extend({ // Syntactic sugar to avoid 'fire-dom-event' as part of an external API. action: z .literal('custom:frigate-card-action') .transform((): 'fire-dom-event' => 'fire-dom-event') .or(z.literal('fire-dom-event')), }); const FRIGATE_CARD_GENERAL_ACTIONS = [ 'frigate', 'clip', 'clips', 'image', 'live', 'snapshot', 'snapshots', 'download', 'frigate_ui', 'fullscreen', ] as const; const FRIGATE_CARD_ACTIONS = [...FRIGATE_CARD_GENERAL_ACTIONS, 'camera_select'] as const; export type FrigateCardAction = typeof FRIGATE_CARD_ACTIONS[number]; const frigateCardGeneralActionSchema = frigateCardCustomActionBaseSchema.extend({ frigate_card_action: z.enum(FRIGATE_CARD_GENERAL_ACTIONS), }); const frigateCardCameraSelectActionSchema = frigateCardCustomActionBaseSchema.extend({ frigate_card_action: z.literal('camera_select'), camera: z.string(), }); export const frigateCardCustomActionSchema = z.union([ frigateCardGeneralActionSchema, frigateCardCameraSelectActionSchema, ]); export type FrigateCardCustomAction = z.infer<typeof frigateCardCustomActionSchema>; const actionSchema = z.union([ toggleActionSchema, callServiceActionSchema, navigateActionSchema, urlActionSchema, moreInfoActionSchema, frigateCardCustomActionSchema, ]); export type ActionType = z.infer<typeof actionSchema>; const actionBaseSchema = z .object({ tap_action: actionSchema.optional(), hold_action: actionSchema.optional(), double_tap_action: actionSchema.optional(), }) .passthrough(); export type Actions = z.infer<typeof actionBaseSchema>; const actionsSchema = z.object({ // Passthrough to allow (at least) entity/camera_image to go through. This // card doesn't need these attributes, but handleAction() in // custom_card_helpers may depending on how the action is configured. actions: actionBaseSchema.optional(), }); const elementsBaseSchema = actionBaseSchema.extend({ style: z.object({}).passthrough().optional(), title: z.string().nullable().optional(), }); /** * Picture Element Configuration. * * All picture element types are validated (not just the Frigate card custom * ones) as a convenience to present the user with a consistent error display * up-front regardless of where they made their error. */ // https://www.home-assistant.io/lovelace/picture-elements/#state-badge const stateBadgeIconSchema = elementsBaseSchema.extend({ type: z.literal('state-badge'), entity: z.string(), }); // https://www.home-assistant.io/lovelace/picture-elements/#state-icon const stateIconSchema = elementsBaseSchema.extend({ type: z.literal('state-icon'), entity: z.string(), icon: z.string().optional(), state_color: z.boolean().default(true), }); // https://www.home-assistant.io/lovelace/picture-elements/#state-label const stateLabelSchema = elementsBaseSchema.extend({ type: z.literal('state-label'), entity: z.string(), attribute: z.string().optional(), prefix: z.string().optional(), suffix: z.string().optional(), }); // https://www.home-assistant.io/lovelace/picture-elements/#service-call-button const serviceCallButtonSchema = elementsBaseSchema.extend({ type: z.literal('service-button'), // Title is required for service button. title: z.string(), service: z.string(), service_data: z.object({}).passthrough().optional(), }); // https://www.home-assistant.io/lovelace/picture-elements/#icon-element const iconSchema = elementsBaseSchema.extend({ type: z.literal('icon'), icon: z.string(), entity: z.string().optional(), }); // https://www.home-assistant.io/lovelace/picture-elements/#image-element const imageSchema = elementsBaseSchema.extend({ type: z.literal('image'), entity: z.string().optional(), image: z.string().optional(), camera_image: z.string().optional(), camera_view: z.string().optional(), state_image: z.object({}).passthrough().optional(), filter: z.string().optional(), state_filter: z.object({}).passthrough().optional(), aspect_ratio: z.string().optional(), }); // https://www.home-assistant.io/lovelace/picture-elements/#image-element const conditionalSchema = z.object({ type: z.literal('conditional'), conditions: z .object({ entity: z.string(), state: z.string().optional(), state_not: z.string().optional(), }) .array(), elements: z.lazy(() => pictureElementsSchema), }); // https://www.home-assistant.io/lovelace/picture-elements/#custom-elements const customSchema = z .object({ // Insist that Frigate card custom elements are handled by other schemas. type: z.string().superRefine((val, ctx) => { if (!val.match(/^custom:(?!frigate-card).+/)) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Frigate-card custom elements must match specific schemas', fatal: true, }); } }), }) .passthrough(); /** * Camera configuration section */ export const cameraConfigDefault = { client_id: 'frigate' as const, live_provider: 'auto' as const, }; const webrtcCameraConfigSchema = z.object({ entity: z.string().optional(), url: z.string().optional(), }); const cameraConfigSchema = z .object({ // No URL validation to allow relative URLs within HA (e.g. Frigate addon). frigate_url: z.string().optional(), client_id: z.string().default(cameraConfigDefault.client_id), camera_name: z.string().optional(), label: z.string().optional(), zone: z.string().optional(), camera_entity: z.string().optional(), live_provider: z.enum(LIVE_PROVIDERS).default(cameraConfigDefault.live_provider), // Used for presentation in the UI (autodetected from the entity if // specified). icon: z.string().optional(), title: z.string().optional(), // Optional identifier to separate different camera configurations used in // this card. id: z.string().optional(), // Camera identifiers for WebRTC. webrtc: webrtcCameraConfigSchema.optional(), }) .default(cameraConfigDefault); export type CameraConfig = z.infer<typeof cameraConfigSchema>; /** * Custom Element Types. */ export const menuIconSchema = iconSchema.extend({ type: z.literal('custom:frigate-card-menu-icon'), }); export type MenuIcon = z.infer<typeof menuIconSchema>; export const menuStateIconSchema = stateIconSchema.extend({ type: z.literal('custom:frigate-card-menu-state-icon'), }); export type MenuStateIcon = z.infer<typeof menuStateIconSchema>; const menuSubmenuItemSchema = elementsBaseSchema.extend({ entity: z.string().optional(), icon: z.string().optional(), state_color: z.boolean().default(true), selected: z.boolean().default(false), }); export type MenuSubmenuItem = z.infer<typeof menuSubmenuItemSchema>; export const menuSubmenuSchema = iconSchema.extend({ type: z.literal('custom:frigate-card-menu-submenu'), items: menuSubmenuItemSchema.array(), }); export type MenuSubmenu = z.infer<typeof menuSubmenuSchema>; const frigateCardConditionSchema = z.object({ view: z.string().array().optional(), fullscreen: z.boolean().optional(), camera: z.string().array().optional(), }); export type FrigateCardCondition = z.infer<typeof frigateCardConditionSchema>; const frigateConditionalSchema = z.object({ type: z.literal('custom:frigate-card-conditional'), conditions: frigateCardConditionSchema, elements: z.lazy(() => pictureElementsSchema), }); export type FrigateConditional = z.infer<typeof frigateConditionalSchema>; const pictureElementSchema = z.union([ menuStateIconSchema, menuIconSchema, menuSubmenuSchema, frigateConditionalSchema, stateBadgeIconSchema, stateIconSchema, stateLabelSchema, serviceCallButtonSchema, iconSchema, imageSchema, conditionalSchema, customSchema, ]); export type PictureElement = z.infer<typeof pictureElementSchema>; const pictureElementsSchema = pictureElementSchema.array().optional(); export type PictureElements = z.infer<typeof pictureElementsSchema>; /** * View configuration section. */ const viewConfigDefault = { default: 'live' as const, timeout: 180, update_force: false, }; const viewConfigSchema = z .object({ default: z .enum(FRIGATE_CARD_VIEWS_USER_SPECIFIED) .optional() .default(viewConfigDefault.default), timeout_seconds: z.number().default(viewConfigDefault.timeout), update_force: z.boolean().default(viewConfigDefault.update_force), update_entities: z.string().array().optional(), }) .merge(actionsSchema) .default(viewConfigDefault); /** * Image view configuration section. */ const imageConfigDefault = { refresh_seconds: 0, }; const imageConfigSchema = z .object({ src: z.string().optional(), refresh_seconds: z.number().min(0).default(imageConfigDefault.refresh_seconds) }) .merge(actionsSchema) .default(imageConfigDefault); export type ImageViewConfig = z.infer<typeof imageConfigSchema>; /** * Thumbnail controls configuration section. */ const thumbnailsControlSchema = z.object({ mode: z.enum(['none', 'above', 'below']), size: z.string().optional(), }); export type ThumbnailsControlConfig = z.infer<typeof thumbnailsControlSchema>; /** * Next/Previous Control configuration section. */ const nextPreviousControlConfigSchema = z.object({ style: z.enum(['none', 'chevrons', 'icons', 'thumbnails']), size: z.string(), }); export type NextPreviousControlConfig = z.infer<typeof nextPreviousControlConfigSchema>; /** * Live view configuration section. */ const liveConfigDefault = { preload: false, lazy_load: true, draggable: true, controls: { next_previous: { size: '48px', style: 'chevrons' as const, }, thumbnails: { media: 'clips' as const, size: '100px', mode: 'none' as const, }, }, }; const webrtcConfigSchema = webrtcCameraConfigSchema.passthrough().optional(); export type WebRTCConfig = z.infer<typeof webrtcConfigSchema>; const jsmpegConfigSchema = z .object({ options: z .object({ // https://github.com/phoboslab/jsmpeg#usage audio: z.boolean().optional(), video: z.boolean().optional(), pauseWhenHidden: z.boolean().optional(), disableGl: z.boolean().optional(), disableWebAssembly: z.boolean().optional(), preserveDrawingBuffer: z.boolean().optional(), progressive: z.boolean().optional(), throttled: z.boolean().optional(), chunkSize: z.number().optional(), maxAudioLag: z.number().optional(), videoBufferSize: z.number().optional(), audioBufferSize: z.number().optional(), }) .optional(), }) .optional(); export type JSMPEGConfig = z.infer<typeof jsmpegConfigSchema>; const liveNextPreviousControlConfigSchema = nextPreviousControlConfigSchema.extend({ // Live cannot show thumbnails, remove that option. style: z .enum(['none', 'chevrons', 'icons']) .default(liveConfigDefault.controls.next_previous.style), size: nextPreviousControlConfigSchema.shape.size.default( liveConfigDefault.controls.next_previous.size, ), }); const liveThumbnailControlConfigSchema = thumbnailsControlSchema.extend({ mode: thumbnailsControlSchema.shape.mode.default( liveConfigDefault.controls.thumbnails.mode, ), size: thumbnailsControlSchema.shape.size.default( liveConfigDefault.controls.thumbnails.size, ), media: z .enum(['clips', 'snapshots']) .default(liveConfigDefault.controls.thumbnails.media), }); const liveOverridableConfigSchema = z .object({ webrtc: webrtcConfigSchema, jsmpeg: jsmpegConfigSchema, controls: z .object({ next_previous: liveNextPreviousControlConfigSchema.default( liveConfigDefault.controls.next_previous, ), thumbnails: liveThumbnailControlConfigSchema.default( liveConfigDefault.controls.thumbnails, ), }) .default(liveConfigDefault.controls), }) .merge(actionsSchema); const liveConfigSchema = liveOverridableConfigSchema .extend({ // Non-overrideable parameters. preload: z.boolean().default(liveConfigDefault.preload), lazy_load: z.boolean().default(liveConfigDefault.lazy_load), draggable: z.boolean().default(liveConfigDefault.draggable), }) .default(liveConfigDefault); export type LiveConfig = z.infer<typeof liveConfigSchema>; /** * Menu configuration section. */ const menuConfigDefault = { mode: 'hidden-top' as const, buttons: { frigate: true, cameras: true, live: true, clips: true, snapshots: true, image: false, download: true, frigate_ui: true, fullscreen: true, }, button_size: '40px', }; const menuConfigSchema = z .object({ mode: z.enum(FRIGATE_MENU_MODES).default(menuConfigDefault.mode), buttons: z .object({ frigate: z.boolean().default(menuConfigDefault.buttons.frigate), cameras: z.boolean().default(menuConfigDefault.buttons.cameras), live: z.boolean().default(menuConfigDefault.buttons.live), clips: z.boolean().default(menuConfigDefault.buttons.clips), snapshots: z.boolean().default(menuConfigDefault.buttons.snapshots), image: z.boolean().default(menuConfigDefault.buttons.image), download: z.boolean().default(menuConfigDefault.buttons.download), frigate_ui: z.boolean().default(menuConfigDefault.buttons.frigate_ui), fullscreen: z.boolean().default(menuConfigDefault.buttons.fullscreen), }) .default(menuConfigDefault.buttons), button_size: z.string().default(menuConfigDefault.button_size), }) .default(menuConfigDefault); export type MenuConfig = z.infer<typeof menuConfigSchema>; /** * Event viewer configuration section (clip, snapshot). */ const viewerConfigDefault = { autoplay_clip: true, lazy_load: true, draggable: true, controls: { next_previous: { size: '48px', style: 'thumbnails' as const, }, thumbnails: { size: '100px', mode: 'none' as const, }, }, }; const viewerNextPreviousControlConfigSchema = nextPreviousControlConfigSchema.extend({ style: z .enum(['none', 'thumbnails', 'chevrons']) .default(viewerConfigDefault.controls.next_previous.style), size: z.string().default(viewerConfigDefault.controls.next_previous.size), }); export type ViewerNextPreviousControlConfig = z.infer< typeof viewerNextPreviousControlConfigSchema >; const viewerConfigSchema = z .object({ autoplay_clip: z.boolean().default(viewerConfigDefault.autoplay_clip), lazy_load: z.boolean().default(viewerConfigDefault.lazy_load), draggable: z.boolean().default(viewerConfigDefault.draggable), controls: z .object({ next_previous: viewerNextPreviousControlConfigSchema.default( viewerConfigDefault.controls.next_previous, ), thumbnails: thumbnailsControlSchema .extend({ mode: thumbnailsControlSchema.shape.mode.default( viewerConfigDefault.controls.thumbnails.mode, ), size: thumbnailsControlSchema.shape.size.default( viewerConfigDefault.controls.thumbnails.size, ), }) .default(viewerConfigDefault.controls.thumbnails), }) .default(viewerConfigDefault.controls), }) .merge(actionsSchema) .default(viewerConfigDefault); export type ViewerConfig = z.infer<typeof viewerConfigSchema>; /** * Event gallery configuration section (clips, snapshots). */ const galleryConfigDefault = { min_columns: 5, }; const galleryConfigSchema = z .object({ min_columns: z.number().min(1).max(10).default(galleryConfigDefault.min_columns), }) .merge(actionsSchema) .default(galleryConfigDefault); export type GalleryConfig = z.infer<typeof galleryConfigSchema>; /** * Dimensions configuration section. */ const dimensionsConfigDefault = { aspect_ratio_mode: 'dynamic' as const, aspect_ratio: [16, 9], }; const dimensionsConfigSchema = z .object({ aspect_ratio_mode: z .enum(['dynamic', 'static', 'unconstrained']) .default(dimensionsConfigDefault.aspect_ratio_mode), aspect_ratio: z .number() .array() .length(2) .or( z .string() .regex(/^\s*\d+\s*[:\/]\s*\d+\s*$/) .transform((input) => input.split(/[:\/]/).map((d) => Number(d))), ) .default(dimensionsConfigDefault.aspect_ratio), }) .default(dimensionsConfigDefault); /** * Configuration overrides */ // Strip all defaults from the override schemas, to ensure values are only what // the user has specified. const overrideConfigurationSchema = z.object({ live: deepRemoveDefaults(liveOverridableConfigSchema).optional(), menu: deepRemoveDefaults(menuConfigSchema).optional(), }); export type OverrideConfigurationKey = keyof z.infer<typeof overrideConfigurationSchema>; const overridesSchema = z .object({ conditions: frigateCardConditionSchema, overrides: overrideConfigurationSchema, }) .array() .optional(); const liveOverridesSchema = z .object({ conditions: frigateCardConditionSchema, overrides: liveOverridableConfigSchema, }) .array() .optional(); export type LiveOverrides = z.infer<typeof liveOverridesSchema>; /** * Main card config. */ export const frigateCardConfigSchema = z.object({ // Main configuration sections. cameras: cameraConfigSchema.array().nonempty(), view: viewConfigSchema, menu: menuConfigSchema, live: liveConfigSchema, event_viewer: viewerConfigSchema, event_gallery: galleryConfigSchema, image: imageConfigSchema, elements: pictureElementsSchema, dimensions: dimensionsConfigSchema, // Configuration overrides. overrides: overridesSchema, // Stock lovelace card config. type: z.string(), test_gui: z.boolean().optional(), }); export type FrigateCardConfig = z.infer<typeof frigateCardConfigSchema>; export type RawFrigateCardConfig = Record<string, unknown>; export type RawFrigateCardConfigArray = RawFrigateCardConfig[]; export const frigateCardConfigDefaults = { cameras: cameraConfigDefault, view: viewConfigDefault, menu: menuConfigDefault, live: liveConfigDefault, event_viewer: viewerConfigDefault, event_gallery: galleryConfigDefault, image: imageConfigDefault, }; const menuButtonSchema = z.union([ menuIconSchema, menuStateIconSchema, menuSubmenuSchema, ]); export type MenuButton = z.infer<typeof menuButtonSchema>; export interface ExtendedHomeAssistant { hassUrl(path?): string; } export interface BrowseMediaQueryParameters { mediaType: 'clips' | 'snapshots'; clientId: string; cameraName: string; label?: string; zone?: string; before?: number; after?: number; } export interface GetFrigateCardMenuButtonParameters { icon: string; title: string; tap_action: FrigateCardAction; hold_action?: FrigateCardAction; emphasize?: boolean; } export interface BrowseMediaNeighbors { previous: BrowseMediaSource | null; previousIndex: number | null; next: BrowseMediaSource | null; nextIndex: number | null; } export interface MediaShowInfo { width: number; height: number; } export interface Message { message: string; type: 'error' | 'info'; icon?: string; } export interface StateParameters { entity?: string; icon?: string; title?: string | null; state_color?: boolean; style?: StyleInfo; } /** * Home Assistant API types. */ // Recursive type, cannot use type interference: // See: https://github.com/colinhacks/zod#recursive-types // // Server side data-type defined here: https://github.com/home-assistant/core/blob/dev/homeassistant/components/media_player/__init__.py export interface BrowseMediaSource { title: string; media_class: string; media_content_type: string; media_content_id: string; can_play: boolean; can_expand: boolean; children_media_class: string | null; thumbnail: string | null; children?: BrowseMediaSource[] | null; } export const browseMediaSourceSchema: z.ZodSchema<BrowseMediaSource> = z.lazy(() => z.object({ title: z.string(), media_class: z.string(), media_content_type: z.string(), media_content_id: z.string(), can_play: z.boolean(), can_expand: z.boolean(), children_media_class: z.string().nullable(), thumbnail: z.string().nullable(), children: z.array(browseMediaSourceSchema).nullable().optional(), }), ); // Server side data-type defined here: https://github.com/home-assistant/core/blob/dev/homeassistant/components/media_source/models.py export const resolvedMediaSchema = z.object({ url: z.string(), mime_type: z.string(), }); export type ResolvedMedia = z.infer<typeof resolvedMediaSchema>; export const signedPathSchema = z.object({ path: z.string(), }); export type SignedPath = z.infer<typeof signedPathSchema>; export const entitySchema = z.object({ entity_id: z.string(), unique_id: z.string(), platform: z.string(), }); export type Entity = z.infer<typeof entitySchema>;
the_stack
import { Assert, AITestClass } from "@microsoft/ai-test-framework"; import { AppInsightsCore, IConfiguration, DiagnosticLogger, ITelemetryItem, createCookieMgr, newId, strTrim } from "@microsoft/applicationinsights-core-js"; import PropertiesPlugin from "../../../src/PropertiesPlugin"; import { ITelemetryConfig } from "../../../src/Interfaces/ITelemetryConfig"; import { TelemetryContext } from "../../../src/TelemetryContext"; import { TelemetryTrace } from "../../../src/Context/TelemetryTrace"; import { IConfig } from "@microsoft/applicationinsights-common"; export class PropertiesTests extends AITestClass { private properties: PropertiesPlugin; private core: AppInsightsCore; private _cookies: { [name: string ]: string } = {}; public testInitialize() { let _self = this; _self._cookies = {}; _self.core = new AppInsightsCore(); _self.core.logger = new DiagnosticLogger(); _self.core.setCookieMgr(createCookieMgr({ cookieCfg: { setCookie: (name: string, value: string) => _self._setCookie(name, value), getCookie: (name: string) => _self._getCookie(name), delCookie: (name: string) => _self._delCookie(name) } }, _self.core.logger)) _self.properties = new PropertiesPlugin(); } public testCleanup() { this.core = null; this.properties = null; } public registerTests() { this.addConfigTests(); this.addUserTests(); this.addDeviceTests(); this.addTelemetryTraceTests(); this.addSessionTests(); } private _setCookie(name: string, value: string) { this._cookies[name] = value; } private _getCookie(name: string) { let cookieValue = this._cookies[name] || ""; // Remove any cookie attributes added to the cookie return cookieValue.split(";")[0]; } private _delCookie(name: string) { if (this._cookies.hasOwnProperty(name)) { delete this._cookies[name]; } } private _getNewId(idLength?: number) { return newId(idLength); } private addTelemetryTraceTests() { this.testCase({ name: 'Trace: default operation.name is grabbed from window pathname, if available', test: () => { const operation = new TelemetryTrace(); Assert.ok(operation.name); } }); this.testCase({ name: 'Trace: operation.name is truncated to max size 1024 if too long', test: () => { const name = new Array(1234).join("a"); // exceeds max of 1024 const operation = new TelemetryTrace(undefined, undefined, name, this.core.logger); Assert.ok(operation.name); Assert.equal(operation.name.length, 1024); } }); } private addConfigTests() { this.testCase({ name: 'Properties Configuration: Config options can be passed from root config', test: () => { this.properties.initialize({ instrumentationKey: 'instrumentation_key', accountId: 'abc', samplingPercentage: 15, sessionExpirationMs: 99999, extensionConfig: { [this.properties.identifier]: { sessionExpirationMs: 88888 } } }, this.core, []); const config: ITelemetryConfig = this.properties['_extConfig']; Assert.equal(15, config.samplingPercentage(), 'Extension configs can be set via root config (number)'); Assert.equal('abc', config.accountId(), 'Extension configs can be set via root config (string)'); Assert.equal(88888, config.sessionExpirationMs(), 'Root config does not override extensionConfig field when both are present') Assert.notEqual(99999, config.sessionExpirationMs(), 'extensionConfig overrides root config field when both are present'); } }); } private addDeviceTests() { this.testCase({ name: 'Device: device context adds Browser field to ITelemetryItem', test: () => { this.properties.initialize({ instrumentationKey: 'key', extensionConfig: {} }, this.core, []); this.properties.context.user.isNewUser = false; // Act const item: ITelemetryItem = {name: 'item'}; this.properties.processTelemetry(item); // Assert Assert.equal("Browser", item.ext.device.deviceClass); Assert.equal("browser", item.ext.device.localId); } }); } private addUserTests() { this.testCase({ name: 'User: user context initializes from cookie when possible', test: () => { // setup const id = "someUserId"; var cookieStub = this.sandbox.stub(this as any, "_getCookie").callsFake(() => id + "||||"); // Act Assert.ok(cookieStub.notCalled, 'Cookie not yet grabbed'); this.properties.initialize(this.getEmptyConfig(), this.core, []); Assert.ok(cookieStub.called, 'Cookie grabbed'); // Assert Assert.equal(id, this.properties.context.user.id, 'user id was set from cookie'); } }); this.testCase({ name: 'User: track is triggered if user context is first time initialized', test: () => { // setup var setCookieStub = this.sandbox.stub(this as any, "_setCookie").callsFake(() => {}); var loggingStub = this.sandbox.stub(this.core.logger, "logInternalMessage"); // Act Assert.ok(setCookieStub.notCalled, 'Cookie not yet generated'); Assert.ok(loggingStub.notCalled, 'logInternalMessage is not yet triggered'); this.properties.initialize(this.getEmptyConfig(), this.core, []); Assert.ok(setCookieStub.called, 'Cookie generated'); // Assert Assert.equal(true, this.properties.context.user.isNewUser, 'current user is a new user'); const item: ITelemetryItem = {name: 'item'}; this.properties.processTelemetry(item); // this.clock.tick(1000); Assert.ok(loggingStub.called, 'logInternalMessage is triggered'); Assert.equal(false, this.properties.context.user.isNewUser, 'current user is not new user with ai_user cookie set') } }); this.testCase({ name: "ai_user cookie is set with acq date and year expiration", test: () => { // setup var actualCookieName: string; var actualCookieValue: string; var newIdStub = this.sandbox.stub(this as any, "_getNewId").callsFake(() => "newId"); var getCookieStub = this.sandbox.stub(this as any, "_getCookie").callsFake(() =>""); var setCookieStub = this.sandbox.stub(this as any, "_setCookie").callsFake((cookieName, cookieValue) => { actualCookieName = cookieName; actualCookieValue = cookieValue; }); // act this.properties.initialize(this.getEmptyConfig(), this.core, []); // verify Assert.equal("ai_user", actualCookieName, "ai_user cookie is set"); var cookieValueParts = actualCookieValue.split(';'); Assert.equal(4, cookieValueParts.length, "ai_user cookie value should have actual value and expiration"); Assert.equal(2, cookieValueParts[0].split('|').length, "ai_user cookie value before expiration should include user id and acq date"); Assert.equal("newId", cookieValueParts[0].split('|')[0], "First part of ai_user cookie value should be new user id guid"); Assert.equal(new Date().toString(), (new Date(cookieValueParts[0].split('|')[1])).toString(), "Second part of ai_user cookie should be parsable as date"); var expiration = strTrim(cookieValueParts[1]); Assert.equal(true, expiration.substr(0, "expires=".length) === "expires=", "ai_user cookie expiration part should start with expires="); var expirationDate = new Date(expiration.substr("expires=".length)); Assert.equal(true, expirationDate > (new Date), "ai_user cookie expiration should be in the future"); } }); this.testCase({ name: "ai_user cookie uses userCookiePostfix for cookie storage", test: () => { // setup var actualCookieName: string; var actualCookieValue: string; var newIdStub = this.sandbox.stub(this as any, "_getNewId").callsFake(() => "newId"); var getCookieStub = this.sandbox.stub(this as any, "_getCookie").callsFake(() =>""); var setCookieStub = this.sandbox.stub(this as any, "_setCookie").callsFake((cookieName, cookieValue) => { actualCookieName = cookieName; actualCookieValue = cookieValue; }); // act let config: IConfig & IConfiguration = this.getEmptyConfig(); config.userCookiePostfix = 'testUserCookieNamePostfix'; this.properties.initialize(config, this.core, []); // verify Assert.equal("ai_usertestUserCookieNamePostfix", actualCookieName, "ai_user cookie is set"); } }); this.testCase({ name: "Ctor: auth and account id initialize from cookie", test: () => { // setup var authId = "bla@bla.com"; var accountId = "Contoso"; var cookieStub = this.sandbox.stub(this as any, "_getCookie").callsFake(() => authId + "|" + accountId); // act this.properties.initialize(this.getEmptyConfig(), this.core, []); // verify Assert.equal(authId, this.properties.context.user.authenticatedId, "user auth id was set from cookie"); Assert.equal(accountId, this.properties.context.user.accountId, "user account id was not set from cookie"); } }); this.testCase({ name: "Ctor: auth id initializes from cookie (without account id)", test: () => { // setup var authId = "bla@bla.com"; var cookieStub = this.sandbox.stub(this as any, "_getCookie").callsFake(() => authId); // act this.properties.initialize(this.getEmptyConfig(), this.core, []); // verify Assert.equal(authId, this.properties.context.user.authenticatedId, "user auth id was set from cookie"); } }); this.testCase({ name: "Ctor: auth user context handles empty cookie", test: () => { // setup var cookieStub = this.sandbox.stub(this as any, "_getCookie").callsFake(() => ""); // act this.properties.initialize(this.getEmptyConfig(), this.core, []); // verify Assert.equal(undefined, this.properties.context.user.authenticatedId, "user auth id was not set"); Assert.equal(undefined, this.properties.context.user.accountId, "user account id was not set"); } }); this.testCase({ name: "Ctor: auth user context handles empty cookie with accountId backward compatibility", test: () => { // setup var config = this.getEmptyConfig(); config.extensionConfig.AppInsightsPropertiesPlugin.accountId = "account17"; var cookieStub = this.sandbox.stub(this as any, "_getCookie").callsFake(() => null); // act this.properties.initialize(config, this.core, []); // verify Assert.equal(config.extensionConfig.AppInsightsPropertiesPlugin.accountId, this.properties.context.user.accountId, "user account id was set from back compat"); } }); this.testCase({ name: "setAuthenticatedUserContext: auth id and account id is set (not in the cookie)", test: () => { // setup var authAndAccountId = ['bla@bla.com', 'contoso']; this.properties.initialize(this.getEmptyConfig(), this.core, []); var cookieStub = this.sandbox.stub(this as any, "_setCookie"); // act this.properties.context.user.setAuthenticatedUserContext(authAndAccountId[0], authAndAccountId[1]); // verify Assert.equal('bla@bla.com', this.properties.context.user.authenticatedId, "user auth id was not set"); Assert.equal('contoso', this.properties.context.user.accountId, "user account id was not set"); Assert.equal(cookieStub.notCalled, true, "cookie was not set"); } }); this.testCase({ name: "setAuthenticatedUserContext: auth user set in cookie without account id", test: () => { // setup var authAndAccountId = ["bla@bla.com"]; var cookieStub = this.sandbox.stub(this as any, "_setCookie"); this.properties.initialize(this.getEmptyConfig(), this.core, []); // act this.properties.context.user.setAuthenticatedUserContext(authAndAccountId[0], null, true); // verify Assert.equal(authAndAccountId[0], this.properties.context.user.authenticatedId, "user auth id was set"); Assert.equal(cookieStub.calledWithExactly('ai_authUser', encodeURI(authAndAccountId.join('|')) + "; path=/"), true, "user auth id and account id cookie was set"); } }); this.testCase({ name: "setAuthenticatedUserContext: auth user and account id set in cookie ", test: () => { // setup var authAndAccountId = ['bla@bla.com', 'contoso']; var cookieStub = this.sandbox.stub(this as any, "_setCookie"); this.properties.initialize(this.getEmptyConfig(), this.core, []); // act this.properties.context.user.setAuthenticatedUserContext(authAndAccountId[0], authAndAccountId[1], true); // verify Assert.equal(authAndAccountId[0], this.properties.context.user.authenticatedId, "user auth id was set"); Assert.equal(cookieStub.calledWithExactly('ai_authUser', encodeURI(authAndAccountId.join('|')) + "; path=/"), true, "user auth id cookie was set"); } }); this.testCase({ name: "setAuthenticatedUserContext: handles only auth user id correctly", test: () => { // setup var authAndAccountId = ['bla@bla.com']; var cookieStub = this.sandbox.stub(this as any, "_setCookie"); this.properties.initialize(this.getEmptyConfig(), this.core, []); // act this.properties.context.user.setAuthenticatedUserContext(authAndAccountId[0], null, true); // verify Assert.equal(authAndAccountId[0], this.properties.context.user.authenticatedId, "user auth id was set"); Assert.equal(null, this.properties.context.user.accountId, "user account id was not set"); Assert.equal(cookieStub.calledWithExactly('ai_authUser', encodeURI(authAndAccountId[0]) + "; path=/"), true, "user auth id cookie was set"); } }); this.testCase({ name: "setAuthenticatedUserContext: handles null correctly", test: () => { // setup var cookieStub = this.sandbox.stub(this as any, "_setCookie"); this.properties.initialize(this.getEmptyConfig(), this.core, []); var loggingStub = this.sandbox.stub(this.core.logger, "throwInternal"); cookieStub.reset(); loggingStub.reset(); // act this.properties.context.user.setAuthenticatedUserContext(null); // verify Assert.equal(undefined, this.properties.context.user.authenticatedId, "user auth id was not set"); Assert.equal(undefined, this.properties.context.user.accountId, "user account id was not set"); Assert.equal(cookieStub.notCalled, true, "cookie was not set"); Assert.equal(loggingStub.calledOnce, true, "Warning was logged"); } }); this.testCase({ name: "setAuthenticatedUserContext: handles undefined correctly", test: () => { // setup var cookieStub = this.sandbox.stub(this as any, "_setCookie"); this.properties.initialize(this.getEmptyConfig(), this.core, []); var loggingStub = this.sandbox.stub(this.core.logger, "throwInternal"); cookieStub.reset(); loggingStub.reset(); // act this.properties.context.user.setAuthenticatedUserContext(undefined, undefined); // verify Assert.equal(undefined, this.properties.context.user.authenticatedId, "user auth id was not set"); Assert.equal(undefined, this.properties.context.user.accountId, "user account id was not set"); Assert.equal(cookieStub.notCalled, true, "cookie was not set"); Assert.equal(loggingStub.calledOnce, true, "Warning was logged"); } }); this.testCase({ name: "setAuthenticatedUserContext: handles only accountID correctly", test: () => { // setup var cookieStub = this.sandbox.stub(this as any, "_setCookie"); this.properties.initialize(this.getEmptyConfig(), this.core, []); var loggingStub = this.sandbox.stub(this.core.logger, "throwInternal"); cookieStub.reset(); loggingStub.reset(); // act this.properties.context.user.setAuthenticatedUserContext(undefined, '1234'); // verify Assert.equal(undefined, this.properties.context.user.authenticatedId, "user auth id was not set"); Assert.equal(undefined, this.properties.context.user.accountId, "user account id was not set"); Assert.equal(cookieStub.notCalled, true, "cookie was not set"); Assert.equal(loggingStub.calledOnce, true, "Warning was logged"); } }); this.testCase({ name: "setAuthenticatedUserContext: handles authId special characters correctly", test: () => { // setup var authAndAccountId = ['my|||special;id', '1234']; this.properties.initialize(this.getEmptyConfig(), this.core, []); var cookieStub = this.sandbox.stub(this as any, "_setCookie"); var loggingStub = this.sandbox.stub(this.core.logger, "throwInternal"); // act this.properties.context.user.setAuthenticatedUserContext(authAndAccountId[0], authAndAccountId[1], true); // verify Assert.equal(undefined, this.properties.context.user.authenticatedId, "user auth id was not set"); Assert.equal(undefined, this.properties.context.user.accountId, "user account id was not set"); Assert.equal(cookieStub.notCalled, true, "cookie was not set"); Assert.equal(loggingStub.calledOnce, true, "Warning was logged"); } }); this.testCase({ name: "setAuthenticatedUserContext: handles accountId special characters correctly", test: () => { // setup var authAndAccountId = ['myid', '1234 5678']; this.properties.initialize(this.getEmptyConfig(), this.core, []); this.properties.context.user.clearAuthenticatedUserContext(); var cookieStub = this.sandbox.stub(this as any, "_setCookie"); var loggingStub = this.sandbox.stub(this.core.logger, "throwInternal"); // act this.properties.context.user.setAuthenticatedUserContext(authAndAccountId[0], authAndAccountId[1]); // verify Assert.equal(undefined, this.properties.context.user.authenticatedId, "user auth id was not set"); Assert.equal(undefined, this.properties.context.user.accountId, "user account id was not set"); Assert.equal(cookieStub.notCalled, true, "cookie was not set"); Assert.equal(loggingStub.calledOnce, true, "Warning was logged"); } }); this.testCase({ name: "setAuthenticatedUserContext: handles non-ascii unicode characters correctly", test: () => { // setup var authAndAccountId = ["\u05D0", "\u05D1"]; // Hebrew characters this.properties.initialize(this.getEmptyConfig(), this.core, []); var cookieStub = this.sandbox.stub(this as any, "_setCookie"); var loggingStub = this.sandbox.stub(this.core.logger, "throwInternal"); // act this.properties.context.user.setAuthenticatedUserContext(authAndAccountId[0], authAndAccountId[1], true); // verify Assert.equal(authAndAccountId[0], this.properties.context.user.authenticatedId, "user auth id was set"); Assert.equal(authAndAccountId[1], this.properties.context.user.accountId, "user account id was set"); Assert.equal(cookieStub.calledWithExactly('ai_authUser', encodeURI(authAndAccountId.join('|')) + "; path=/"), true, "user auth id cookie was set"); Assert.equal(loggingStub.notCalled, true, "No warnings"); } }); this.testCase({ name: "clearAuthenticatedUserContext: auth user and account cleared in context and cookie ", test: () => { // setup this.properties.initialize(this.getEmptyConfig(), this.core, []); this.properties.context.user.setAuthenticatedUserContext("bla", "123"); var cookieStub = this.sandbox.stub(this as any, "_delCookie"); // act this.properties.context.user.clearAuthenticatedUserContext(); // verify Assert.equal(undefined, this.properties.context.user.authenticatedId, "user auth id was cleared"); Assert.equal(undefined, this.properties.context.user.accountId, "user account id was cleared"); Assert.equal(cookieStub.calledWithExactly('ai_authUser'), true, "cookie was deleted"); } }); this.testCase({ name: "clearAuthenticatedUserContext: works correctly when auth id and account id were never set", test: () => { // setup this.properties.initialize(this.getEmptyConfig(), this.core, []); var cookieStub = this.sandbox.stub(this as any, "_delCookie"); // act this.properties.context.user.clearAuthenticatedUserContext(); // verify Assert.equal(undefined, this.properties.context.user.authenticatedId, "user auth id was cleared"); Assert.equal(undefined, this.properties.context.user.accountId, "user account id was cleared"); Assert.equal(cookieStub.calledWithExactly('ai_authUser'), true, "cookie was deleted"); } }); this.testCase({ name: "Validate telemetrycontext sets up web extension properties on TelemetryItem", test: () => { // setup this.properties.initialize(this.getEmptyConfig(), this.core, []); let context = new TelemetryContext(this.core, this.getTelemetryConfig()); context.web = { domain: "www.bing.com", userConsent: true, screenRes: "1024x768", browser: "internet explorer", browserVer: "48.0", isManual: true, browserLang: "EN" }; let telemetyItem: ITelemetryItem = { name: "test", time: new Date("2018-06-12").toISOString(), iKey: "iKey", ext: {}, baseType: "RemoteDependencyData", baseData: { id: 'some id', name: "/test/name", success: true, responseCode: 200, duration: 123, type: 'Fetch', data: 'some data', target: 'https://example.com/test/name' }, data: { property1: "val1", measurement1: 50.0, } }; context.applyWebContext(telemetyItem); let ext = telemetyItem.ext; Assert.ok(ext); Assert.equal("www.bing.com", ext.web.domain); Assert.equal("1024x768", ext.web.screenRes); Assert.equal(true, ext.web.userConsent); Assert.equal("48.0", ext.web.browserVer); Assert.equal("EN", ext.web.browserLang); Assert.equal("internet explorer", ext.web.browser); Assert.equal(true, ext.web.isManual); } }); this.testCase({ name: "validate telemetrycontext cleanup sets empty extensions to undefined", test: () => { // setup this.properties.initialize(this.getEmptyConfig(), this.core, []); const telemetyItem: ITelemetryItem = { name: "test", time: new Date("2018-06-12").toISOString(), iKey: "iKey", ext: { "user" : { "localId": "TestId", "authId": "AuthenticatedId", "id": "TestId" }, "web": {} }, tags: [{"user.accountId": "TestAccountId"}], baseType: "RemoteDependencyData", baseData: { id: 'some id', name: "/test/name", success: true, responseCode: 200, duration: 123, type: 'Fetch', data: 'some data', target: 'https://example.com/test/name' }, data: { property1: "val1", property2: "val2", measurement1: 50.0, measurement2: 1.3 } } // act const telemetrycontext = new TelemetryContext(this.core, this.getTelemetryConfig()); telemetrycontext.cleanUp(telemetyItem); // verify Assert.equal(undefined, telemetyItem.ext.web, "web was cleared"); Assert.notEqual(undefined, telemetyItem.ext.user, "user was not cleared"); } }); } private addSessionTests() { this.testCase({ name: 'Session: automaticSession session id is stored in sesId if customer does not provide session info', test: () => { this.properties.initialize(this.getEmptyConfig(), this.core, []); // Assert const item: ITelemetryItem = {name: 'item'}; this.properties.processTelemetry(item); Assert.ok(this.properties.context.getSessionId(), 'session id is stored in sesId'); Assert.equal(this.properties.context.getSessionId(), this.properties.context.sessionManager.automaticSession.id, 'automaticSession is stored in sesId') } }); this.testCase({ name: 'Session: customer session id is stored in sesId if customer provides session info', test: () => { this.properties.initialize(this.getEmptyConfig(), this.core, []); // Assert const item: ITelemetryItem = {name: 'item'}; this.properties.context.session.id = 'random id'; this.properties.processTelemetry(item); Assert.ok(this.properties.context.getSessionId(), 'session id is stored in sesId'); Assert.equal(this.properties.context.getSessionId(), 'random id', 'automaticSession is stored in sesId') } }); } private getEmptyConfig(): IConfiguration { return { instrumentationKey: 'key', extensionConfig: { AppInsightsPropertiesPlugin: { accountId: null, sessionRenewalMs: null, sessionExpirationMs: null, samplingPercentage: null, endpointUrl: null, cookieDomain: null, emitLineDelimitedJson: null, maxBatchSizeInBytes: null, maxBatchInterval: null, disableTelemetry: null, enableSessionStorageBuffer: null, isRetryDisabled: null, isBeaconApiDisabled: null, sdkExtension: null, isBrowserLinkTrackingEnabled: null, appId: null, sesId: null, getNewId: (idLength?: number) => this._getNewId(idLength) } } }; } private getTelemetryConfig(): ITelemetryConfig { return { instrumentationKey: () => "", accountId: () => "", sessionRenewalMs: () => 1000, samplingPercentage: () => 0, sessionExpirationMs: () => 1000, cookieDomain: () => null, sdkExtension: () => "", isBrowserLinkTrackingEnabled: () => true, appId: () => "", getSessionId: () => "", namePrefix: () => "", sessionCookiePostfix: () => "", userCookiePostfix: () => "", idLength: () => 22, getNewId: () => this._getNewId } } }
the_stack
import { ExtendedSocket } from 'extendedsocket' import { ActiveConnections } from 'storage/activeconnections' import { CSTeamNum } from 'gametypes/shareddefs' import { HostPacketType } from 'packets/definitions' import { UserInventory } from 'user/userinventory' import { InHostPacket } from 'packets/in/host' import { InHostItemUsed } from 'packets/in/host/itemused' import { InHostIngame_AddKillCount } from 'packets/in/host/ingame_addkillcount' import { InHostIngame_BuyItem } from 'packets/in/host/ingame_buyitem' import { InHostIngame_PlayerDeath } from 'packets/in/host/ingame_playerdeath' import { InHostIngame_PlayerSpawn } from 'packets/in/host/ingame_playerspawn' import { InHostIngame_RoundEnd } from 'packets/in/host/ingame_roundend' import { InHostSetBuyMenu } from 'packets/in/host/setbuymenu' import { InHostSetInventory } from 'packets/in/host/setinventory' import { InHostSetLoadout } from 'packets/in/host/setloadout' import { InHostTeamChanging } from 'packets/in/host/teamchanging' import { OutHostPacket } from 'packets/out/host' /** * handles incoming host type packets */ export class HostHandler { /* constructor() {} */ /** * handles the incoming host packets * @param packetData the host's packet data * @param connection the client's socket */ public async onPacket( packetData: Buffer, connection: ExtendedSocket ): Promise<boolean> { const hostPacket = new InHostPacket(packetData) const session = connection.session if (session == null) { console.error( `couldn't get session from connection ${connection.uuid}` ) return false } switch (hostPacket.packetType) { case HostPacketType.OnGameEnd: return this.onGameEnd(connection) case HostPacketType.SetInventory: return this.onSetUserInventory(hostPacket, connection) case HostPacketType.SetLoadout: return this.onSetUserLoadout(hostPacket, connection) case HostPacketType.SetBuyMenu: return this.onSetUserBuyMenu(hostPacket, connection) case HostPacketType.TeamChanging: return this.onTeamChangingRequest(packetData, connection) case HostPacketType.ItemUsed: return this.onItemUsed(hostPacket, connection) case HostPacketType.Ingame_AddPoint: return this.onIngameAddPoint(hostPacket, connection) case HostPacketType.Ingame_PlayerDeath: return this.onIngamePlayerDeath(hostPacket, connection) case HostPacketType.Ingame_RoundEnd: return this.onIngameRoundEnd(hostPacket, connection) case HostPacketType.Ingame_BuyItem: return this.onIngameBuyItem(hostPacket, connection) case HostPacketType.Ingame_PlayerSpawn: return this.onIngamePlayerSpawn(hostPacket, connection) } console.warn( 'HostHandler::onPacket: unknown host packet type %i', hostPacket.packetType ) return false } private async onGameEnd(userConn: ExtendedSocket): Promise<boolean> { const session = userConn.session if (session == null) { console.warn( `Could not get connection "${userConn.uuid}"'s session` ) return false } if (session.isInRoom() === false) { console.warn( 'User ID %i tried to end a match without being in a room', session.user.id ) return false } const currentRoom = session.currentRoom if (currentRoom == null) { console.error( `Tried to get user's ${session.user.id} room but it couldn't be found. room id: ${currentRoom.id}` ) return false } console.log( 'Ending game for room "%s" (room id %i)', currentRoom.settings.roomName, currentRoom.id ) await currentRoom.endGame() return true } private onItemUsed( hostPacket: InHostPacket, userConn: ExtendedSocket ): boolean { const itemData = new InHostItemUsed(hostPacket) const targetConn = ActiveConnections.Singleton().FindByOwnerId( itemData.userId ) const requesterSession = userConn.session const targetSession = targetConn.session if (requesterSession == null) { console.warn(`Could not get user ID's ${itemData.userId} session`) return false } if (requesterSession.isInRoom() === false) { console.warn( `User ID ${requesterSession.user.id} tried to send someone's team chaning request without being in a room` ) return false } if (targetSession == null) { console.warn( `User ID ${requesterSession.user.id} tried to send someone's team changing request with user ID ${itemData.userId} whose session is null` ) return false } const currentRoom = requesterSession.currentRoom if (currentRoom == null) { console.error( `Tried to get user's ${requesterSession.user.id} room but it couldn't be found.` ) return false } if (currentRoom.host.userId !== requesterSession.user.id) { console.warn( `User ID ${requesterSession.user.id} sent User ID ${targetSession.user.id}'s team changing request without being the room's host. Real host ID: ${currentRoom.host.userId} room "${currentRoom.settings.roomName}" (id ${currentRoom.id})` ) return false } userConn.send(OutHostPacket.itemUse(itemData.userId, itemData.itemId)) console.log( `Sending user ID ${requesterSession.user.id}'s item ${itemData.itemId} using request to host ID ${currentRoom.host.userId}, room ${currentRoom.id}` ) return true } private onTeamChangingRequest( packetData: Buffer, userConn: ExtendedSocket ): boolean { const teamData = new InHostTeamChanging(packetData) const targetConn: ExtendedSocket = ActiveConnections.Singleton().FindByOwnerId( teamData.userId ) const requesterSession = userConn.session const targetSession = targetConn.session if (requesterSession == null) { console.warn(`Could not get user ID's ${teamData.userId} session`) return false } if (requesterSession.isInRoom() === false) { console.warn( `User ID ${requesterSession.user.id} tried to send someone's team chaning request without being in a room` ) return false } if (targetSession == null) { console.warn( `User ID ${requesterSession.user.id} tried to send someone's team changing request with user ID ${teamData.userId} whose session is null` ) return false } const currentRoom = requesterSession.currentRoom if (currentRoom == null) { console.error( `Tried to get user's ${requesterSession.user.id} room but it couldn't be found.` ) return false } if (currentRoom.host.userId !== requesterSession.user.id) { console.warn( `User ID ${requesterSession.user.id} sent User ID ${targetSession.user.id}'s team changing request without being the room's host. Real host ID: ${currentRoom.host.userId} room "${currentRoom.settings.roomName}" (id ${currentRoom.id})` ) return false } if ( teamData.newTeam !== CSTeamNum.Terrorist && teamData.newTeam !== CSTeamNum.CounterTerrorist ) { console.warn( `User Id ${targetSession.user.id} tried to change his team, but the value ${teamData.newTeam} is not allowed.` ) return false } currentRoom.updateUserTeam(targetSession.user.id, teamData.newTeam) console.log( `Changing user ${requesterSession.user.id}'s team to ${teamData.newTeam} in room ${currentRoom.id}` ) return true } private async onSetUserInventory( hostPacket: InHostPacket, userConn: ExtendedSocket ): Promise<boolean> { const preloadData = new InHostSetInventory(hostPacket) const targetConn = ActiveConnections.Singleton().FindByOwnerId( preloadData.userId ) const requesterSession = userConn.session const targetSession = targetConn.session if (requesterSession == null) { console.warn( `Could not get user ID's ${preloadData.userId} session` ) return false } if (requesterSession.isInRoom() === false) { console.warn( `User ID ${requesterSession.user.id} tried to send its inventory without being in a room` ) return false } if (targetSession == null) { console.warn( `User ID ${requesterSession.user.id} tried to send its inventory to user ID ${preloadData.userId} whose session is null` ) return false } const currentRoom = requesterSession.currentRoom if (currentRoom == null) { console.error( `Tried to get user's ${requesterSession.user.id} room but it couldn't be found.` ) return false } if (currentRoom.host.userId !== requesterSession.user.id) { console.warn( `User ID ${requesterSession.user.id} sent an user's inventory request without being the room's host. Real host ID: ${currentRoom.host.userId} room "${currentRoom.settings.roomName}" (id ${currentRoom.id})` ) return false } await this.sendUserInventoryTo( requesterSession.user.id, userConn, targetSession.user.id ) console.log( `Sending user ID ${preloadData.userId}'s inventory to host ID ${currentRoom.host.userId}, room ${currentRoom.settings.roomName} (room id ${currentRoom.id})` ) return true } private async onSetUserLoadout( hostPacket: InHostPacket, sourceConn: ExtendedSocket ): Promise<boolean> { const loadoutData = new InHostSetLoadout(hostPacket) const targetConn = ActiveConnections.Singleton().FindByOwnerId( loadoutData.userId ) const requesterSession = sourceConn.session const targetSession = targetConn.session if (requesterSession == null) { console.warn(`Could not get user's ${loadoutData.userId} session`) return false } if (requesterSession.isInRoom() === false) { console.warn( 'User ID %i tried to send loadout without being in a room', requesterSession.user.id ) return false } if (targetSession == null) { console.warn( 'User ID %i tried to send its loadout to user ID %i whose session is null', requesterSession.user.id, loadoutData.userId ) return false } const currentRoom = requesterSession.currentRoom if (currentRoom == null) { console.error( `Tried to get user's ${requesterSession.user.id} room but it couldn't be found.` ) return false } if (currentRoom.host.userId !== requesterSession.user.id) { console.warn( `User ${requesterSession.user.id} sent an user's loadout request without being the room's host. Real host: ${currentRoom.host.userId} room ${currentRoom.id}` ) return false } await this.sendUserLoadoutTo(sourceConn, targetSession.user.id) console.log( `Sending user ${requesterSession.user.id}'s loadout to host ${currentRoom.host.userId}, room ${currentRoom.id}` ) return true } private async onSetUserBuyMenu( hostPacket: InHostPacket, sourceConn: ExtendedSocket ): Promise<boolean> { const buyMenuData = new InHostSetBuyMenu(hostPacket) const targetConn = ActiveConnections.Singleton().FindByOwnerId( buyMenuData.userId ) const requesterSession = sourceConn.session const targetSession = targetConn.session if (requesterSession == null) { console.warn(`Could not get user's ${buyMenuData.userId} session`) return false } if (requesterSession.isInRoom() === false) { console.warn( 'User ID %i tried to send buy menu without being in a room', requesterSession.user.id ) return false } if (targetSession == null) { console.warn( 'User ID %i tried to send its buy menu to user ID %i whose session is null', requesterSession.user.id, buyMenuData.userId ) return false } const currentRoom = requesterSession.currentRoom if (currentRoom == null) { console.error( `Tried to get user's ${requesterSession.user.id} room but it couldn't be found.` ) return false } if (currentRoom.host.userId !== requesterSession.user.id) { console.warn( `User ${requesterSession.user.id} sent an user's buy menu request without being the room's host. Real host: ${currentRoom.host.userId} room ${currentRoom.id}` ) return false } await this.sendUserBuyMenuTo(sourceConn, targetSession.user.id) console.debug( `Sending user ${requesterSession.user.id}'s buy menu to host ${currentRoom.host.userId}, room ${currentRoom.id}` ) return true } private onIngameAddPoint( hostPacket: InHostPacket, userConn: ExtendedSocket ): boolean { const pointData = new InHostIngame_AddKillCount(hostPacket) console.log( `${pointData.scorerId} scored ${pointData.newKillsNum} kills. totalKills: ${pointData.totalFrags}` ) return true } private onIngamePlayerDeath( hostPacket: InHostPacket, hostConn: ExtendedSocket ): boolean { const deathPacket = new InHostIngame_PlayerDeath(hostPacket) const curRoom = hostConn.session.currentRoom if (curRoom == null) { console.warn('The host must be in a room') return false } curRoom.onPlayerKilled(deathPacket.damageInfo) return true } private onIngameRoundEnd( hostPacket: InHostPacket, hostConn: ExtendedSocket ): boolean { const roundData = new InHostIngame_RoundEnd(hostPacket) const curRoom = hostConn.session.currentRoom if (curRoom == null) { console.warn('The host must be in a room') return false } curRoom.onRoundWon(roundData.winningTeamNum) return true } private onIngameBuyItem( hostPacket: InHostPacket, userConn: ExtendedSocket ): boolean { const buyData = new InHostIngame_BuyItem(hostPacket) console.debug(`${buyData.buyerId} bought ${buyData.GetItemBought()}`) return true } private onIngamePlayerSpawn( hostPacket: InHostPacket, userConn: ExtendedSocket ): boolean { const spawnData = new InHostIngame_PlayerSpawn(hostPacket) console.debug( `${spawnData.playerUserId} spawned at ${spawnData.spawnPoint.X} ${spawnData.spawnPoint.Y} ${spawnData.spawnPoint.Z}` ) return true } /** * send the host an user's inventory * @param hostUserId the target host's user ID * @param hostConn the target host's connection * @param targetUserId the target user's ID session */ private async sendUserInventoryTo( hostUserId: number, hostConn: ExtendedSocket, targetUserId: number ): Promise<void> { const inventory = await UserInventory.getInventory(hostUserId) hostConn.send(OutHostPacket.setInventory(targetUserId, inventory.items)) } /** * send the host an user's loadout * @param hostConn the target host's connection * @param targetUserId the target user's ID session */ private async sendUserLoadoutTo( hostConn: ExtendedSocket, targetUserId: number ): Promise<void> { hostConn.send(await OutHostPacket.setLoadout(targetUserId)) } /** * send the host an user's loadout * @param hostUserId the target host's user ID * @param hostConn the target host's connection * @param targetUserId the target user's ID session */ private async sendUserBuyMenuTo( hostConn: ExtendedSocket, targetUserId: number ): Promise<void> { hostConn.send(await OutHostPacket.setBuyMenu(targetUserId)) } }
the_stack
import AxisUtils from '@/utils/tool/AxisUtils'; import RectUtils from '@/utils/tool/RectUtils'; import MathUtils from '@/utils/MathUtils'; import { DEFAULT_TEXT_SHADOW, EDragStatus, ESortDirection } from '../../constant/annotation'; import EKeyCode from '../../constant/keyCode'; import { EDragTarget } from '../../constant/tool'; import locale from '../../locales'; import { EMessage } from '../../locales/constants'; import AttributeUtils from '../../utils/tool/AttributeUtils'; import CanvasUtils from '../../utils/tool/CanvasUtils'; import CommonToolUtils from '../../utils/tool/CommonToolUtils'; import DrawUtils from '../../utils/tool/DrawUtils'; import MarkerUtils from '../../utils/tool/MarkerUtils'; import { getPolygonPointUnderZoom } from '../../utils/tool/polygonTool'; import uuid from '../../utils/uuid'; import { BasicToolOperation, IBasicToolOperationProps } from './basicToolOperation'; import TextAttributeClass from './textAttributeClass'; interface IRectOperationProps extends IBasicToolOperationProps { drawOutSideTarget: boolean; // 是否可以在边界外进行标注 style: any; } const scope = 6; class RectOperation extends BasicToolOperation { public drawingRect?: IRect; public firstClickCoord?: ICoordinate; // 第一次点击的位置 public firstCurrentPos?: ICoordinate; // 第一次点击的 currentPos public rectList: IRect[]; public drawOutSideTarget: boolean; // 是否能在边界外进行标注 // 具体操作 public hoverRectID?: string; // 当前是否hover rect public hoverRectPointIndex: number; // 当前 hoverIndex, 依次为左上角、右上角、右下角、左下角 public hoverRectEdgeIndex: number; // 当前 hover 的边 public selectedRectID?: string; // public isFlow: boolean; // 是否进行流动 public config: IRectConfig; public markerIndex: number; // 用于列表标签定位 private _textAttributInstance?: TextAttributeClass; private dragInfo?: { dragStartCoord: ICoordinate; dragTarget: EDragTarget; changePointIndex?: number[]; // 用于存储拖拽点 / 边的下标 firstRect: IRect; // 最初的框 startTime: number; }; constructor(props: IRectOperationProps) { super(props); this.drawOutSideTarget = props.drawOutSideTarget || false; this.rectList = []; this.isFlow = true; this.config = CommonToolUtils.jsonParser(props.config); this.hoverRectEdgeIndex = -1; this.hoverRectPointIndex = -1; this.markerIndex = 0; this.setStyle(props.style); this.createNewDrawingRect = this.createNewDrawingRect.bind(this); this.getDrawingRectWithRectList = this.getDrawingRectWithRectList.bind(this); this.setSelectedIdAfterAddingDrawingRect = this.setSelectedIdAfterAddingDrawingRect.bind(this); this.getCurrentSelectedData = this.getCurrentSelectedData.bind(this); this.updateSelectedRectTextAttribute = this.updateSelectedRectTextAttribute.bind(this); this.setSelectedID = this.setSelectedID.bind(this); } public setResult(rectList: IRect[]) { this.clearActiveStatus(); this.setRectList(rectList); if (this.hasMarkerConfig) { const nextMarkerInfo = CommonToolUtils.getNextMarker(this.getCurrentPageResult(rectList), this.config.markerList); if (nextMarkerInfo) { this.setMarkerIndex(nextMarkerInfo.index); } } this.render(); } public destroy() { super.destroy(); if (this._textAttributInstance) { this._textAttributInstance.clearTextAttribute(); } } public setConfig(config: string, isClear = false) { this.config = CommonToolUtils.jsonParser(config); if (isClear === true) { this.clearResult(false); } } /** * 设置当前的结果集 * @param rectList * @param isUpload */ public setRectList(rectList: IRect[], isUpload = false) { const oldLen = this.rectList.length; this.rectList = rectList; if (oldLen !== rectList.length) { // 件数发生改变 this.emit('updatePageNumber'); } if (isUpload) { // 为了兼容外层实时同步数据 - (估计后面会干掉) this.emit('updateResult'); } } public get selectedRect() { return this.rectList.find((v) => v.id === this.selectedRectID); } public get selectedID() { return this.selectedRectID; } public get selectedText() { return this.selectedRect?.textAttribute; } get dataList() { return this.rectList; } /** * 当前页面展示的框体 */ public get currentShowList() { let rect: IRect[] = []; const [showingRect, selectedRect] = CommonToolUtils.getRenderResultList<IRect>( this.rectList, CommonToolUtils.getSourceID(this.basicResult), this.attributeLockList, this.selectedID, ); rect = showingRect; if (this.isHidden) { rect = []; } if (selectedRect) { rect.push(selectedRect); } return rect; } /** * 当前依赖状态下本页的所有框 * * @readonly * @memberof RectOperation */ public get currentPageResult() { const [showingRect] = CommonToolUtils.getRenderResultList<IRect>( this.rectList, CommonToolUtils.getSourceID(this.basicResult), [], ); return showingRect; } /** * 当前依赖状态下本页的所有框 * * @readonly * @memberof RectOperation */ public getCurrentPageResult(rectList: IRect[]) { const [showingRect] = CommonToolUtils.getRenderResultList<IRect>( rectList, CommonToolUtils.getSourceID(this.basicResult), [], ); return showingRect; } public setSelectedID(newID?: string) { this.setSelectedRectID(newID); } public setSelectedRectID(newID?: string) { const oldID = this.selectedRectID; if (newID !== oldID && oldID) { // 触发文本切换的操作 this._textAttributInstance?.changeSelected(); } if (!newID) { this._textAttributInstance?.clearTextAttribute(); } this.selectedRectID = newID; this.render(); this.emit('selectedChange'); } public setStyle(toolStyle: any) { super.setStyle(toolStyle); // 当存在文本 icon 的时候需要更改当前样式 if (this._textAttributInstance && this.config.attributeConfigurable === false) { this._textAttributInstance?.updateIcon(this.getTextIconSvg()); } } /** * 向外部提供标记的更改 * @param markerIndex */ public setMarkerIndex = (markerIndex: number) => { this.markerIndex = markerIndex; }; /** * 更改当前列表标注位置,并且设置为选中 * @param markerIndex * @returns */ public setMarkerIndexAndSelect = (markerIndex: number) => { if (!this.config.markerList) { return; } this.markerIndex = markerIndex; const markerValue = this.config.markerList[markerIndex].value; const currentRect = this.currentPageResult.find((rect) => rect.label === markerValue); if (currentRect) { this.setSelectedID(currentRect.id); if (this.config.attributeConfigurable === true) { this.setDefaultAttribute(currentRect.attribute); } } this.emit('markIndexChange'); }; /** 更新文本输入,并且进行关闭 */ public updateSelectedRectTextAttribute(newTextAttribute?: string) { if (this._textAttributInstance && newTextAttribute) { // 切换的时候如果存在 let textAttribute = newTextAttribute; if (AttributeUtils.textAttributeValidate(this.config.textCheckType, '', textAttribute) === false) { this.emit('messageError', AttributeUtils.getErrorNotice(this.config.textCheckType, this.lang)); textAttribute = ''; } this.setRectList( this.rectList.map((v) => { if (v.id === this.selectedRectID) { return { ...v, textAttribute, }; } return v; }), true, ); this.emit('updateTextAttribute'); this.render(); } } public getHoverRectID = (e: MouseEvent) => { const coordinate = this.getCoordinateUnderZoom(e); const newScope = scope; const { currentShowList } = this; if (currentShowList.length > 0) { if (this.selectedRectID) { const { selectedRect } = this; if (selectedRect) { if (RectUtils.isInRect(coordinate, selectedRect, newScope, this.zoom)) { return selectedRect.id; } } } const hoverList = currentShowList.filter((rect) => RectUtils.isInRect(coordinate, rect, newScope, this.zoom)); if (hoverList.length === 0) { return ''; } if (hoverList.length === 1) { return hoverList[0].id; } if (hoverList.length > 1) { // 判断矩形的大小, 矩形面积小的优先 const rectSizeList = hoverList .map((rect) => ({ size: rect.width * rect.height, id: rect.id })) .sort((a, b) => a.size - b.size); return rectSizeList[0].id; } } return ''; }; /** * 获取当前的选中部分的hoverIndex * ../../../param e */ public getHoverRectPointIndex(e: MouseEvent) { if (!this.selectedRect) { return -1; } return AxisUtils.returnClosePointIndex( this.getCoordinateUnderZoom(e), RectUtils.getRectPointList(this.selectedRect, this.zoom), scope + 2, ); } public getHoverRectEdgeIndex(e: MouseEvent) { if (!this.selectedRect) { return -1; } let edgeIndex = -1; const { selectedRect } = this; const edgeList = RectUtils.getRectEdgeList(selectedRect, this.zoom); const coordinate = this.getCoordinateUnderZoom(e); for (let i = 0; i < edgeList.length; i++) { const edge = edgeList[i]; const { length } = MathUtils.getFootOfPerpendicular(coordinate, edge.begin, edge.end); if (length < scope + 10) { edgeIndex = i; } } return edgeIndex; } /** * 获取当前配置下的 icon svg * @param attribute */ public getTextIconSvg(attribute = '') { return AttributeUtils.getTextIconSvg( attribute, this.config.attributeList, this.config.attributeConfigurable, this.baseIcon, ); } public onMouseDown(e: MouseEvent) { if (super.onMouseDown(e) || this.forbidMouseOperation || e.ctrlKey === true) { return; } // e.stopPropagation(); // 仅有在选中模式才能进行拖动 const dragStartCoord = this.getCoordinateUnderZoom(e); const hoverRectID = this.getHoverRectID(e); const firstRect = this.currentShowList.find((v) => v.id === this.selectedRectID); /** * 拖拽基础判断,如果包含以下行为则直接禁止操作 * 1. 不存在框体 * 2. 拖拽行为下禁止操作 - 右键 * 3. 拖拽行为下禁止操作 - 左键 + space */ if (!firstRect || e.button === 2 || (e.button === 0 && this.isSpaceKey === true)) { return; } if (this.selectedRectID) { if (this.getHoverRectPointIndex(e) > -1) { // 点的拖拽 const dragTarget = EDragTarget.Point; this.dragInfo = { dragStartCoord, dragTarget, startTime: +new Date(), firstRect, }; this.dragStatus = EDragStatus.Start; return; } if (this.getHoverRectEdgeIndex(e) > -1) { // 点的拖拽 const dragTarget = EDragTarget.Line; this.dragInfo = { dragStartCoord, dragTarget, startTime: +new Date(), firstRect, }; this.dragStatus = EDragStatus.Start; return; } } if (hoverRectID === this.selectedRectID && !this.drawingRect) { const dragTarget = EDragTarget.Plane; this.dragInfo = { dragStartCoord, dragTarget, firstRect, startTime: +new Date(), }; this.dragStatus = EDragStatus.Start; } return undefined; } public onDragMove(coordinate: ICoordinate) { if (!this.dragInfo) { return; } this.dragStatus = EDragStatus.Move; // 选中后的操作 const dragRect = RectUtils.getRectUnderZoom(this.dragInfo.firstRect, this.zoom); const { x, y, width, height } = dragRect; const offset = { x: coordinate.x - this.dragInfo.dragStartCoord.x, y: coordinate.y - this.dragInfo.dragStartCoord.y, }; // 缩放后的偏移 let selectedRect = this.rectList.filter((v) => v.id === this.selectedRectID)[0]; switch (this.dragInfo.dragTarget) { // 仅处理翻转的偏移 case EDragTarget.Plane: selectedRect = { ...selectedRect, x: x + offset.x, y: y + offset.y, width, height, }; break; case EDragTarget.Point: { let newX = x; let newY = y; let newWidth = width; let newHeight = height; switch (this.hoverRectPointIndex) { case 0: { newX = width - offset.x < 0 ? x + width : x + offset.x; newY = height - offset.y < 0 ? y + height : y + offset.y; newWidth = Math.abs(offset.x - width); newHeight = Math.abs(offset.y - height); break; } case 1: { newX = width + offset.x > 0 ? x : x + width + offset.x; newY = height - offset.y < 0 ? y + height : y + offset.y; newWidth = Math.abs(width + offset.x); newHeight = Math.abs(height - offset.y); break; } case 2: { newX = width + offset.x > 0 ? x : x + width + offset.x; newY = height + offset.y > 0 ? y : y + height + offset.y; newWidth = Math.abs(width + offset.x); newHeight = height + offset.y > 0 ? height + offset.y : Math.abs(height + offset.y); break; } case 3: { newX = width - offset.x < 0 ? x + width : x + offset.x; newY = height + offset.y > 0 ? y : y + height + offset.y; newWidth = Math.abs(offset.x - width); newHeight = height + offset.y > 0 ? height + offset.y : Math.abs(height + offset.y); break; } default: { return; } } selectedRect = { ...selectedRect, x: newX, y: newY, width: newWidth, height: newHeight, }; } break; case EDragTarget.Line: { let newX = x; let newY = y; let newWidth = width; let newHeight = height; switch (this.hoverRectEdgeIndex) { case 0: { newY = height - offset.y < 0 ? y + height : y + offset.y; newHeight = Math.abs(offset.y - height); break; } case 1: { newX = width + offset.x > 0 ? x : x + width + offset.x; newWidth = Math.abs(width + offset.x); break; } case 2: { newY = height + offset.y > 0 ? y : y + height + offset.y; newHeight = height + offset.y > 0 ? height + offset.y : Math.abs(height + offset.y); break; } case 3: { newX = width - offset.x < 0 ? x + width : x + offset.x; newWidth = Math.abs(offset.x - width); break; } default: { return; } } selectedRect = { ...selectedRect, x: newX, y: newY, width: newWidth, height: newHeight, }; break; } default: { // 都无命中,则无法进行拖拽 return; } } // 边缘判断 if (this.config.drawOutsideTarget === false) { if (this.basicResult) { if (this.basicResult?.pointList?.length > 0) { // 多边形判断 if ( RectUtils.isRectNotInPolygon(selectedRect, getPolygonPointUnderZoom(this.basicResult.pointList, this.zoom)) ) { return; } } const basicX = this.basicResult.x * this.zoom; const basicY = this.basicResult.y * this.zoom; const basicWidth = this.basicResult.width * this.zoom; const basicHeight = this.basicResult.height * this.zoom; if ( this.dragInfo.dragTarget !== EDragTarget.Plane && (selectedRect.x < basicX - 0.01 || selectedRect.y < basicY - 0.01 || selectedRect.width > basicX + basicWidth - selectedRect.x + 0.01 || selectedRect.height > basicY + basicHeight - selectedRect.y + 0.01) ) { return; } if (selectedRect.x < basicX) { selectedRect.x = basicX; } if (selectedRect.y < basicY) { selectedRect.y = basicY; } if (selectedRect.width > basicX + basicWidth - selectedRect.x) { switch (this.dragInfo.dragTarget) { case EDragTarget.Plane: selectedRect.x = basicX + basicWidth - width; break; case EDragTarget.Point: case EDragTarget.Line: if (offset.x > 0 && offset.y > 0) { selectedRect.width = basicX + basicWidth - selectedRect.x; } break; default: { return; } } } if (selectedRect.height > basicY + basicHeight - selectedRect.y) { switch (this.dragInfo.dragTarget) { case EDragTarget.Plane: selectedRect.y = basicY + basicHeight - height; break; default: { break; } } } } else { // 原图的限制 if (selectedRect.x < 0) { selectedRect.x = 0; } if (selectedRect.y < 0) { selectedRect.y = 0; } if (this.imgInfo) { switch (this.dragInfo.dragTarget) { // 仅处理翻转的偏移 case EDragTarget.Plane: if (selectedRect.x + selectedRect.width > this.imgInfo?.width) { selectedRect.x = this.imgInfo.width - width; } if (selectedRect.y + selectedRect.height > this.imgInfo?.height) { selectedRect.y = this.imgInfo.height - height; } break; default: { if ( selectedRect.x + selectedRect.width > this.imgInfo?.width || selectedRect.y + selectedRect.height > this.imgInfo?.height ) { // 对线条和点先不做延伸的判断 return; } } } } } } this.setRectList( this.rectList.map((v) => { if (v.id === selectedRect.id) { return RectUtils.getRectUnderZoom(selectedRect, 1 / this.zoom); } return v; }), ); this.render(); } public onMouseMove(e: MouseEvent) { if (super.onMouseMove(e) || this.forbidMouseOperation || !this.imgInfo) { return; } const coordinateZoom = this.getCoordinateUnderZoom(e); const coordinate = AxisUtils.changeDrawOutsideTarget( coordinateZoom, { x: 0, y: 0 }, this.imgInfo, this.config.drawOutsideTarget, this.basicResult, this.zoom, ); if (this.selectedRectID && this.dragInfo) { this.onDragMove(coordinate); return; } if (this.selectedRectID) { const hoverRectPointIndex = this.getHoverRectPointIndex(e); if (hoverRectPointIndex !== this.hoverRectPointIndex) { this.hoverRectPointIndex = hoverRectPointIndex; this.hoverRectEdgeIndex = -1; this.render(); return; } if (this.hoverRectPointIndex === -1) { // 边的检测 const hoverRectEdgeIndex = this.getHoverRectEdgeIndex(e); if (hoverRectEdgeIndex !== this.hoverRectEdgeIndex) { this.hoverRectEdgeIndex = hoverRectEdgeIndex; this.render(); return; } } } const hoverRectID = this.getHoverRectID(e); const oldHoverRectID = this.hoverRectID; this.hoverRectID = hoverRectID; if (hoverRectID !== oldHoverRectID) { this.render(); } if (this.drawingRect && this.firstClickCoord) { let { x, y } = this.firstClickCoord; let { width, height } = this.drawingRect; width = Math.abs(x - coordinate.x); // zoom 下的 width height = Math.abs(y - coordinate.y); if (coordinate.x < x) { x = coordinate.x; } if (coordinate.y < y) { y = coordinate.y; } if (this.config.drawOutsideTarget === false) { if (this.basicResult?.pointList?.length > 0) { // changeDrawOutsideTarget 最好还是在这里下功夫这里暂时进行多边形的判断 if ( RectUtils.isRectNotInPolygon( { ...this.drawingRect, x, y, width, height, }, getPolygonPointUnderZoom(this.basicResult.pointList, this.zoom), ) ) { return; } } if (coordinate.x < 0) { width = Math.abs(this.firstClickCoord.x); x = 0; } if (coordinate.y < 0) { height = Math.abs(this.firstClickCoord.y); y = 0; } if (this.imgInfo) { if (x + width > this.imgInfo.width) { width = Math.abs(this.imgInfo.width - x); } if (y + height > this.imgInfo.height) { height = Math.abs(this.imgInfo.height - y); } } } this.drawingRect = { ...this.drawingRect, x, y, width, height, }; this.render(); } return undefined; } public setAttributeLockList(attributeLockList: string[]) { this.setSelectedRectID(undefined); super.setAttributeLockList(attributeLockList); } public setBasicResult(basicResult: any) { super.setBasicResult(basicResult); this.clearActiveStatus(); } public setRectValidAndRender(id: string) { if (!id) { return; } this.setRectList( this.rectList.map((rect) => { if (rect.id === id) { return { ...rect, valid: !rect.valid, }; } return rect; }), true, ); this.render(); // 同步 rectList this.emit('updateResult'); } public createNewDrawingRect(e: MouseEvent, basicSourceID: string) { if (!this.imgInfo) { return; } const coordinateZoom = this.getCoordinateUnderZoom(e); const coordinate = AxisUtils.changeDrawOutsideTarget( coordinateZoom, { x: 0, y: 0 }, this.imgInfo, this.config.drawOutsideTarget, this.basicResult, this.zoom, ); this.setSelectedRectID(''); this.hoverRectID = ''; if (this.drawOutSideTarget) { if (coordinate.x < 0) { coordinate.x = 0; } if (coordinate.y < 0) { coordinate.y = 0; } } this.drawingRect = { ...coordinate, width: 0, height: 0, attribute: this.defaultAttribute, valid: !e.ctrlKey, id: uuid(8, 62), sourceID: basicSourceID, textAttribute: '', }; if (this.hasMarkerConfig) { const nextMarkInfo = CommonToolUtils.getNextMarker( this.currentPageResult, this.config.markerList, this.markerIndex, ); if (nextMarkInfo) { if (this.drawingRect) { this.drawingRect = { ...this.drawingRect, label: nextMarkInfo.label, }; } this.markerIndex = nextMarkInfo.index; this.emit('markIndexChange'); } else { // 不存在则不允许创建新的 this.emit('messageInfo', locale.getMessagesByLocale(EMessage.MarkerFinish, this.lang)); this.drawingRect = undefined; return; } } if (this.config.textConfigurable) { let textAttribute = ''; textAttribute = AttributeUtils.getTextAttribute( this.rectList.filter((rect) => CommonToolUtils.isSameSourceID(rect.sourceID, basicSourceID)), this.config.textCheckType, ); if (this.drawingRect) { this.drawingRect = { ...this.drawingRect, textAttribute, }; } } // 标注序号添加 Object.assign(this.drawingRect, { order: CommonToolUtils.getMaxOrder( this.rectList.filter((v) => CommonToolUtils.isSameSourceID(v.sourceID, basicSourceID)), ) + 1, }); this.firstClickCoord = { ...coordinate, }; this.firstCurrentPos = { ...this.currentPos, }; /** * 数据注入 */ if (this.dataInjectionAtCreation) { const data = this.dataInjectionAtCreation(this.drawingRect); if (data) { Object.assign(this.drawingRect, data); } } } /** * 将绘制中的框体添加进 rectList 中 * @returns */ public addDrawingRectToRectList() { if (!this.drawingRect) { return; } // 结束框的绘制 // drawingRect 为相对于原图的坐标 let { width, height } = this.drawingRect; width /= this.zoom; height /= this.zoom; // 小于最小尺寸设置为无效框 if (Math.round(width) < this.config.minWidth || Math.round(height) < this.config.minHeight) { this.emit('messageInfo', locale.getMessagesByLocale(EMessage.RectErrorSizeNotice, this.lang)); this.drawingRect = undefined; this.firstClickCoord = undefined; this.dragInfo = undefined; this.dragStatus = EDragStatus.Wait; this.render(); return; } const newRectList = this.getDrawingRectWithRectList(); this.setRectList(newRectList, true); this.history.pushHistory(this.rectList); this.setSelectedIdAfterAddingDrawingRect(); this.firstClickCoord = undefined; this.drawingRect = undefined; this.dragInfo = undefined; this.dragStatus = EDragStatus.Wait; } public setSelectedIdAfterAddingDrawingRect() { if (!this.drawingRect) { return; } if (this.config.textConfigurable) { this.setSelectedRectID(this.drawingRect.id); } else { this.setSelectedRectID(); } } public getDrawingRectWithRectList() { if (!this.drawingRect) { return this.rectList; } let { x, y, width, height } = this.drawingRect; x /= this.zoom; y /= this.zoom; width /= this.zoom; height /= this.zoom; return [ ...this.rectList, { ...this.drawingRect, x, y, width, height, }, ]; } /** * mouseup 下的鼠标右键 * @param e */ public rightMouseUp(e: MouseEvent) { const hoverRectID = this.getHoverRectID(e); const hoverRect = this.rectList.find((v) => v.id === hoverRectID); const { selectedRectID } = this; this.setSelectedRectID(undefined); if (hoverRect) { this.setDefaultAttribute(hoverRect.attribute); } if (this.drawingRect) { // 取消绘制 this.drawingRect = undefined; this.firstClickCoord = undefined; } else { // 选中操作 if (selectedRectID !== hoverRectID) { this.dblClickListener.clearRightDblClick(); } this.setSelectedRectID(hoverRectID); this.hoverRectID = ''; if (hoverRect?.label && this.hasMarkerConfig) { const markerIndex = CommonToolUtils.getCurrentMarkerIndex(hoverRect.label, this.config.markerList); if (markerIndex >= 0) { this.setMarkerIndex(markerIndex); this.emit('markIndexChange'); } } } this.render(); } public shiftRightMouseUp(e: MouseEvent) { const hoverRectID = this.getHoverRectID(e); this.emit('shiftRightMouseUp', hoverRectID); } public onMouseUp(e: MouseEvent) { if (super.onMouseUp(e) || this.forbidMouseOperation || !this.imgInfo) { return true; } if (this.dragInfo && this.dragStatus === EDragStatus.Move) { // 拖拽停止 this.dragInfo = undefined; this.dragStatus = EDragStatus.Wait; this.history.pushHistory(this.rectList); // 同步 rectList this.emit('updateResult'); return; } // shift + 右键操作 if (e.button === 2 && e.shiftKey === true) { this.shiftRightMouseUp(e); return; } // 右键关闭 if (e.button === 2) { this.rightMouseUp(e); return; } const basicSourceID = CommonToolUtils.getSourceID(this.basicResult); if (this.drawingRect) { // 结束框的绘制 this.addDrawingRectToRectList(); return; } if (e.ctrlKey === true && e.button === 0 && this.hoverRectID) { // ctrl + 左键 + hover存在,更改框属性 this.setRectValidAndRender(this.hoverRectID); return; } // 创建框 this.createNewDrawingRect(e, basicSourceID); this.render(); return undefined; } public onRightDblClick(e: MouseEvent) { super.onRightDblClick(e); const hoverRectID = this.getHoverRectID(e); if (this.selectedRectID && this.selectedRectID === hoverRectID) { // 删除 this.deleteRect(hoverRectID); } } public onKeyDown(e: KeyboardEvent) { if (!CommonToolUtils.hotkeyFilter(e)) { // 如果为输入框则进行过滤 return; } if (super.onKeyDown(e) === false) { return; } const { keyCode } = e; switch (keyCode) { case EKeyCode.Ctrl: if (this.drawingRect) { this.drawingRect = { ...this.drawingRect, valid: !e.ctrlKey, }; this.render(); } break; case EKeyCode.F: if (this.selectedRectID) { this.setRectValidAndRender(this.selectedRectID); } break; case EKeyCode.Z: this.setIsHidden(!this.isHidden); this.render(); break; case EKeyCode.Delete: this.deleteRect(this.selectedRectID); break; case EKeyCode.Tab: { e.preventDefault(); if (this.drawingRect) { // 如果正在编辑则不允许使用 Tab 切换 return; } let sort = ESortDirection.ascend; if (e.shiftKey) { sort = ESortDirection.descend; } const [showingRect, selectedRect] = CommonToolUtils.getRenderResultList<IRect>( this.rectList, CommonToolUtils.getSourceID(this.basicResult), this.attributeLockList, this.selectedRectID, ); let rectList = [...showingRect]; if (selectedRect) { rectList = [...rectList, selectedRect]; } const viewPort = CanvasUtils.getViewPort(this.canvas, this.currentPos, this.zoom); rectList = rectList.filter((rect) => CanvasUtils.inViewPort({ x: rect.x, y: rect.y }, viewPort)); const nextSelectedRect = CommonToolUtils.getNextSelectedRectID(rectList, sort, this.selectedRectID) as IRect; if (nextSelectedRect) { this.setSelectedRectID(nextSelectedRect.id); if (this.config.attributeConfigurable === true) { this.setDefaultAttribute(nextSelectedRect.attribute); } } break; } default: { if (this.config.attributeConfigurable) { const keyCode2Attribute = AttributeUtils.getAttributeByKeycode(keyCode, this.config.attributeList); if (keyCode2Attribute !== undefined) { this.setDefaultAttribute(keyCode2Attribute); } } break; } } return true; } public onKeyUp(e: KeyboardEvent) { super.onKeyUp(e); switch (e.keyCode) { case EKeyCode.Ctrl: if (this.drawingRect) { this.drawingRect = { ...this.drawingRect, valid: true, }; this.render(); } break; default: { break; } } } public onWheel(e: MouseEvent) { const oldZoom = this.zoom; let newDrawingRect; let newFirsClickCoord; if (this.drawingRect && this.firstClickCoord) { newDrawingRect = RectUtils.getRectUnderZoom(this.drawingRect, 1 / oldZoom); newFirsClickCoord = AxisUtils.changePointByZoom(this.firstClickCoord, 1 / oldZoom); } super.onWheel(e, false); if (newDrawingRect && newFirsClickCoord) { this.drawingRect = RectUtils.getRectUnderZoom(newDrawingRect, this.zoom); this.firstClickCoord = AxisUtils.changePointByZoom(newFirsClickCoord, this.zoom); } this.render(); } public textChange = (v: string) => { if (this.config.textConfigurable !== true || !this.selectedRectID) { return; } this.setRectList(AttributeUtils.textChange(v, this.selectedRectID, this.rectList), true); this.emit('selectedChange'); this.render(); }; public getCurrentSelectedData() { const { selectedRect } = this; if (!selectedRect) { return; } const toolColor = this.getColor(selectedRect.attribute); const color = selectedRect.valid ? toolColor?.valid.stroke : toolColor?.invalid.stroke; return { width: selectedRect.width * this.zoom * 0.6, textAttribute: selectedRect.textAttribute, color, }; } /** * 获取当前渲染的样式 * @param rect * @returns */ public getRenderStyle(rect: IRect) { const toolColor = this.getColor(rect.attribute); let strokeColor; let fillColor; // 是否为有效框; if (rect.valid === false) { strokeColor = toolColor?.invalid.stroke; fillColor = toolColor?.invalid.fill; } else { strokeColor = toolColor?.valid.stroke; fillColor = toolColor?.valid.fill; } return { strokeColor, fillColor, textColor: strokeColor, toolColor, }; } public renderTextAttribute() { const { selectedRect } = this; if (!this.ctx || this.config.textConfigurable !== true || !selectedRect) { return; } const { x, y, width, height, attribute, valid } = selectedRect; const newWidth = width * this.zoom * 0.6; const coordinate = AxisUtils.getOffsetCoordinate({ x, y: y + height }, this.currentPos, this.zoom); const toolColor = this.getColor(attribute); const color = valid ? toolColor?.valid.stroke : toolColor?.invalid.stroke; const distance = 4; if (!this._textAttributInstance) { // 属性文本示例 this._textAttributInstance = new TextAttributeClass({ width: newWidth, container: this.container, icon: this.getTextIconSvg(attribute), color, getCurrentSelectedData: this.getCurrentSelectedData, updateSelectedTextAttribute: this.updateSelectedRectTextAttribute, }); } if (this._textAttributInstance && !this._textAttributInstance?.isExit) { this._textAttributInstance.appendToContainer(); } this._textAttributInstance.update(`${selectedRect.textAttribute}`, { left: coordinate.x, top: coordinate.y + distance, color, width: newWidth, }); } public renderSelectedRect(rect?: IRect) { const { selectedRect } = this; if (!this.ctx || !rect || !selectedRect) { return; } const { ctx } = this; let radius = 10; const pointList = RectUtils.getRectPointList(selectedRect); const len = pointList.length; const toolColor = this.getColor(rect.attribute); pointList.forEach((v: ICoordinate, i: number) => { ctx.save(); ctx.moveTo(v.x, v.y); ctx.beginPath(); if (this.hoverRectPointIndex === i) { radius = scope + 6; } else { radius = scope; } // 是否为有效框; if (rect.valid === false) { ctx.strokeStyle = toolColor?.invalid.stroke; ctx.fillStyle = toolColor?.invalid.stroke; } else { ctx.strokeStyle = toolColor?.valid.stroke; ctx.fillStyle = toolColor?.valid.stroke; } ctx.arc(v.x * this.zoom + this.currentPos.x, v.y * this.zoom + this.currentPos.y, radius, 0, 2 * Math.PI); ctx.fill(); // 边的加深 if (this.hoverRectEdgeIndex === i) { ctx.beginPath(); ctx.lineWidth = 10; const lineColor = this.getColor(rect.attribute); const strokeStyle = rect.valid === false ? lineColor?.invalid?.stroke : lineColor?.valid?.stroke; ctx.strokeStyle = strokeStyle; ctx.moveTo(pointList[i].x * this.zoom + this.currentPos.x, pointList[i].y * this.zoom + this.currentPos.y); ctx.lineTo( pointList[(i + 1) % len].x * this.zoom + this.currentPos.x, pointList[(i + 1) % len].y * this.zoom + this.currentPos.y, ); ctx.stroke(); } ctx.restore(); }); this.renderTextAttribute(); } /** * 绘制当前框的 * @param rect 当前矩形框 * @param zoom 是否进行缩放 * @param isZoom 矩形框是否为缩放后的比例 */ public renderDrawingRect(rect: IRect, zoom = this.zoom, isZoom = false) { if (this.ctx && rect) { const { ctx, style } = this; // 不看图形信息 const { hiddenText = false } = style; ctx.save(); const { strokeColor, fillColor, textColor } = this.getRenderStyle(rect); ctx.font = 'lighter 14px Arial'; let showText = ''; if (this.config?.isShowOrder && rect.order && rect?.order > 0) { showText = `${rect.order}`; } if (rect.label && this.hasMarkerConfig) { const order = CommonToolUtils.getCurrentMarkerIndex(rect.label, this.config.markerList) + 1; showText = `${order}_${MarkerUtils.getMarkerShowText(rect.label, this.config.markerList)}`; } if (rect.attribute) { showText = `${showText} ${AttributeUtils.getAttributeShowText(rect.attribute, this.config?.attributeList)}`; } const transformRect = AxisUtils.changeRectByZoom(rect, isZoom ? zoom : this.zoom, this.currentPos); if (!hiddenText) { // 框体上方展示 DrawUtils.drawText(this.canvas, { x: transformRect.x, y: transformRect.y - 6 }, showText, { color: strokeColor, font: 'normal normal 900 14px SourceHanSansCN-Regular', ...DEFAULT_TEXT_SHADOW, textMaxWidth: 300, }); } const lineWidth = this.style?.width ?? 2; if (rect.id === this.hoverRectID || rect.id === this.selectedRectID) { DrawUtils.drawRectWithFill(this.canvas, transformRect, { color: fillColor }); } DrawUtils.drawRect(this.canvas, transformRect, { color: strokeColor, thickness: lineWidth, hiddenText: true }); ctx.restore(); // 框大小数值显示 let rectSize = `${Math.round(rect.width)} * ${Math.round(rect.height)}`; if (isZoom === true) { // 说明绘制的是缩放后的比例 rectSize = `${Math.round(rect.width / this.zoom)} * ${Math.round(transformRect.height / this.zoom)}`; } const textSizeWidth = rectSize.length * 7; if (!hiddenText) { DrawUtils.drawText( this.canvas, { x: transformRect.x + transformRect.width - textSizeWidth, y: transformRect.y + transformRect.height + 15 }, rectSize, { color: textColor, font: 'normal normal 600 14px Arial', ...DEFAULT_TEXT_SHADOW, }, ); } // 文本的输入 if (!hiddenText && rect.textAttribute && rect.id !== this.selectedRectID) { const marginTop = 0; const textWidth = Math.max(20, transformRect.width - textSizeWidth); DrawUtils.drawText( this.canvas, { x: transformRect.x, y: transformRect.y + transformRect.height + 20 + marginTop }, rect.textAttribute, { color: textColor, font: 'italic normal 900 14px Arial', textMaxWidth: textWidth, ...DEFAULT_TEXT_SHADOW, }, ); } } } /** * 渲染静态框体 */ public renderStaticRect() { if (!(this.rectList?.length > 0 && JSON.stringify(this.rectList))) { return; } const { renderEnhance = {} } = this; const [showingRect, selectedRect] = CommonToolUtils.getRenderResultList<IRect>( this.rectList, CommonToolUtils.getSourceID(this.basicResult), this.attributeLockList, this.selectedRectID, ); // 静态矩形 if (!this.isHidden) { showingRect?.forEach((rect) => { this.renderDrawingRect(rect); // 静态渲染挣增强渲染 if (renderEnhance.staticRender) { renderEnhance.staticRender( this.canvas, AxisUtils.changeRectByZoom(rect, this.zoom, this.currentPos), this.getRenderStyle(rect), ); } }); } // 选中矩形熏染 if (selectedRect) { this.renderDrawingRect(selectedRect); this.renderSelectedRect(selectedRect); if (renderEnhance.selectedRender) { renderEnhance.selectedRender( this.canvas, AxisUtils.changeRectByZoom(selectedRect, this.zoom, this.currentPos), this.getRenderStyle(selectedRect), ); } } } /** * 创建创建中的框体 * @returns */ public renderCreatingRect() { if (!this.drawingRect) { return; } const { renderEnhance = {} } = this; this.renderDrawingRect(this.drawingRect, 1, true); // 正常框体的创建 // 创建时进行渲染 if (renderEnhance.creatingRender) { renderEnhance.creatingRender( this.canvas, AxisUtils.changeRectByZoom(this.drawingRect, 1, this.currentPos), this.getRenderStyle(this.drawingRect), ); } } /** * 渲染矩形框体 */ public renderRect() { this.renderStaticRect(); this.renderCreatingRect(); } public render() { if (!this.ctx) { return; } super.render(); this.renderRect(); this.renderCursorLine(this.getLineColor(this.defaultAttribute)); } public setDefaultAttribute(defaultAttribute?: string) { const oldDefault = this.defaultAttribute; this.defaultAttribute = defaultAttribute ?? ''; if (oldDefault !== defaultAttribute) { // 如果更改 attribute 需要同步更改 style 的样式 this.changeStyle(defaultAttribute); // 触发侧边栏同步 this.emit('changeAttributeSidebar'); // 如有选中目标,则需更改当前选中的属性 const { selectedRect } = this; if (selectedRect) { this.setRectList( this.rectList.map((v) => { if (v.id === this.selectedID) { return { ...v, attribute: this.defaultAttribute, }; } return v; }), true, ); this.history.pushHistory(this.rectList); this.render(); } if (this.drawingRect) { this.drawingRect = { ...this.drawingRect, attribute: this.defaultAttribute, }; this.render(); } if (this._textAttributInstance) { if (this.attributeLockList.length > 0 && !this.attributeLockList.includes(this.defaultAttribute)) { // 属性隐藏 this._textAttributInstance.clearTextAttribute(); return; } this._textAttributInstance.updateIcon(this.getTextIconSvg(defaultAttribute)); } } } public setValid(valid: boolean) { super.setValid(valid); this.emit('updateResult'); } /** * 清楚所有的中间状态 */ public clearActiveStatus() { this.drawingRect = undefined; this.firstClickCoord = undefined; this.dragInfo = undefined; this.dragStatus = EDragStatus.Wait; this.setSelectedRectID(undefined); } public clearResult(sendMessage = true) { const newRectList: IRect[] = this.rectList.filter((rect) => rect.disableDelete === true); if (newRectList.length > 0 && sendMessage) { this.emit('messageInfo', locale.getMessagesByLocale(EMessage.ClearPartialData, this.lang)); } this.setRectList(newRectList, true); this.setSelectedRectID(undefined); } public deleteRect(rectID?: string) { if (!rectID) { return; } const selectedRect = this.rectList.find((v) => v.id === rectID); if (selectedRect?.disableDelete === true) { this.emit('messageInfo', locale.getMessagesByLocale(EMessage.DisableDelete, this.lang)); return; } this.setRectList( this.rectList.filter((v) => v.id !== rectID), true, ); this.history.pushHistory(this.rectList); this.setSelectedRectID(undefined); this._textAttributInstance?.clearTextAttribute(); this.render(); } /** * 导出结果 */ public exportData(): any[] { const { rectList } = this; return [rectList, this.basicImgInfo]; } /** 撤销 */ public undo() { const rectList = this.history.undo(); if (rectList) { if (rectList.length !== this.rectList.length) { this.setSelectedRectID(''); } this.setRectList(rectList, true); this.render(); } } /** 重做 */ public redo() { const rectList = this.history.redo(); if (rectList) { if (rectList.length !== this.rectList.length) { this.setSelectedRectID(''); } this.setRectList(rectList, true); this.render(); } } } export { RectOperation, IRectOperationProps }; export default RectOperation;
the_stack
import {Injectable} from '@angular/core'; import {Subject} from 'rxjs'; @Injectable({ providedIn: 'root' }) export class HidenavShService { data = []; mode: any = 'ios'; names = []; tabnames = []; scroll: any; requestName(){ let name = 'page'+this.names.length; this.names.push(name); return name; } requestTabName(name){ if(!this.tabnames[name]) this.tabnames[name] = []; let tabname = name+'tab'+this.tabnames[name].length; this.tabnames[name].push(tabname); return tabname; } constructor() { this.scroll = new Subject(); } initiate(name) { let names = []; for (let key in this.data) { if (this.data[key].parent == name) names.push(key); } for (let name of names) { this.initiate2(name); } if (names.length == 0) this.initiate2(name); } initiate2(name) { if (!(this.data[name] && (this.data[name].parent && this.data[this.data[name].parent] && this.data[this.data[name].parent].tabscontent && this.data[name].content && this.data[this.data[name].parent].header) || (!this.data[name].parent && this.data[name].content && this.data[name].header))) return false; let parent = this.data[name].parent; let content = this.data[name].content; if (this.data[name].lastscroll == null) this.data[name].lastscroll = 0; if (this.data[name].guardEvents == null) this.data[name].guardEvents = true; content.scrollEvents = true; if (!parent) { let header = this.data[name].header; if (this.data[name].static) { this.data[name].static.forEach(el => { el.nativeElement.style.position = 'absolute'; el.nativeElement.style.zIndex = 102; }); } if (header) { let parentElem = header.nativeElement.parentNode; let elem = header.nativeElement; if (parentElem.getAttribute('init-expanded') == 'true') this.data[name].initExpanded = true; let notchHeight = parseInt(getComputedStyle(document.documentElement).getPropertyValue("--ion-safe-area-top"), 10); this.data[name].shrinkexpandheaderHeight = parseInt(parentElem.getAttribute('header-height'), 10)+notchHeight; this.data[name].opacityFactor = parseInt(parentElem.getAttribute('opacity-factor'), 10); this.data[name].opacityColor = parentElem.getAttribute('opacity-color'); this.data[name].blurFactor = parseInt(parentElem.getAttribute('blur-factor'), 10); parentElem.style.height = this.data[name].shrinkexpandheaderHeight + 'px'; parentElem.style.overflow = 'hidden'; parentElem.style.position = 'absolute'; elem.style.position = 'absolute'; parentElem.style.width = '100%'; elem.style.width = '100%'; this.waitforelem(name, 'this.data[name].header.nativeElement.scrollHeight', 'proceedShrinkExpand'); } } else if (parent) { let header = this.data[parent].header; let tabscontentElem = this.data[parent].tabscontentElem; if (this.data[parent].static) { this.data[parent].static.forEach(el => { el.nativeElement.style.position = 'absolute'; el.nativeElement.style.zIndex = 102; }); } if (header) { let supertabsToolbar: any = tabscontentElem.nativeElement.querySelector('super-tabs-toolbar'); let parentElem = header.nativeElement.parentNode; let elem = header.nativeElement; if (parentElem.getAttribute('init-expanded') == 'true') this.data[name].initExpanded = true; if (parentElem.getAttribute('preserve-header') == 'true') { this.data[name].preserveHeader = true; this.data[parent].preserveHeader = true; } let notchHeight = parseInt(getComputedStyle(document.documentElement).getPropertyValue("--ion-safe-area-top"), 10); this.data[name].shrinkexpandheaderHeight = parseInt(parentElem.getAttribute('header-height'), 10)+notchHeight; this.data[name].opacityFactor = parseInt(parentElem.getAttribute('opacity-factor'), 10); this.data[name].opacityColor = elem.getAttribute('opacity-color'); this.data[name].blurFactor = parseInt(parentElem.getAttribute('blur-factor'), 10); parentElem.style.height = this.data[name].shrinkexpandheaderHeight + 'px'; parentElem.style.overflow = 'hidden'; parentElem.style.position = 'absolute'; elem.style.position = 'absolute'; parentElem.style.width = '100%'; elem.style.width = '100%'; supertabsToolbar.style.position = 'absolute'; supertabsToolbar.style.transform = 'translate3d(0, ' + this.data[name].shrinkexpandheaderHeight + 'px, 0)'; parentElem.style.zIndex = 101; this.waitforelemTabs(name, 'this.data[this.data[name].parent].header.nativeElement.scrollHeight', 'this.data[this.data[name].parent].tabscontentElem.nativeElement.querySelector(\'super-tabs-toolbar\').clientHeight', 'proceedShrinkExpandTabs'); } } } waitforelem(name, evaluate, func) { let x = eval(evaluate); if (!{x} || x < this.data[name].shrinkexpandheaderHeight) { window.requestAnimationFrame(this.waitforelem.bind(this, name, evaluate, func)); } else { this[func](name); } } waitforelemTabs(name, evaluate, evaluate2, func) { let x = eval(evaluate); let y = eval(evaluate2); if (!{x} || x < this.data[name].shrinkexpandheaderHeight || !{y} || y == 0) { window.requestAnimationFrame(this.waitforelemTabs.bind(this, name, evaluate, evaluate2, func)); } else { this[func](name); } } proceedShrinkExpand(name) { let parentElem = this.data[name].header.nativeElement.parentNode; let elem = this.data[name].header.nativeElement; let overlay = this.data[name].header.nativeElement.parentNode.querySelector('.overlay'); if (this.data[name].opacityColor) { overlay.style.setProperty('--color', this.data[name].opacityColor); } if (this.data[name].opacityFactor > 0) { //angular decides that opacity is bad and changes it to alpha which doesn't work lol overlay.style.setProperty('filter', 'opacity(var(--opacity))'); overlay.style.setProperty('--opacity', this.data[name].opacityFactor / 10); } if (this.data[name].blurFactor > 0) { elem.style.setProperty('filter', 'blur(var(--blur))'); elem.style.setProperty('--blur', this.data[name].blurFactor / 10); } this.data[name].shrinkexpandHeight = this.data[name].shrinkexpandheaderHeight; this.data[name].shrinkexpandHeight = this.data[name].header.nativeElement.scrollHeight; elem.style.transform = 'translate3d(0, ' + -((this.data[name].shrinkexpandHeight - this.data[name].shrinkexpandheaderHeight) / 2) + 'px, 0)'; this.data[name].content.getScrollElement().then(res => { this.data[name].contentElem = res; this.data[name].paddingTop = parseInt(window.getComputedStyle(this.data[name].contentElem)['padding-top'], 10); this.data[name].contentElem.style.paddingTop = (this.data[name].shrinkexpandHeight + this.data[name].paddingTop) + 'px'; //this.data[name].contentElem.style.marginTop = this.data[name].shrinkexpandheaderHeight + 'px'; let elemPad = document.createElement('div'); elemPad.style.cssText = 'background:rgba(0,0,0,0)'; let x = this.data[name].contentElem.scrollHeight + (this.data[name].shrinkexpandHeight - this.data[name].shrinkexpandheaderHeight); //experimental height elemPad.style.height = x + 'px'; setTimeout(() => { //check if height is still ok and adjust if not this.data[name].elemPadHeight = Math.max(0, (x - (this.data[name].contentElem.scrollHeight - this.data[name].contentElem.offsetHeight) + (this.data[name].shrinkexpandHeight - this.data[name].shrinkexpandheaderHeight))); elemPad.style.height = this.data[name].elemPadHeight + 'px'; }, 100); this.data[name].contentElem.appendChild(elemPad); let scrollDist = this.data[name].initExpanded ? 2 : (this.data[name].shrinkexpandHeight - this.data[name].shrinkexpandheaderHeight); this.data[name].content.scrollByPoint(0, scrollDist, 0).then(() => { this.data[name].contentHeight = this.data[name].contentEl.nativeElement.clientHeight; this.data[name].content.scrollEvents = true; this.data[name].content.ionScroll.subscribe(e => { if (e.detail.scrollTop == 0) { this.data[name].contentElem.style.paddingTop = 0; this.data[name].contentEl.nativeElement.style.height = (this.data[name].contentHeight - this.data[name].shrinkexpandHeight) + 'px'; this.data[name].contentEl.nativeElement.style.top = (this.data[name].shrinkexpandHeight + this.data[name].paddingTop) + 'px'; elemPad.style.height = (this.data[name].elemPadHeight + this.data[name].shrinkexpandHeight + this.data[name].paddingTop) + 'px'; } else { let s = e.detail.scrollTop; this.data[name].contentElem.style.paddingTop = (this.data[name].shrinkexpandHeight + this.data[name].paddingTop) + 'px'; this.data[name].contentEl.nativeElement.style.height = (this.data[name].contentHeight + this.data[name].shrinkexpandHeight) + 'px'; this.data[name].contentEl.nativeElement.style.top = null; this.data[name].contentElem.scrollTop = s; elemPad.style.height = this.data[name].elemPadHeight + 'px'; } if (this.data[name].initExpanded) { this.data[name].content.scrollToPoint(0, 0, 0).then(() => { this.data[name].initExpanded = false; }); } if (this.data[name].initExpanded) { this.data[name].content.scrollToPoint(0, 0, 0).then(() => { this.data[name].initExpanded = false; }); } let height = Math.max(Math.min(this.data[name].shrinkexpandHeight, this.data[name].shrinkexpandHeight - e.detail.scrollTop), this.data[name].shrinkexpandheaderHeight); elem.style.transform = 'translate3d(0, ' + -(Math.min((this.data[name].shrinkexpandHeight - this.data[name].shrinkexpandheaderHeight) / 2, e.detail.scrollTop / 2)) + 'px, 0)'; parentElem.style.height = height + 'px'; let scrollFactor = Math.min(e.detail.scrollTop / (this.data[name].shrinkexpandHeight / 2), 1); if(scrollFactor >= 0){ let currentValOpacity = overlay.style.getPropertyValue('--opacity'); let newValOpacity = this.data[name].opacityFactor / 10 * scrollFactor; if(currentValOpacity != newValOpacity) overlay.style.setProperty('--opacity', newValOpacity); let currentValBlur = elem.style.getPropertyValue('--blur'); let newValBlur = (this.data[name].blurFactor * scrollFactor)+'px'; if(currentValBlur != newValBlur) elem.style.setProperty('--blur', newValBlur); } //event emitter setTimeout(() => { this.data[name].guardEvents = false; }, 10); if (this.data[name].lastscroll != height && !this.data[name].guardEvents) { this.scroll.next({name: this.data[name].parent ? this.data[name].parent : name, height: height}); } this.data[name].lastscroll = height; // }); //catch the last tick this.data[name].content.ionScrollEnd.subscribe(() => { setTimeout(() => { if (this.data[name].contentElem.scrollTop == 0) { this.data[name].contentElem.style.paddingTop = 0; this.data[name].contentEl.nativeElement.style.height = (this.data[name].contentHeight - this.data[name].shrinkexpandHeight) + 'px'; this.data[name].contentEl.nativeElement.style.top = (this.data[name].shrinkexpandHeight + this.data[name].paddingTop) + 'px'; elemPad.style.height = (this.data[name].elemPadHeight + this.data[name].shrinkexpandHeight + this.data[name].paddingTop) + 'px'; } }, 10) }); }); }); } proceedShrinkExpandTabs(name) { let parent = this.data[name].parent; let parentElem = this.data[parent].header.nativeElement.parentNode; let elem = this.data[parent].header.nativeElement; let tabscontentElem = this.data[parent].tabscontentElem; let supertabsToolbar: any = tabscontentElem.nativeElement.querySelector('super-tabs-toolbar'); let overlay = this.data[parent].header.nativeElement.parentNode.querySelector('.overlay'); if (this.data[name].opacityColor) { overlay.style.setProperty('--color', this.data[name].opacityColor); } if (this.data[name].opacityFactor > 0) { //angular decides that opacity is bad and changes it to alpha which doesn't work lol overlay.style.setProperty('filter', 'opacity(var(--opacity))'); overlay.style.setProperty('--opacity', this.data[name].opacityFactor / 10); } if (this.data[name].blurFactor > 0) { elem.style.setProperty('filter', 'blur(var(--blur))'); elem.style.setProperty('--blur', this.data[name].blurFactor / 10); } this.data[name].shrinkexpandHeight = this.data[name].shrinkexpandheaderHeight; this.data[name].shrinkexpandHeight = elem.scrollHeight; elem.style.transform = 'translate3d(0, ' + -((this.data[name].shrinkexpandHeight - this.data[name].shrinkexpandheaderHeight) / 2) + 'px, 0)'; this.data[name].content.getScrollElement().then(res => { this.data[name].contentElem = res; this.data[name].paddingTop = parseInt(window.getComputedStyle(this.data[name].contentElem)['padding-top'], 10); this.data[name].contentElem.style.paddingTop = (this.data[name].shrinkexpandHeight + supertabsToolbar.clientHeight + this.data[name].paddingTop) + 'px'; this.data[name].contentElem.style.height = (this.data[parent].tabscontentElem.nativeElement.clientHeight) + 'px'; //this.data[name].contentElem.style.marginTop = this.data[name].shrinkexpandheaderHeight + 'px'; let elemPad = document.createElement('div'); elemPad.style.cssText = 'background:rgba(0,0,0,0)'; let x = this.data[name].contentElem.scrollHeight + (this.data[name].shrinkexpandHeight - this.data[name].shrinkexpandheaderHeight); //experimental height elemPad.style.height = x + 'px'; setTimeout(() => { //check if height is still ok and adjust if not this.data[name].elemPadHeight = Math.max(0, (x - (this.data[name].contentElem.scrollHeight - this.data[name].contentElem.offsetHeight) + (this.data[name].shrinkexpandHeight - this.data[name].shrinkexpandheaderHeight))); elemPad.style.height = this.data[name].elemPadHeight + 'px'; }, 100); this.data[name].contentElem.appendChild(elemPad); let scrollDist = this.data[name].initExpanded ? 2 : (this.data[name].shrinkexpandHeight - this.data[name].shrinkexpandheaderHeight); this.data[name].content.scrollByPoint(0, scrollDist, 0).then(() => { this.data[name].contentHeight = this.data[name].contentEl.nativeElement.clientHeight; this.data[name].content.scrollEvents = true; this.data[name].content.ionScroll.subscribe(e => { if (e.detail.scrollTop == 0) { this.data[name].contentElem.style.paddingTop = 0; this.data[name].contentEl.nativeElement.style.height = (this.data[name].contentHeight - (this.data[name].shrinkexpandHeight + supertabsToolbar.clientHeight)) + 'px'; this.data[name].contentEl.nativeElement.style.top = (this.data[name].shrinkexpandHeight + supertabsToolbar.clientHeight + this.data[name].paddingTop) + 'px'; elemPad.style.height = (this.data[name].elemPadHeight + this.data[name].shrinkexpandHeight + this.data[name].paddingTop + supertabsToolbar.clientHeight) + 'px'; } else { let s = e.detail.scrollTop; this.data[name].contentElem.style.paddingTop = (this.data[name].shrinkexpandHeight + supertabsToolbar.clientHeight + this.data[name].paddingTop) + 'px'; this.data[name].contentEl.nativeElement.style.height = (this.data[name].contentHeight + this.data[name].shrinkexpandHeight + supertabsToolbar.clientHeight) + 'px'; this.data[name].contentEl.nativeElement.style.top = null; this.data[name].contentElem.scrollTop = s; elemPad.style.height = this.data[name].elemPadHeight + 'px'; } if (this.data[name].initExpanded) { this.data[name].content.scrollToPoint(0, 0, 0).then(() => { this.data[name].initExpanded = false; }); } let height = Math.max(Math.min(this.data[name].shrinkexpandHeight, this.data[name].shrinkexpandHeight - e.detail.scrollTop), this.data[name].shrinkexpandheaderHeight); elem.style.transform = 'translate3d(0, ' + -(Math.min((this.data[name].shrinkexpandHeight - this.data[name].shrinkexpandheaderHeight) / 2, e.detail.scrollTop / 2)) + 'px, 0)'; parentElem.style.height = height + 'px'; let scrollFactor = Math.min(e.detail.scrollTop / (this.data[name].shrinkexpandHeight / 2), 1); if(scrollFactor >= 0){ let currentValOpacity = overlay.style.getPropertyValue('--opacity'); let newValOpacity = this.data[name].opacityFactor / 10 * scrollFactor; if(currentValOpacity != newValOpacity) overlay.style.setProperty('--opacity', newValOpacity); let currentValBlur = elem.style.getPropertyValue('--blur'); let newValBlur = (this.data[name].blurFactor * scrollFactor)+'px'; if(currentValBlur != newValBlur) elem.style.setProperty('--blur', newValBlur); } supertabsToolbar.style.transform = 'translate3d(0, ' + height + 'px, 0)'; //event emitter setTimeout(() => { this.data[name].guardEvents = false; }, 10); if (this.data[name].lastscroll != height && !this.data[name].guardEvents) { this.scroll.next({name: this.data[name].parent ? this.data[name].parent : name, height: height}); } this.data[name].lastscroll = height; // }); //catch the last tick this.data[name].content.ionScrollEnd.subscribe(() => { setTimeout(() => { if (this.data[name].contentElem.scrollTop == 0) { this.data[name].contentElem.style.paddingTop = 0; this.data[name].contentEl.nativeElement.style.height = (this.data[name].contentHeight - (this.data[name].shrinkexpandHeight + supertabsToolbar.clientHeight)) + 'px'; this.data[name].contentEl.nativeElement.style.top = (this.data[name].shrinkexpandHeight + supertabsToolbar.clientHeight + this.data[name].paddingTop) + 'px'; elemPad.style.height = (this.data[name].elemPadHeight + this.data[name].shrinkexpandHeight + this.data[name].paddingTop + supertabsToolbar.clientHeight) + 'px'; } }, 10) }); }); }); } resetContent(name) { if (!this.data[name].preserveHeader) { let parent = this.data[name].parent; let height = parseInt(this.data[parent].header.nativeElement.parentNode.style.height, 10); if (height <= this.data[name].shrinkexpandHeight && height > this.data[name].shrinkexpandheaderHeight || height == this.data[name].shrinkexpandheaderHeight && this.data[name].contentElem.scrollTop < (this.data[name].shrinkexpandHeight - this.data[name].shrinkexpandheaderHeight)) { this.data[name].contentElem.scrollTop = this.data[name].shrinkexpandHeight - height; } } else { let parent = this.data[name].parent; let parentElem = this.data[parent].header.nativeElement.parentNode; let elem = this.data[parent].header.nativeElement; let tabscontentElem = this.data[parent].tabscontentElem; let supertabsToolbar: any = tabscontentElem.nativeElement.querySelector('super-tabs-toolbar'); let overlay = this.data[parent].header.nativeElement.parentNode.querySelector('.overlay'); let height = Math.max(Math.min(this.data[name].shrinkexpandHeight, this.data[name].shrinkexpandHeight - this.data[name].contentElem.scrollTop), this.data[name].shrinkexpandheaderHeight); elem.style.transform = 'translate3d(0, ' + -(Math.min((this.data[name].shrinkexpandHeight - this.data[name].shrinkexpandheaderHeight) / 2, this.data[name].contentElem.scrollTop / 2)) + 'px, 0)'; parentElem.style.height = height + 'px'; overlay.style.setProperty('--opacity', this.data[name].opacityFactor / 10 * Math.min(this.data[name].contentElem.scrollTop / (this.data[name].shrinkexpandHeight / 2), 1)); elem.style.setProperty('--blur', (this.data[name].blurFactor * Math.min(this.data[name].contentElem.scrollTop / (this.data[name].shrinkexpandHeight / 2), 1)) +'px'); supertabsToolbar.style.transform = 'translate3d(0, ' + height + 'px, 0)'; this.scroll.next({name: this.data[name].parent, height: height}); } } findCurrentTab(parent) { let i = this.data[parent].supertabs.activeTabIndex; let tabs = this.data[parent].tabscontentElem.nativeElement.querySelectorAll('super-tab'); let results = []; for (let tab of tabs) { let cont = tab.querySelector('ion-content'); if (cont.attributes['hidenav-sh-content']) results.push(cont.attributes['hidenav-sh-content'].nodeValue); else results.push(null); } if (results[i] != null) { return results[i]; } return null; } public expand(parent, duration = 200) { if (this.data[parent].content) { this.data[parent].content.scrollToPoint(0, 0, duration); } else { if (!this.data[parent].preserveHeader) { let names = []; for (let key in this.data) { if (this.data[key].parent == parent) names.push(key); } for (let name of names) this.data[name].content.scrollToPoint(0, 0, duration); } else { let currentTab = this.findCurrentTab(parent); this.data[currentTab].content.scrollToPoint(0, 0, duration); } } } public shrink(parent, duration = 200) { let height = parseInt(this.data[parent].header.nativeElement.parentNode.style.height, 10); if(height > this.data[parent].shrinkexpandheaderHeight){ if (this.data[parent].content) { this.data[parent].content.scrollToPoint(0, (this.data[parent].shrinkexpandHeight - this.data[parent].shrinkexpandheaderHeight), duration); }else{ if (!this.data[parent].preserveHeader) { let names = []; for (let key in this.data) { if (this.data[key].parent == parent) names.push(key); } for (let name of names) { this.data[name].content.scrollToPoint(0, (this.data[name].shrinkexpandHeight - this.data[name].shrinkexpandheaderHeight), duration); } } else { let currentTab = this.findCurrentTab(parent); this.data[currentTab].content.scrollToPoint(0, (this.data[currentTab].shrinkexpandHeight - this.data[currentTab].shrinkexpandheaderHeight), duration); } } } } public toggle(parent, duration = 200) { if (this.data[parent].content) { let height = parseInt(this.data[parent].header.nativeElement.parentNode.style.height, 10); if (height < this.data[parent].shrinkexpandHeight) this.data[parent].content.scrollToPoint(0, 0, duration); else this.data[parent].content.scrollToPoint(0, (this.data[parent].shrinkexpandHeight - this.data[parent].shrinkexpandheaderHeight), duration); } else { if (!this.data[parent].preserveHeader) { let names = []; for (let key in this.data) { if (this.data[key].parent == parent) names.push(key); } let height = parseInt(this.data[parent].header.nativeElement.parentNode.style.height, 10); for (let name of names) { if (height < this.data[name].shrinkexpandHeight) this.data[name].content.scrollToPoint(0, 0, duration); else this.data[name].content.scrollToPoint(0, (this.data[name].shrinkexpandHeight - this.data[name].shrinkexpandheaderHeight), duration); } } else { let currentTab = this.findCurrentTab(parent); let height = parseInt(this.data[parent].header.nativeElement.parentNode.style.height, 10); if (height < this.data[currentTab].shrinkexpandHeight) this.data[currentTab].content.scrollToPoint(0, 0, duration); else this.data[currentTab].content.scrollToPoint(0, (this.data[currentTab].shrinkexpandHeight - this.data[currentTab].shrinkexpandheaderHeight), duration); } } } }
the_stack
import { createEffect, Effect, Event, /*::type*/ CompositeName, /*::type*/ kind, } from 'effector' const typecheck = '{global}' test('createEffect', () => { const createEffect_effect1: Effect<number, string> = createEffect() const createEffect_effect2 = createEffect('', { handler: createEffect_effect1, }) const createEffect_effect3 = createEffect('', { handler() { return 'foo' }, }) const createEffect_effect4: Effect<number, string> = createEffect('fx 4') const createEffect_effect5: Effect<number, string> = createEffect({ name: 'fx 5', }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) describe('createEffect(handler)', () => { test('createEffect<P, D>(handler)', () => { const fx1: Effect<string, number> = createEffect<string, number>( word => word.length, ) const fx2: Effect<string, number> = createEffect<string, number>( (word: string) => word.length, ) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('createEffect<P, D, F>(handler)', () => { //prettier-ignore const fx1: Effect<string, number, TypeError> = createEffect<string, number, TypeError>(word => word.length) //prettier-ignore const fx2: Effect<string, number, TypeError> = createEffect<string, number, TypeError>((word: string) => word.length) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('createEffect<typeof handler>(handler)', () => { const handler = (word: string) => word.length const fx: Effect<string, number> = createEffect<typeof handler>(handler) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('createEffect<typeof handler, Error>(handler)', () => { const handler = (word: string) => word.length //prettier-ignore const fx: Effect<string, number, TypeError> = createEffect<typeof handler, TypeError>(handler) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('type inference support', () => { const fx: Effect<string, number> = createEffect( (word: string) => word.length, ) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('edge case with function in params', () => { type Params = (x: number) => string const fx1: Effect<Params, string> = createEffect<Params, string>(fn => fn(0), ) const fx2: Effect<Params, string> = createEffect<Params, string>( (fn: Params) => fn(0), ) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) }) describe('single generic', () => { type SyncFn = (_: string) => number type AsyncFn = (_: string) => Promise<number> describe('with config', () => { describe('valid case', () => { test('use sync generic, give sync handler', () => { const foo: Effect<string, number> = createEffect<SyncFn>({ handler: (_: string) => 0, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('use sync generic, give async handler', () => { const foo: Effect<string, number> = createEffect<SyncFn>({ handler: async (_: string) => 0, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 7, '(handler: SyncFn): Effect<string, number, Error>', gave the following error. Argument of type '{ handler: (_: string) => Promise<number>; }' is not assignable to parameter of type 'SyncFn'. Object literal may only specify known properties, and 'handler' does not exist in type 'SyncFn'. Overload 2 of 7, '(config: { name?: string | undefined; handler: SyncFn; sid?: string | undefined; }): Effect<string, number, Error>', gave the following error. Type '(_: string) => Promise<number>' is not assignable to type 'SyncFn'. Type 'Promise<number>' is not assignable to type 'number'. " `) }) test('use async generic, give sync handler', () => { const foo: Effect<string, number> = createEffect<AsyncFn>({ handler: (_: string) => 0, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 7, '(handler: AsyncFn): Effect<string, number, Error>', gave the following error. Argument of type '{ handler: (_: string) => number; }' is not assignable to parameter of type 'AsyncFn'. Object literal may only specify known properties, and 'handler' does not exist in type 'AsyncFn'. Overload 2 of 7, '(config: { name?: string | undefined; handler: AsyncFn; sid?: string | undefined; }): Effect<string, number, Error>', gave the following error. Type '(_: string) => number' is not assignable to type 'AsyncFn'. Type 'number' is not assignable to type 'Promise<number>'. " `) }) test('use async generic, give async handler', () => { const foo: Effect<string, number> = createEffect<AsyncFn>({ handler: async (_: string) => 0, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) }) test('config type mismatch (should fail)', () => { const foo = createEffect<SyncFn>({ async handler(_: string) { return '--' }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 7, '(handler: SyncFn): Effect<string, number, Error>', gave the following error. Argument of type '{ handler(_: string): Promise<string>; }' is not assignable to parameter of type 'SyncFn'. Object literal may only specify known properties, and 'handler' does not exist in type 'SyncFn'. Overload 2 of 7, '(config: { name?: string | undefined; handler: SyncFn; sid?: string | undefined; }): Effect<string, number, Error>', gave the following error. Type '(_: string) => Promise<string>' is not assignable to type 'SyncFn'. Type 'Promise<string>' is not assignable to type 'number'. " `) }) test('non-function generic', () => { const foo: Effect<string, number> = createEffect<string>({ async handler(_: string) { return '--' }, }) expect(typecheck).toMatchInlineSnapshot(` " Type 'string' does not satisfy the constraint 'Function'. " `) }) }) describe('without config', () => { test('function generic', () => { const foo: Effect<string, number> = createEffect<SyncFn>() expect(typecheck).toMatchInlineSnapshot(` " Expected 1-2 arguments, but got 0. " `) }) test('non-function generic', () => { const foo = createEffect<string>() expect(typecheck).toMatchInlineSnapshot(` " Expected 1-2 arguments, but got 0. " `) }) }) }) test('#(properties)', () => { const effect = createEffect() const kind1: kind = effect.kind const shortName: string = effect.shortName const compositeName: CompositeName = effect.compositeName const computed = effect.map(() => 'hello') const kind2: kind = computed.kind const shortName1: string = computed.shortName const compositeName1: CompositeName = computed.compositeName expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('#use', () => { const effect1 = createEffect() const foo = createEffect<number, string, any>() effect1.use(arg => Promise.resolve('foo')) //@ts-expect-error effect1.use(foo) expect(typecheck).toMatchInlineSnapshot(` " Argument of type 'Effect<number, string, any>' is not assignable to parameter of type '(params: unknown) => unknown'. Types of parameters 'params' and 'params' are incompatible. Type 'unknown' is not assignable to type 'number'. " `) }) describe('#filter', () => { it('should filter values (should be ok)', () => { const fx = createEffect<number, string, any>() fx.use(params => String(params)) const filteredEvent: Event<number> = fx.filter({ fn: params => params % 2 === 0, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) it('should return correct event type (should fail)', () => { const fx = createEffect<number, string, any>() fx.use(params => String(params)) //@ts-expect-error const filteredEvent: Event<boolean> = fx.filter({ fn: params => params % 2 === 0, }) expect(typecheck).toMatchInlineSnapshot(` " Type 'Event<number>' is not assignable to type 'Event<boolean>'. Types of property 'watch' are incompatible. Type '(watcher: (payload: number) => any) => Subscription' is not assignable to type '(watcher: (payload: boolean) => any) => Subscription'. Types of parameters 'watcher' and 'watcher' are incompatible. Types of parameters 'payload' and 'payload' are incompatible. Type 'number' is not assignable to type 'boolean'. " `) }) }) describe('#filterMap', () => { it('should filter and map values (should be ok)', () => { const fx = createEffect<number | string | boolean, string, any>() fx.use(params => String(params)) const filteredEvent: Event<string> = fx.filterMap(params => { if (params !== false) { return String(params) } }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) it('should return correct event type (should fail)', () => { const fx = createEffect<string, string, any>() fx.use(params => String(params)) //@ts-expect-error const filteredEvent: Event<number | void> = fx.filterMap(params => { if (params.length > 0) { return params.length } }) expect(typecheck).toMatchInlineSnapshot(` " Type 'Event<number>' is not assignable to type 'Event<number | void>'. Types of parameters 'payload' and 'payload' are incompatible. Type 'number | void' is not assignable to type 'number'. Type 'void' is not assignable to type 'number'. " `) }) }) it('should pass', () => { const handler = (_: any) => {} const effect = createEffect<any, any, any>({handler}) effect(1) effect('') expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) it('should allow any value', () => { const handler = (_: any) => {} const effect = createEffect({handler}) effect(1) effect('') expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) describe('void params', () => { describe('should allow only calls without arguments', () => { test('createEffect(config)', () => { const handler = async () => 'ok' const effect = createEffect({handler}) //@ts-expect-error effect(1) effect() expect(typecheck).toMatchInlineSnapshot(` " Argument of type 'number' is not assignable to parameter of type 'void'. " `) }) test('createEffect(name, config)', () => { const handler = async () => 'ok' const effect = createEffect('effect', {handler}) //@ts-expect-error effect(1) effect() expect(typecheck).toMatchInlineSnapshot(` " Argument of type 'number' is not assignable to parameter of type 'void'. " `) }) }) describe('with handler', () => { test('handler returns void', () => { const handler = () => {} const effect = createEffect({handler}) effect() expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('handler returns value', () => { const handler = () => 'ok' const effect = createEffect({handler}) const result: Promise<string> = effect() expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) }) test('with use', () => { const handler = () => {} const effect = createEffect('').use(handler) effect() expect(typecheck).toMatchInlineSnapshot(` " Expected 1 arguments, but got 0. " `) }) describe('with createEffect(handler)', () => { test('void params should allow only call without arguments', () => { const fx = createEffect(() => 'ok') fx() //@ts-expect-error fx(1) expect(typecheck).toMatchInlineSnapshot(` " Argument of type 'number' is not assignable to parameter of type 'void'. " `) }) test('optional params should allow call with and without arguments', () => { const fx = createEffect((params = 1) => 'ok') const assert: Effect<number | void, 'ok'> = fx fx() fx(1) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) }) describe('with createEffect<P, D, F>(handler)', () => { test('void params should allow only call without arguments', () => { const fx = createEffect<void, string, TypeError>(() => 'ok') fx() //@ts-expect-error fx(1) expect(typecheck).toMatchInlineSnapshot(` " Argument of type 'number' is not assignable to parameter of type 'void'. " `) }) test('optional params should allow call with and without arguments', () => { const fx = createEffect<number | void, 'ok', TypeError>( (params = 1) => 'ok', ) fx() fx(1) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) }) }) describe('nested effects', () => { describe('with handler', () => { it('support nesting (should be ok)', () => { const nestedEffect: Effect<string, string> = createEffect() const parentEffect: Effect<string, string> = createEffect({ handler: nestedEffect, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('no false-positive (should be type error)', () => { const nestedEffect: Effect<string, string> = createEffect() //@ts-expect-error const parentEffect: Effect<number, number> = createEffect( 'should not throw', { handler: nestedEffect, }, ) expect(typecheck).toMatchInlineSnapshot(` " Type 'Effect<string, string, Error>' is not assignable to type 'Effect<number, number, Error>'. The types of 'done.watch' are incompatible between these types. Type '(watcher: (payload: { params: string; result: string; }) => any) => Subscription' is not assignable to type '(watcher: (payload: { params: number; result: number; }) => any) => Subscription'. Types of parameters 'watcher' and 'watcher' are incompatible. Types of parameters 'payload' and 'payload' are incompatible. Type '{ params: string; result: string; }' is not assignable to type '{ params: number; result: number; }'. " `) }) }) test('with use', () => {}) }) describe('optional params', () => { describe('inference of optional argument type from handler type', () => { it('should allow calls with and w/o arguments', () => { const handler = (params = 0) => params const effect = createEffect({handler}) effect(1) effect() expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) it('should allow calls with and w/o arguments in case of `params?: any`', () => { const handler = (params?: any) => params const effect = createEffect({handler}) effect('really anything') effect() expect(typecheck).toMatchInlineSnapshot(` " Expected 1 arguments, but got 0. " `) }) }) })
the_stack
import * as ts from "typescript"; import * as lua from "../../../LuaAST"; import { getOrUpdate } from "../../../utils"; import { FunctionVisitor, TransformationContext } from "../../context"; import { AnnotationKind, getTypeAnnotations } from "../../utils/annotations"; import { annotationRemoved } from "../../utils/diagnostics"; import { createDefaultExportIdentifier, createExportedIdentifier, hasDefaultExportModifier, isSymbolExported, } from "../../utils/export"; import { createSelfIdentifier, unwrapVisitorResult } from "../../utils/lua-ast"; import { createSafeName, isUnsafeName } from "../../utils/safe-names"; import { transformToImmediatelyInvokedFunctionExpression } from "../../utils/transform"; import { transformIdentifier } from "../identifier"; import { createDecoratingExpression, transformDecoratorExpression } from "./decorators"; import { transformAccessorDeclarations } from "./members/accessors"; import { createConstructorName, transformConstructorDeclaration } from "./members/constructor"; import { createPropertyDecoratingExpression, transformClassInstanceFields, transformStaticPropertyDeclaration, } from "./members/fields"; import { createMethodDecoratingExpression, transformMethodDeclaration } from "./members/method"; import { checkForLuaLibType } from "./new"; import { createClassSetup } from "./setup"; import { getExtendedNode, getExtendedType, isStaticNode } from "./utils"; export const transformClassDeclaration: FunctionVisitor<ts.ClassLikeDeclaration> = (declaration, context) => { // If declaration is a default export, transform to export variable assignment instead if (hasDefaultExportModifier(declaration)) { const left = createExportedIdentifier(context, createDefaultExportIdentifier(declaration)); const right = transformClassAsExpression(declaration, context); return [lua.createAssignmentStatement(left, right, declaration)]; } const { statements } = transformClassLikeDeclaration(declaration, context); return statements; }; export const transformThisExpression: FunctionVisitor<ts.ThisExpression> = node => createSelfIdentifier(node); export function transformClassAsExpression( expression: ts.ClassLikeDeclaration, context: TransformationContext ): lua.Expression { return transformToImmediatelyInvokedFunctionExpression( context, () => { const { statements, name } = transformClassLikeDeclaration(expression, context); return { statements: unwrapVisitorResult(statements), result: name }; }, expression ); } const classSuperInfos = new WeakMap<TransformationContext, ClassSuperInfo[]>(); interface ClassSuperInfo { className: lua.Identifier; extendedTypeNode?: ts.ExpressionWithTypeArguments; } function transformClassLikeDeclaration( classDeclaration: ts.ClassLikeDeclaration, context: TransformationContext, nameOverride?: lua.Identifier ): { statements: lua.Statement[]; name: lua.Identifier } { let className: lua.Identifier; if (nameOverride !== undefined) { className = nameOverride; } else if (classDeclaration.name !== undefined) { className = transformIdentifier(context, classDeclaration.name); } else { // TypeScript error className = lua.createAnonymousIdentifier(); } const annotations = getTypeAnnotations(context.checker.getTypeAtLocation(classDeclaration)); if (annotations.has(AnnotationKind.Extension)) { context.diagnostics.push(annotationRemoved(classDeclaration, AnnotationKind.Extension)); } if (annotations.has(AnnotationKind.MetaExtension)) { context.diagnostics.push(annotationRemoved(classDeclaration, AnnotationKind.MetaExtension)); } // Get type that is extended const extendedTypeNode = getExtendedNode(context, classDeclaration); const extendedType = getExtendedType(context, classDeclaration); const superInfo = getOrUpdate(classSuperInfos, context, () => []); superInfo.push({ className, extendedTypeNode }); if (extendedType) { checkForLuaLibType(context, extendedType); } // Get all properties with value const properties = classDeclaration.members.filter(ts.isPropertyDeclaration).filter(member => member.initializer); // Divide properties into static and non-static const instanceFields = properties.filter(prop => !isStaticNode(prop)); const result: lua.Statement[] = []; let localClassName: lua.Identifier; if (isUnsafeName(className.text)) { localClassName = lua.createIdentifier( createSafeName(className.text), undefined, className.symbolId, className.text ); lua.setNodePosition(localClassName, className); } else { localClassName = className; } result.push(...createClassSetup(context, classDeclaration, className, localClassName, extendedType)); // Find first constructor with body const constructor = classDeclaration.members.find( (n): n is ts.ConstructorDeclaration => ts.isConstructorDeclaration(n) && n.body !== undefined ); if (constructor) { // Add constructor plus initialization of instance fields const constructorResult = transformConstructorDeclaration( context, constructor, localClassName, instanceFields, classDeclaration ); if (constructorResult) result.push(constructorResult); } else if (!extendedType) { // Generate a constructor if none was defined in a base class const constructorResult = transformConstructorDeclaration( context, ts.factory.createConstructorDeclaration([], [], [], ts.factory.createBlock([], true)), localClassName, instanceFields, classDeclaration ); if (constructorResult) result.push(constructorResult); } else if (instanceFields.length > 0) { // Generate a constructor if none was defined in a class with instance fields that need initialization // localClassName.prototype.____constructor = function(self, ...) // baseClassName.prototype.____constructor(self, ...) // ... const constructorBody = transformClassInstanceFields(context, instanceFields); const superCall = lua.createExpressionStatement( lua.createCallExpression( lua.createTableIndexExpression( context.transformExpression(ts.factory.createSuper()), lua.createStringLiteral("____constructor") ), [createSelfIdentifier(), lua.createDotsLiteral()] ) ); constructorBody.unshift(superCall); const constructorFunction = lua.createFunctionExpression( lua.createBlock(constructorBody), [createSelfIdentifier()], lua.createDotsLiteral(), lua.FunctionExpressionFlags.Declaration ); result.push( lua.createAssignmentStatement(createConstructorName(localClassName), constructorFunction, classDeclaration) ); } // Transform accessors for (const member of classDeclaration.members) { if (!ts.isAccessor(member)) continue; const accessors = context.resolver.getAllAccessorDeclarations(member); if (accessors.firstAccessor !== member) continue; const accessorsResult = transformAccessorDeclarations(context, accessors, localClassName); if (accessorsResult) { result.push(accessorsResult); } } const decorationStatements: lua.Statement[] = []; for (const member of classDeclaration.members) { if (ts.isAccessor(member)) { const expression = createPropertyDecoratingExpression(context, member, localClassName); if (expression) decorationStatements.push(lua.createExpressionStatement(expression)); } else if (ts.isMethodDeclaration(member)) { const statement = transformMethodDeclaration(context, member, localClassName); if (statement) result.push(statement); if (member.body) { const statement = createMethodDecoratingExpression(context, member, localClassName); if (statement) decorationStatements.push(statement); } } else if (ts.isPropertyDeclaration(member)) { if (isStaticNode(member)) { const statement = transformStaticPropertyDeclaration(context, member, localClassName); if (statement) decorationStatements.push(statement); } const expression = createPropertyDecoratingExpression(context, member, localClassName); if (expression) decorationStatements.push(lua.createExpressionStatement(expression)); } } result.push(...decorationStatements); // Decorate the class if (classDeclaration.decorators) { const decoratingExpression = createDecoratingExpression( context, classDeclaration.kind, classDeclaration.decorators.map(d => transformDecoratorExpression(context, d)), localClassName ); const decoratingStatement = lua.createAssignmentStatement(localClassName, decoratingExpression); result.push(decoratingStatement); } superInfo.pop(); return { statements: result, name: className }; } export const transformSuperExpression: FunctionVisitor<ts.SuperExpression> = (expression, context) => { const superInfos = getOrUpdate(classSuperInfos, context, () => []); const superInfo = superInfos[superInfos.length - 1]; if (!superInfo) return lua.createAnonymousIdentifier(expression); const { className, extendedTypeNode } = superInfo; // Using `super` without extended type node is a TypeScript error const extendsExpression = extendedTypeNode?.expression; let baseClassName: lua.AssignmentLeftHandSideExpression | undefined; if (extendsExpression && ts.isIdentifier(extendsExpression)) { const symbol = context.checker.getSymbolAtLocation(extendsExpression); if (symbol && !isSymbolExported(context, symbol)) { // Use "baseClassName" if base is a simple identifier baseClassName = transformIdentifier(context, extendsExpression); } } if (!baseClassName) { // Use "className.____super" if the base is not a simple identifier baseClassName = lua.createTableIndexExpression(className, lua.createStringLiteral("____super"), expression); } return lua.createTableIndexExpression(baseClassName, lua.createStringLiteral("prototype")); };
the_stack
import { expect, use } from "chai"; import * as Fs from "fs"; import * as Nock from "nock"; import * as Path from "path"; import * as Sinon from "sinon"; import * as Temp from "temp"; import * as ChaiAsPromised from "chai-as-promised"; use(ChaiAsPromised); import ReleaseBinaryCommand from "../../../../src/commands/distribute/release"; import { CommandArgs, CommandResult, CommandFailedResult } from "../../../../src/util/commandline"; Temp.track(); describe("release command", () => { const fakeAppOwner = "fakeAppOwner"; const fakeAppName = "fakeAppName"; const fakeAppIdentifier = `${fakeAppOwner}/${fakeAppName}`; const fakeToken = "c1o3d3e7"; const fakeReleaseUploadingId = "00000000-0000-0000-0000-000000000001"; const fakeReleaseId = "1"; const fakeReleaseUrl = "/fake/release/url/" + fakeReleaseId; const fakeDistributionGroupName = "fakeDistributionGroupName"; const fakeDistributionGroupName2 = "fakeDistributionGroupName2"; const fakeStoreName = "fakeStoreName"; const fakeGuid = "00000000-0000-0000-0000-000000000000"; const fakeUploadUrl = `/upload/upload_chunk/${fakeGuid}`; const fakeStoreType = "googleplay"; const fakeStoreTrack = "alpha"; const fakeHost = "http://localhost:1700"; const version = "1.0"; const shortVersion = "1"; const fakeUrlEncodedToken = "fakeUrlEncodedToken"; const releaseFileName = "releaseBinaryFile.apk"; const releaseNotesFileName = "releaseNotesFile.txt"; const releaseFileContent = "Hello World!"; const releaseNotes = "Release Notes for v1"; let tmpFolderPath: string; let uploadSpy: Sinon.SinonSpy; let postSymbolSpy: Sinon.SinonSpy; let patchSymbolSpy: Sinon.SinonSpy; let distributeSpy: Sinon.SinonSpy; let expectedRequestsScope: Nock.Scope; let skippedRequestsScope: Nock.Scope; before(() => { Nock.disableNetConnect(); }); beforeEach(() => { tmpFolderPath = Temp.mkdirSync("releaseTest"); uploadSpy = Sinon.spy(); postSymbolSpy = Sinon.spy(); patchSymbolSpy = Sinon.spy(); distributeSpy = Sinon.spy(); }); context("Successful requests", () => { beforeEach(() => { expectedRequestsScope = setupSuccessfulUploadChunkResponse( setupSuccessfulUploadFinishedResponse( setupSuccessfulGetUploadResponse( setupSuccessfulSetUploadMetadataResponse( setupSuccessfulPostUploadResponse(setupSuccessfulPatchUploadFinishedResponse(Nock(fakeHost))) ) ) ) ); }); describe("when all network requests are successful (group)", () => { beforeEach(() => { expectedRequestsScope = setupSuccessfulGetDistributionGroupUsersResponse( fakeDistributionGroupName, setupSuccessfulAddGroupResponse( setupSuccessfulCreateReleaseResponse( setupSuccsessFulGetDistributionGroupResponse(fakeDistributionGroupName, expectedRequestsScope) ) ) ); }); it("uploads release with release notes text", async () => { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); // Act const command = prepareTestCommand(["-f", releaseFilePath, "-r", releaseNotes, "-g", fakeDistributionGroupName]); const result = await command.execute(); // Assert testCommandSuccess(result, expectedRequestsScope); }); it("uploads release with release notes file", async () => { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); const releaseNotesFilePath = createFile(tmpFolderPath, releaseNotesFileName, releaseNotes); // Act const command = prepareTestCommand(["-f", releaseFilePath, "-R", releaseNotesFilePath, "-g", fakeDistributionGroupName]); const result = await command.execute(); // Assert testCommandSuccess(result, expectedRequestsScope); }); }); describe("when all network requests are successful (multi-group)", () => { beforeEach(() => { expectedRequestsScope = setupSuccessfulGetDistributionGroupUsersResponse( fakeDistributionGroupName, setupSuccessfulGetDistributionGroupUsersResponse( fakeDistributionGroupName2, setupSuccessfulAddGroupResponse( setupSuccessfulAddGroupResponse( setupSuccsessFulGetDistributionGroupResponse( fakeDistributionGroupName, setupSuccsessFulGetDistributionGroupResponse(fakeDistributionGroupName2, expectedRequestsScope) ) ) ) ) ); }); it("uploads release and distributes to multiple groups", async () => { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); // Act const command = prepareTestCommand([ "-f", releaseFilePath, "-g", `${fakeDistributionGroupName},${fakeDistributionGroupName2}`, ]); const result = await command.execute(); // Assert testCommandSuccess(result, expectedRequestsScope); }); }); describe("when all network requests are successful (store)", () => { beforeEach(() => { expectedRequestsScope = setupSuccessfulGetStoreDetailsResponse( setupSuccessfulCreateReleaseResponse(setupSuccessfulAddStoreResponse(expectedRequestsScope), false) ); }); it("uploads release with release notes text", async () => { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); // Act const command = prepareTestCommand(["-f", releaseFilePath, "-r", releaseNotes, "-s", fakeStoreName]); const result = await command.execute(); // Assert testCommandSuccess(result, expectedRequestsScope); }); it("uploads release with release notes file", async () => { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); const releaseNotesFilePath = createFile(tmpFolderPath, releaseNotesFileName, releaseNotes); // Act const command = prepareTestCommand(["-f", releaseFilePath, "-R", releaseNotesFilePath, "-s", fakeStoreName]); const result = await command.execute(); // Assert testCommandSuccess(result, expectedRequestsScope); }); }); describe("when all network requests are successful (no release notes)", () => { beforeEach(() => { expectedRequestsScope = setupSuccessfulGetStoreDetailsResponse(setupSuccessfulAddStoreResponse(Nock(fakeHost))); }); it("uploads release with neither release notes nor file to Google Play Store", async () => { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); // Act const command = prepareTestCommand(["-f", releaseFilePath, "-s", fakeStoreName]); const result = await command.execute(); // Assert testCommandSuccess(result, expectedRequestsScope); }); }); }); context("build-version", () => { const zipFileName = "binary.zip"; const msiFileName = "binary.msi"; const pkgFileName = "binary.pkg"; const dmgFileName = "binary.dmg"; const buildVersion = "sample-build-version"; const buildNumber = "sample-build-number"; describe("when build version specified", () => { beforeEach(() => { expectedRequestsScope = setupSuccessfulUploadChunkResponse( setupSuccessfulGetDistributionGroupUsersResponse( fakeDistributionGroupName, setupSuccessfulPostUploadResponse( setupSuccessfulUploadFinishedResponse( setupSuccessfulPatchUploadFinishedResponse( setupSuccessfulGetUploadResponse( setupSuccessfulSetUploadMetadataResponse( setupSuccessfulAddGroupResponse( setupSuccsessFulGetDistributionGroupResponse(fakeDistributionGroupName, Nock(fakeHost)) ) ) ) ) ) ) ) ); }); it("should return success for zip file", async () => { // Arrange const releaseFilePath = createFile(tmpFolderPath, zipFileName, releaseFileContent); // Act const command = prepareTestCommand(["-f", releaseFilePath, "-g", fakeDistributionGroupName, "-b", buildVersion]); const result = await command.execute(); // Assert testCommandSuccess(result, expectedRequestsScope); Sinon.assert.calledWith(postSymbolSpy, Sinon.match({ build_version: buildVersion })); }); it("should return success for msi file", async () => { // Arrange const releaseFilePath = createFile(tmpFolderPath, msiFileName, releaseFileContent); // Act const command = prepareTestCommand(["-f", releaseFilePath, "-g", fakeDistributionGroupName, "-b", buildVersion]); const result = await command.execute(); // Assert testCommandSuccess(result, expectedRequestsScope); Sinon.assert.calledWith(postSymbolSpy, Sinon.match({ build_version: buildVersion })); }); it("should return success for pkg file", async () => { // Arrange const releaseFilePath = createFile(tmpFolderPath, pkgFileName, releaseFileContent); // Act const command = prepareTestCommand([ "-f", releaseFilePath, "-g", fakeDistributionGroupName, "-b", buildVersion, "-n", buildNumber, ]); const result = await command.execute(); // Assert testCommandSuccess(result, expectedRequestsScope); Sinon.assert.calledWith(postSymbolSpy, Sinon.match({ build_version: buildVersion, build_number: buildNumber })); }); it("should return success for dmg file", async () => { // Arrange const releaseFilePath = createFile(tmpFolderPath, dmgFileName, releaseFileContent); // Act const command = prepareTestCommand([ "-f", releaseFilePath, "-g", fakeDistributionGroupName, "-b", buildVersion, "-n", buildNumber, ]); const result = await command.execute(); // Assert testCommandSuccess(result, expectedRequestsScope); Sinon.assert.calledWith(postSymbolSpy, Sinon.match({ build_version: buildVersion, build_number: buildNumber })); }); }); describe("when validates input arguments", () => { beforeEach(() => { skippedRequestsScope = Nock(fakeHost); }); it("raises error when zip file uploading and no --build-version specified", async () => { // Arrange const expectedErrorMessage = "--build-version parameter must be specified when uploading .zip files"; // Act const command = prepareTestCommand(["-f", zipFileName, "-g", fakeDistributionGroupName]); const result = (await expect(command.execute()).to.eventually.be.rejected) as CommandFailedResult; // Assert testFailure(result, expectedErrorMessage, skippedRequestsScope); }); it("raises error when msi file uploading and no --build-version specified", async () => { // Arrange const expectedErrorMessage = "--build-version parameter must be specified when uploading .msi files"; // Act const command = prepareTestCommand(["-f", msiFileName, "-g", fakeDistributionGroupName]); const result = (await expect(command.execute()).to.eventually.be.rejected) as CommandFailedResult; // Assert testFailure(result, expectedErrorMessage, skippedRequestsScope); }); it("raises error when pkg file uploading and no --build-version specified", async () => { // Arrange const expectedErrorMessage = "--build-version and --build-number must both be specified when uploading .pkg files"; // Act const command = prepareTestCommand(["-f", pkgFileName, "-g", fakeDistributionGroupName]); const result = (await expect(command.execute()).to.eventually.be.rejected) as CommandFailedResult; // Assert testFailure(result, expectedErrorMessage, skippedRequestsScope); }); it("raises error when pkg file uploading and no --build-number specified", async () => { // Arrange const expectedErrorMessage = "--build-version and --build-number must both be specified when uploading .pkg files"; // Act const command = prepareTestCommand(["-f", pkgFileName, "-g", fakeDistributionGroupName, "-b", buildVersion]); const result = (await expect(command.execute()).to.eventually.be.rejected) as CommandFailedResult; // Assert testFailure(result, expectedErrorMessage, skippedRequestsScope); }); it("passes with aab for stores", async () => { const command = prepareTestCommand(["-f", "valid.aab", "-r", "release notes", "--store", fakeStoreName]); await expect(command.execute()).to.eventually.be.rejected; }); it("passes with apk for stores", async () => { const command = prepareTestCommand(["-f", "valid.apk", "-r", "release notes", "--store", fakeStoreName]); await expect(command.execute()).to.eventually.be.rejected; }); it("passes with ipa for stores", async () => { const command = prepareTestCommand(["-f", "valid.ipa", "-r", "release notes", "--store", fakeStoreName]); await expect(command.execute()).to.eventually.be.rejected; }); }); }); context("silent", () => { beforeEach(() => { expectedRequestsScope = setupSuccessfulUploadChunkResponse( setupSuccessfulUploadFinishedResponse( setupSuccessfulPatchUploadFinishedResponse( setupSuccessfulGetUploadResponse( setupSuccessfulGetDistributionGroupUsersResponse( fakeDistributionGroupName, setupSuccessfulPostUploadResponse( setupSuccessfulSetUploadMetadataResponse( setupSuccessfulCreateReleaseResponse( setupSuccessfulAddGroupResponse( setupSuccsessFulGetDistributionGroupResponse(fakeDistributionGroupName, Nock(fakeHost)) ) ) ) ) ) ) ) ) ); }); describe("when notifying testers by default", () => { it("should successfully distribute the release", async () => { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); // Act const command = prepareTestCommand(["-f", releaseFilePath, "-r", releaseNotes, "-g", fakeDistributionGroupName]); const result = await command.execute(); // Assert testCommandSuccess(result, expectedRequestsScope); }); }); describe("when notifying testers", () => { it("should successfully distribute the release", async () => { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); // Act const command = prepareTestCommand([ "-f", releaseFilePath, "-r", releaseNotes, "-g", fakeDistributionGroupName, "--no-silent", ]); const result = await command.execute(); // Assert testCommandSuccess(result, expectedRequestsScope); }); }); describe("when not notifying testers", () => { beforeEach(() => { expectedRequestsScope = setupSuccessfulAddGroupResponse(Nock(fakeHost), true); }); it("should successfully distribute the release", async () => { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); // Act const command = prepareTestCommand(["-f", releaseFilePath, "-r", releaseNotes, "-g", fakeDistributionGroupName, "--silent"]); const result = await command.execute(); // Assert testCommandSuccess(result, expectedRequestsScope); }); }); }); context("mandatory", () => { beforeEach(() => { expectedRequestsScope = setupSuccessfulUploadChunkResponse( setupSuccessfulUploadFinishedResponse( setupSuccessfulPatchUploadFinishedResponse( setupSuccessfulGetUploadResponse( setupSuccessfulGetDistributionGroupUsersResponse( fakeDistributionGroupName, setupSuccessfulPostUploadResponse( setupSuccessfulSetUploadMetadataResponse( setupSuccessfulCreateReleaseResponse( setupSuccessfulAddGroupResponse( setupSuccsessFulGetDistributionGroupResponse(fakeDistributionGroupName, Nock(fakeHost)), false, true ) ) ) ) ) ) ) ) ); }); describe("when distributing with mandatory flag set to true", () => { it("should successfully distribute the release", async () => { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); // Act const command = prepareTestCommand([ "-f", releaseFilePath, "-r", releaseNotes, "-g", fakeDistributionGroupName, "--mandatory", ]); const result = await command.execute(); // Assert testCommandSuccess(result, expectedRequestsScope); }); }); }); context("get release failed", () => { beforeEach(() => { expectedRequestsScope = setupSuccessfulUploadChunkResponse( setupSuccessfulUploadFinishedResponse( setupSuccessfulPatchUploadFinishedResponse( setupSuccessfulGetDistributionGroupUsersResponse( fakeDistributionGroupName, setupSuccessfulPostUploadResponse( setupSuccessfulSetUploadMetadataResponse(setupFailPatchUploadFinishedResponse(Nock(fakeHost))) ) ) ) ) ); skippedRequestsScope = setupSuccessfulGetUploadResponse( setupSuccessfulCreateReleaseResponse(setupSuccessfulAddGroupResponse(Nock(fakeHost))) ); }); it("should fail during get release when HTTP status isn't 2xx", async () => { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); // Act const command = prepareTestCommand(["-f", releaseFilePath, "-r", releaseNotes, "-g", fakeDistributionGroupName, "--mandatory"]); const result = (await expect(command.execute()).to.eventually.be.rejected) as CommandFailedResult; // Assert testFailure(result, "failed to get release id with HTTP status:", expectedRequestsScope, skippedRequestsScope); }); }); describe("when release upload fails", () => { beforeEach(() => { expectedRequestsScope = setupSuccessfulGetDistributionGroupUsersResponse( fakeDistributionGroupName, setupFailedUploadChunkResponse(setupSuccessfulSetUploadMetadataResponse(Nock(fakeHost))) ); skippedRequestsScope = setupSuccessfulCreateReleaseResponse( setupSuccessfulPatchUploadFinishedResponse( setupSuccessfulUploadFinishedResponse( setupSuccessfulPostUploadResponse(setupSuccessfulAddGroupResponse(setupSuccessfulPatchUploadResponse(Nock(fakeHost)))) ) ) ); }); it("should fail and does not try to set release notes for the release", async () => { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); const releaseNotesFilePath = createFile(tmpFolderPath, releaseNotesFileName, releaseNotes); // Act const command = prepareTestCommand(["-f", releaseFilePath, "-R", releaseNotesFilePath, "-g", fakeDistributionGroupName]); const result = (await expect(command.execute()).to.eventually.be.rejected) as CommandFailedResult; // Assert testFailure( result, "Uploading file error: Upload Failed. Encountered too many errors while uploading. Please try again.", expectedRequestsScope, skippedRequestsScope ); }); }); describe("when creating the release fails", () => { beforeEach(() => { expectedRequestsScope = setupSuccessfulGetDistributionGroupUsersResponse( fakeDistributionGroupName, setupFailedSetUploadMetadataResponse(Nock(fakeHost)) ); skippedRequestsScope = setupSuccessfulGetDistributionGroupUsersResponse( fakeDistributionGroupName, setupSuccessfulCreateReleaseResponse( setupSuccessfulUploadChunkResponse( setupSuccessfulUploadFinishedResponse( setupSuccessfulPostUploadResponse(setupSuccessfulAddGroupResponse(setupSuccessfulPatchUploadResponse(Nock(fakeHost)))) ) ) ) ); }); it("does not try to set the release notes for the release", async () => { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); const releaseNotesFilePath = createFile(tmpFolderPath, releaseNotesFileName, releaseNotes); // Act const command = prepareTestCommand(["-f", releaseFilePath, "-R", releaseNotesFilePath, "-g", fakeDistributionGroupName]); const result = (await expect(command.execute()).to.eventually.be.rejected) as CommandFailedResult; // Assert testFailure( result, `Uploading file error: The asset cannot be uploaded. Failed to set metadata.`, expectedRequestsScope, skippedRequestsScope ); }); }); describe("when getting the distribution group fails", () => { beforeEach(() => { expectedRequestsScope = setupSuccessfulSetUploadMetadataResponse( setupSuccessfulUploadChunkResponse( setupSuccessfulGetUploadResponse( setupSuccessfulUploadFinishedResponse( setupSuccessfulPatchUploadFinishedResponse( setupSuccessfulPostUploadResponse(setupFailedGetDistributionGroupResponse(fakeDistributionGroupName, Nock(fakeHost))) ) ) ) ) ); skippedRequestsScope = setupSuccessfulGetDistributionGroupUsersResponse( fakeDistributionGroupName, setupSuccessfulCreateReleaseResponse(setupSuccessfulAddGroupResponse(setupSuccessfulPatchUploadResponse(Nock(fakeHost)))) ); }); it("does not try to add the group to the release", async () => { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); const releaseNotesFilePath = createFile(tmpFolderPath, releaseNotesFileName, releaseNotes); // Act const command = prepareTestCommand(["-f", releaseFilePath, "-R", releaseNotesFilePath, "-g", fakeDistributionGroupName]); const result = (await expect(command.execute()).to.eventually.be.rejected) as CommandFailedResult; // Assert testFailure(result, `Could not find group ${fakeDistributionGroupName}`, expectedRequestsScope, skippedRequestsScope); }); }); describe("when adding the group to the distribution group fails", () => { beforeEach(() => { expectedRequestsScope = setupSuccessfulGetDistributionGroupUsersResponse( fakeDistributionGroupName, setupSuccessfulPostUploadResponse( setupSuccessfulGetUploadResponse( setupSuccessfulUploadChunkResponse( setupSuccessfulCreateReleaseResponse( setupSuccessfulSetUploadMetadataResponse( setupSuccessfulUploadFinishedResponse( setupSuccessfulPatchUploadFinishedResponse( setupSuccsessFulGetDistributionGroupResponse( fakeDistributionGroupName, setupFailedAddGroupResponse(Nock(fakeHost)) ) ) ) ) ) ) ) ) ); }); it("responds with a failed result", async () => { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); const releaseNotesFilePath = createFile(tmpFolderPath, releaseNotesFileName, releaseNotes); // Act const command = prepareTestCommand(["-f", releaseFilePath, "-R", releaseNotesFilePath, "-g", fakeDistributionGroupName]); const result = (await expect(command.execute()).to.eventually.be.rejected) as CommandFailedResult; // Assert testFailure(result, `Could not find release ${fakeReleaseId}`, expectedRequestsScope); }); }); describe("when using invalid arguments", () => { let releaseFilePath: string; let releaseNotesFilePath: string; before(() => { releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); releaseNotesFilePath = createFile(tmpFolderPath, releaseNotesFileName, releaseNotes); }); it("fails if --file is not specified", async () => { expect(() => prepareTestCommand(["-R", releaseNotesFilePath, "-g", fakeDistributionGroupName])).to.throw; }); it("fails if neither --release-notes nor --release-notes-file is specified", async () => { const command = prepareTestCommand(["-f", releaseFilePath, "-g", fakeDistributionGroupName]); await expect(command.execute()).to.eventually.be.rejected; }); it("fails if both --release-notes and --release-notes-file are specified", async () => { const command = prepareTestCommand([ "-f", releaseFilePath, "-r", releaseNotes, "-R", releaseNotesFilePath, "-g", fakeDistributionGroupName, ]); await expect(command.execute()).to.eventually.be.rejected; }); it("fails if neither --group nor --store is specified", async () => { const command = prepareTestCommand(["-f", releaseFilePath, "-R", releaseNotesFilePath]); await expect(command.execute()).to.eventually.be.rejected; }); it("fails if distributing invalid file type to store", async () => { const command = prepareTestCommand(["-f", "invalid.ext", "-R", releaseNotesFilePath, "--store", fakeStoreName]); await expect(command.execute()).to.eventually.be.rejected; }); it("fails if distributing invalid file type to group", async () => { const command = prepareTestCommand(["-f", "invalid.aab", "-R", releaseNotesFilePath, "--group", fakeStoreName]); await expect(command.execute()).to.eventually.be.rejected; }); describe("when publishing to an 'apple' type store", () => { beforeEach(() => { expectedRequestsScope = setupSuccessfulGetStoreDetailsResponse(Nock(fakeHost), "apple"); }); it("fails if neither --release-notes nor --release-notes-file is specified", async () => { // Arrange const expectedErrorMessage = "At least one of '--release-notes' or '--release-notes-file' must be specified when publishing to an Apple store."; // Act const command = prepareTestCommand(["-f", releaseFilePath, "-s", fakeStoreName]); const result = (await expect(command.execute()).to.eventually.be.rejected) as CommandFailedResult; // Assert testFailure(result, expectedErrorMessage, expectedRequestsScope); }); }); }); afterEach(() => { Nock.cleanAll(); }); after(() => { Nock.enableNetConnect(); }); function prepareTestCommand(args: string[]): ReleaseBinaryCommand { const command = new ReleaseBinaryCommand(getCommandArgs(args)); return command; } function createFile(folderPath: string, fileName: string, fileContent: string): string { const finalPath = Path.join(folderPath, fileName); Fs.writeFileSync(finalPath, fileContent); return finalPath; } function testCommandSuccess(result: CommandResult, executionScope: Nock.Scope) { expect(result.succeeded).to.eql(true, "Command should be successfully completed"); executionScope.done(); // All normal API calls are executed } function testFailure(result: CommandFailedResult, errorMessage: string, executionScope: Nock.Scope, skippedScope?: Nock.Scope) { expect(result.succeeded).to.eql(false, "Command should fail"); expect(result.errorMessage).to.contain(errorMessage); if (skippedScope) { expect(skippedScope.isDone()).to.eql(false, "Skipped scope should not be completed"); } executionScope.done(); // All normal API calls are executed } function getCommandArgs(additionalArgs: string[]): CommandArgs { const args: string[] = ["-a", fakeAppIdentifier, "--token", fakeToken, "--env", "local"].concat(additionalArgs); return { args, command: ["distribute", "release"], commandPath: "FAKE", }; } function setupSuccessfulGetDistributionGroupUsersResponse(group: string, nockScope: Nock.Scope): Nock.Scope { return nockScope .get(`/v0.1/apps/${fakeAppOwner}/${fakeAppName}/distribution_groups/${group}/members`) .reply(200, (uri: any, requestBody: any) => { return [ { /* Single user, fields are not used */ }, ]; }); } function setupSuccessfulPostUploadResponse(nockScope: Nock.Scope): Nock.Scope { return nockScope.post(`/v0.1/apps/${fakeAppOwner}/${fakeAppName}/uploads/releases`).reply(200, (uri: any, requestBody: any) => { postSymbolSpy(requestBody); return { upload_url: fakeHost + fakeUploadUrl, package_asset_id: fakeGuid, url_encoded_token: fakeUrlEncodedToken, upload_domain: fakeHost, id: fakeReleaseUploadingId, }; }); } function setupSuccessfulSetUploadMetadataResponse(nockScope: Nock.Scope): Nock.Scope { return nockScope .post(`/upload/set_metadata/${fakeGuid}`) .query(true) .reply(200, (uri: any, requestBody: any) => { postSymbolSpy(requestBody); return { resume_restart: false, chunk_list: [1], chunk_size: releaseFileContent.length, blob_partitions: 1, }; }); } function setupFailedSetUploadMetadataResponse(nockScope: Nock.Scope): Nock.Scope { return nockScope .post(`/upload/set_metadata/${fakeGuid}`) .query(true) .reply(500, (uri: any, requestBody: any) => { postSymbolSpy(requestBody); }); } function setupSuccessfulUploadChunkResponse(nockScope: Nock.Scope): Nock.Scope { return nockScope .post(`/upload/upload_chunk/${fakeGuid}`) .query(true) .reply(200, (uri: any, requestBody: any) => { postSymbolSpy(requestBody); return {}; }); } function setupFailedUploadChunkResponse(nockScope: Nock.Scope): Nock.Scope { return nockScope .post(`/upload/upload_chunk/${fakeGuid}`) .query(true) .times(21) .reply(500, (uri: any, requestBody: any) => { postSymbolSpy(requestBody); }); } function setupSuccessfulUploadFinishedResponse(nockScope: Nock.Scope): Nock.Scope { return nockScope .post(`/upload/finished/${fakeGuid}`) .query(true) .reply(200, (uri: any, requestBody: any) => { postSymbolSpy(requestBody); return { error: false, state: "Done", }; }); } function setupSuccessfulGetUploadResponse(nockScope: Nock.Scope): Nock.Scope { return nockScope .get(`/v0.1/apps/${fakeAppOwner}/${fakeAppName}/uploads/releases/${fakeReleaseUploadingId}`) .reply(200, (uri: any, requestBody: any) => { patchSymbolSpy(requestBody); return { release_distinct_id: fakeReleaseId, upload_status: "readyToBePublished", }; }); } function setupSuccessfulPatchUploadResponse(nockScope: Nock.Scope): Nock.Scope { return nockScope .patch(`/v0.1/apps/${fakeAppOwner}/${fakeAppName}/uploads/releases/${fakeReleaseUploadingId}`, { upload_status: "committed", }) .reply(200, (uri: any, requestBody: any) => { patchSymbolSpy(requestBody); return { upload_status: "committed", release_url: fakeReleaseUrl, }; }); } function setupSuccessfulPatchUploadFinishedResponse(nockScope: Nock.Scope): Nock.Scope { return nockScope .patch(`/v0.1/apps/${fakeAppOwner}/${fakeAppName}/uploads/releases/${fakeReleaseUploadingId}`, { upload_status: "uploadFinished", }) .reply(200, (uri: any, requestBody: any) => { patchSymbolSpy(requestBody); uploadSpy(requestBody); return { upload_status: "uploadFinished", release_url: fakeReleaseUrl, }; }); } function setupFailPatchUploadFinishedResponse(nockScope: Nock.Scope): Nock.Scope { return nockScope .get(`/v0.1/apps/${fakeAppOwner}/${fakeAppName}/uploads/releases/${fakeReleaseUploadingId}`) .reply(500, (uri: any, requestBody: any) => { patchSymbolSpy(requestBody); return { upload_status: "error", release_url: fakeReleaseUrl, }; }); } function setupSuccessfulCreateReleaseResponse(nockScope: Nock.Scope, optionalReleaseNotes = true): Nock.Scope { return nockScope .put( `/v0.1/apps/${fakeAppOwner}/${fakeAppName}/releases/${fakeReleaseId}`, optionalReleaseNotes ? { release_notes: releaseNotes } : undefined ) .reply(200, (uri: any, requestBody: any) => { distributeSpy(requestBody); return { version, short_version: shortVersion, }; }); } function setupSuccessfulAddGroupResponse(nockScope: Nock.Scope, silent = false, mandatory = false): Nock.Scope { const postAddReleaseGroupDestinationUrl = `/v0.1/apps/${fakeAppOwner}/${fakeAppName}/releases/${fakeReleaseId}/groups`; const expectedBody = { id: fakeGuid, mandatory_update: mandatory, notify_testers: !silent, }; return nockScope.post(postAddReleaseGroupDestinationUrl, expectedBody).reply(201, { id: fakeGuid, mandatory_update: mandatory, notify_testers: !silent, }); } function setupSuccessfulGetStoreDetailsResponse(nockScope: Nock.Scope, storeType: string = fakeStoreType): Nock.Scope { const getDistributionStoresUrl = `/v0.1/apps/${fakeAppOwner}/${fakeAppName}/distribution_stores/${fakeStoreName}`; return nockScope.get(getDistributionStoresUrl).reply(200, { id: fakeGuid, name: fakeStoreName, type: storeType, track: fakeStoreTrack, }); } function setupSuccessfulAddStoreResponse(nockScope: Nock.Scope): Nock.Scope { const postAddReleaseStoreDestinationUrl = `/v0.1/apps/${fakeAppOwner}/${fakeAppName}/releases/${fakeReleaseId}/stores`; const expectedBody = { id: fakeGuid, }; return nockScope.post(postAddReleaseStoreDestinationUrl, expectedBody).reply(201, { id: fakeGuid, }); } function setupFailedAddGroupResponse(nockScope: Nock.Scope, silent = false, mandatory = false): Nock.Scope { const postAddReleaseGroupDestinationUrl = `/v0.1/apps/${fakeAppOwner}/${fakeAppName}/releases/${fakeReleaseId}/groups`; const expectedBody = { id: fakeGuid, mandatory_update: mandatory, notify_testers: !silent, }; return nockScope.post(postAddReleaseGroupDestinationUrl, expectedBody).reply(404); } function setupSuccsessFulGetDistributionGroupResponse(group: string, nockScope: Nock.Scope): Nock.Scope { const getDistributionGroupUrl = `/v0.1/apps/${fakeAppOwner}/${fakeAppName}/distribution_groups/${group}`; return nockScope.get(getDistributionGroupUrl).reply(200, { id: fakeGuid, name: group, dismay_name: "my group", origin: "appcenter", is_public: false, }); } function setupFailedGetDistributionGroupResponse(group: string, nockScope: Nock.Scope): Nock.Scope { const getDistributionGroupUrl = `/v0.1/apps/${fakeAppOwner}/${fakeAppName}/distribution_groups/${group}`; return nockScope.get(getDistributionGroupUrl).reply(404); } });
the_stack
import { Cache } from '../src'; import { ICache } from '../src/CacheTypes'; import { createStorage } from '../src/createStorage'; import { prefixLayer } from '../src/layers/prefixLayer'; jest.mock('../src/createStorage', () => require.requireActual('../__mocks__/createStorage')); const INITIAL_STATE = { restore: true, data: 1 }; function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } function createStorageCalled(type): any { return { multiRemove: jest.fn(() => Promise.resolve()), multiGet: jest.fn(() => Promise.resolve([])), multiSet: jest.fn(() => Promise.resolve()), getAllKeys: jest.fn(() => Promise.resolve([])), setItem: jest.fn(() => Promise.resolve()), removeItem: jest.fn(() => Promise.resolve()), getItem: jest.fn(() => Promise.resolve()), }; } /* describe('Test speed', () => { const arr1 = Array.from(Array(100000), (x, i) => i + 1); const arr2 = Array.from(Array(100000), (x, i) => i - 1); const set1 = new Set(arr1.splice(0)); it('naive 2', () => { const start = Date.now(); const a = arr1; const arr1Length = arr1.length; const arr2Length = arr2.length; a.length = arr1Length + arr2Length; for (var i = 0; i < arr2Length; i++) { a[arr1Length + i] = arr2[i]; } Array.from(new Set(a.splice(0))); console.log('time Set for', Date.now() - start); }); it('push for', () => { const start = Date.now(); const a = arr1; for (var l = 0; l < arr2.length; l++) { a.push(arr2[l]); } Array.from(new Set(a.splice(0))); console.log('time push for', Date.now() - start); }); it('push ...', () => { const start = Date.now(); const a = arr1; a.push(...arr2); Array.from(new Set(a.splice(0))); console.log('time push ...', Date.now() - start); }); it('concat', () => { const start = Date.now(); const a = arr1.concat(arr2); Array.from(new Set(a.splice(0))); console.log('time concat', Date.now() - start); }); it('Set for', () => { const start = Date.now(); const a = set1; for (var l = 0; l < arr2.length; l++) { a.add(arr2[l]); } Array.from(a.values()); a.clear(); console.log('time Set for', Date.now() - start); }); }); */ describe('Cache ', () => { let cache: ICache; const start = Date.now(); beforeAll(() => { cache = new Cache(); }); it('cache restored', async () => { expect(cache.isRehydrated()).not.toBeTruthy(); await cache.restore(); expect(cache.isRehydrated()).toBeTruthy(); }); it('cache set', async () => { cache.set('prova', 1); expect(cache.get('prova')).toBe(1); }); it('cache remove', async () => { cache.remove('prova'); expect(cache.get('prova')).toBeUndefined(); }); it('cache purge', async () => { expect(cache.getState()).toEqual(INITIAL_STATE); cache.purge(); expect(cache.getState()).toEqual({}); }); it('cache remove', () => { cache.set('prova', 2); }); it('cache flush', () => { cache.flush().then(() => { expect(cache.get('prova')).toBe(2); console.log('cache flush', Date.now() - start); }); }); }); describe('Cache ssr initial data ', () => { let cache: ICache; const start = Date.now(); const ssrState = { test1: 1, test2: 2, test3: 3, }; beforeAll(() => { cache = new Cache({ initialState: ssrState, mergeState: (restoredState, initialState) => initialState, }); }); it('cache restored', async () => { expect(cache.isRehydrated()).not.toBeTruthy(); cache.set('test4', 4); await cache.restore(); expect(cache.isRehydrated()).toBeTruthy(); expect(cache.getState()).toEqual({ ...ssrState, test4: 4 }); }); it('cache set', async () => { cache.set('prova', 1); expect(cache.get('prova')).toBe(1); }); it('cache remove', async () => { cache.remove('prova'); expect(cache.get('prova')).toBeUndefined(); }); it('cache purge', async () => { expect(cache.getState()).toEqual(ssrState); cache.purge(); expect(cache.getState()).toEqual({}); }); it('cache remove', () => { cache.set('prova', 2); }); it('cache flush', () => { cache.flush().then(() => { expect(cache.get('prova')).toBe(2); console.log('cache flush', Date.now() - start); }); }); }); describe('Cache ssr async initial data ', () => { let cache: ICache; const start = Date.now(); const ssrState = { test1: 1, test2: 2, test3: 3, }; beforeAll(() => { cache = new Cache({ initialState: ssrState, mergeState: async (restoredState, initialState) => initialState, }); }); it('cache restored', async () => { expect(cache.isRehydrated()).not.toBeTruthy(); cache.set('test4', 4); await cache.restore(); expect(cache.isRehydrated()).toBeTruthy(); expect(cache.getState()).toEqual({ ...ssrState, test4: 4 }); }); it('cache set', async () => { cache.set('prova', 1); expect(cache.get('prova')).toBe(1); }); it('cache remove', async () => { cache.remove('prova'); expect(cache.get('prova')).toBeUndefined(); }); it('cache purge', async () => { expect(cache.getState()).toEqual(ssrState); cache.purge(); expect(cache.getState()).toEqual({}); }); it('cache remove', () => { cache.set('prova', 2); }); it('cache flush', () => { cache.flush().then(() => { expect(cache.get('prova')).toBe(2); console.log('cache flush', Date.now() - start); }); }); }); describe('Cache layers', () => { let cache: ICache; const storage: any = createStorage(null); beforeAll(() => { cache = new Cache({ storage, mutateKeys: [prefixLayer('test')] }); }); it('cache restored', async () => { expect(cache.isRehydrated()).not.toBeTruthy(); await cache.restore(); expect(cache.isRehydrated()).toBeTruthy(); }); it('cache set', async () => { cache.set('prova', 1); expect(cache.get('prova')).toBe(1); await cache.flush(); }); it('cache restored', async () => { cache = new Cache({ storage, mutateKeys: [prefixLayer('test')] }); expect(cache.isRehydrated()).not.toBeTruthy(); await cache.restore(); console.log('storage', storage.getState()); expect(cache.isRehydrated()).toBeTruthy(); expect(cache.getState()).toEqual({ prova: 1 }); }); it('cache remove', async () => { cache.remove('prova'); expect(cache.get('prova')).toBeUndefined(); await cache.flush(); }); it('cache restored', async () => { cache = new Cache({ storage, mutateKeys: [prefixLayer('test')] }); expect(cache.isRehydrated()).not.toBeTruthy(); await cache.restore(); expect(cache.isRehydrated()).toBeTruthy(); expect(cache.getState()).toEqual({}); }); }); describe('Cache disable persist', () => { let cache; beforeAll(() => { cache = new Cache({ disablePersist: true }); }); it('cache isRehydrated without restore', () => { expect(cache.isRehydrated()).toBeTruthy(); }); it('cache restored', async () => { await cache.restore(); expect(cache.isRehydrated()).toBeTruthy(); }); it('cache set', () => { cache.set('prova', 1); expect(cache.get('prova')).toBe(1); cache.set('restore', true); expect(cache.get('restore')).toBeTruthy(); }); it('cache remove', () => { cache.remove('prova'); expect(cache.get('prova')).toBeUndefined(); }); it('cache purge', () => { expect(cache.getState()).toEqual({ restore: true }); cache.purge(true); expect(cache.getState()).toEqual({}); }); it('cache replace', () => { expect(cache.getState()).toEqual({}); cache.replace(INITIAL_STATE, true); expect(cache.getState()).toEqual(INITIAL_STATE); }); it('cache flush', async () => { await cache.flush(); expect(cache.getState()).toEqual(INITIAL_STATE); }); }); describe('storage', () => { let cache; let storage; beforeAll(() => { storage = createStorage(undefined); cache = new Cache({ storage }); }); it('cache restored', async () => { expect(cache.isRehydrated()).not.toBeTruthy(); await cache.restore(); expect(cache.isRehydrated()).toBeTruthy(); expect(cache.getState()).toEqual(INITIAL_STATE); }); it('storage', async () => { cache.set('prova', 1); expect(cache.get('prova')).toBe(1); await cache.flush(); await storage.getAllKeys().then((keys) => expect(keys.length).toBe(3)); await storage.getItem('cache.prova').then((value) => expect(value).toBe('1')); }); }); describe('Cache, others', () => { it('cache debounce', async () => { const storage = createStorageCalled(undefined); const cache = new Cache({ storage }); await cache.restore(); Array.from(Array(10000).keys()).forEach((index) => { cache.set(`prova${index}`, index); }); Array.from(Array(3500).keys()).forEach((index) => { cache.remove(`prova${index}`); }); await sleep(600); //jest.runOnlyPendingTimers(); expect(storage.multiRemove).toHaveBeenCalledTimes(1); expect(storage.multiSet).toHaveBeenCalledTimes(1); Array.from(Array(20).keys()).forEach((index) => { cache.set(`prova${index}`, index); }); Array.from(Array(20).keys()).forEach((index) => { cache.remove(`prova${index}`); }); await sleep(600); expect(storage.multiRemove).toHaveBeenCalledTimes(2); Array.from(Array(20).keys()).forEach((index) => { cache.set(`prova${index}`, index); }); Array.from(Array(20).keys()).forEach((index) => { cache.delete(`prova${index}`); }); await sleep(600); expect(storage.multiSet).toHaveBeenCalledTimes(2); Array.from(Array(20).keys()).forEach((index) => { cache.set(`prova${index}`, index); }); Array.from(Array(20).keys()).forEach((index) => { cache.remove(`prova${index}`); }); Array.from(Array(20).keys()).forEach((index) => { cache.set(`prova${index}`, index); }); await sleep(600); expect(storage.multiSet).toHaveBeenCalledTimes(3); expect(storage.setItem).toHaveBeenCalledTimes(0); expect(storage.removeItem).toHaveBeenCalledTimes(0); //jest.runTimersToTime(2000); }); it('cache debounce with await', async () => { const storage = createStorageCalled(undefined); const cache = new Cache({ storage }); await cache.restore(); console.log('cache debounce with await start'); const startTime = Date.now(); Array.from(Array(10000).keys()).forEach((index) => { cache.set(`prova${index}`, index); }); console.log('cache debounce 1', Date.now() - startTime); Array.from(Array(3500).keys()).forEach((index) => { cache.remove(`prova${index}`); }); console.log('cache debounce 2', Date.now() - startTime); Array.from(Array(20).keys()).forEach((index) => { cache.set(`prova${index}`, index); }); Array.from(Array(20).keys()).forEach((index) => { cache.remove(`prova${index}`); }); Array.from(Array(20).keys()).forEach((index) => { cache.set(`prova${index}`, index); }); Array.from(Array(20).keys()).forEach((index) => { cache.delete(`prova${index}`); }); Array.from(Array(20).keys()).forEach((index) => { cache.set(`prova${index}`, index); }); Array.from(Array(20).keys()).forEach((index) => { cache.remove(`prova${index}`); }); Array.from(Array(20).keys()).forEach((index) => { cache.set(`prova${index}`, index); }); cache.set('end', 2); console.log('cache debounce 3', Date.now() - startTime); await cache.flush(); console.log('cache debounce end', Date.now() - startTime); expect(storage.multiSet).toHaveBeenCalledTimes(1); expect(storage.multiRemove).toHaveBeenCalledTimes(1); expect(storage.setItem).toHaveBeenCalledTimes(0); expect(storage.removeItem).toHaveBeenCalledTimes(0); //jest.runTimersToTime(2000); }); it('cache callback', async () => { const cache = new Cache(); await cache.restore(); const callback = jest.fn(); const dispose = cache.subscribe(callback); cache.notify(); expect(callback).toHaveBeenCalledTimes(1); cache.notify(); expect(callback).toHaveBeenCalledTimes(2); dispose(); cache.notify(); expect(callback).toHaveBeenCalledTimes(2); }); it('cache flush', async () => { console.log('cache flush start'); const startTime = Date.now(); const cache = new Cache(); await cache.restore(); console.log('cache flush 1', Date.now() - startTime); Array.from(Array(10000).keys()).forEach((index) => { cache.set(`prova${index}`, index); }); cache.flush().then(() => console.log('cache flush 2', Date.now() - startTime)); cache.set('prova', 2); await cache.flush(); console.log('cache flush 3', Date.now() - startTime); expect(cache.get('prova')).toBe(2); }); });
the_stack
import { MockBoot, renderRelayTree } from "v2/DevTools" import { SystemContextProvider } from "v2/System" import { ViewingRoomAppFragmentContainer } from "../ViewingRoomApp" import { graphql } from "react-relay" import { ViewingRoomApp_DraftTest_QueryRawResponse } from "v2/__generated__/ViewingRoomApp_DraftTest_Query.graphql" import { ViewingRoomApp_ScheduledTest_QueryRawResponse } from "v2/__generated__/ViewingRoomApp_ScheduledTest_Query.graphql" import { ViewingRoomApp_OpenTest_QueryRawResponse } from "v2/__generated__/ViewingRoomApp_OpenTest_Query.graphql" import { ViewingRoomApp_ClosedTest_QueryRawResponse } from "v2/__generated__/ViewingRoomApp_ClosedTest_Query.graphql" import { ViewingRoomApp_LoggedOutTest_QueryRawResponse } from "v2/__generated__/ViewingRoomApp_LoggedOutTest_Query.graphql" import { Breakpoint } from "@artsy/palette" import { mockLocation } from "v2/DevTools/mockLocation" jest.useFakeTimers() jest.unmock("react-relay") jest.mock("v2/System/Router/useRouter", () => ({ useIsRouteActive: () => false, useRouter: () => ({ match: { params: { slug: "subscription-demo-gg-guy-yanai", }, }, }), })) describe("ViewingRoomApp", () => { let user const slug = "subscription-demo-gg-guy-yanai" beforeEach(() => { mockLocation() user = { id: "blah" } window.history.pushState({}, "Viewing Room Title", slug) }) // DRAFT viewing room describe("for draft viewing room when viewed by user that has access to viewing rooms partner", () => { // encoded through https://jwt.io with data of "partner_ids": ["00001", "12345"] beforeEach(() => { user.accessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwicGFydG5lcl9pZHMiOlsiMDAwMDEiLCIxMjM0NSJdfQ.3mH8dg__KaPBEA5jSU8mHMEExttDIP2-nk3NJ2yb0ok" }) const getWrapper = async ( breakpoint: Breakpoint = "lg", response: ViewingRoomApp_DraftTest_QueryRawResponse = DraftViewingRoomAppFixture ) => { return renderRelayTree({ Component: ({ viewingRoom }) => { return ( <MockBoot breakpoint={breakpoint}> <SystemContextProvider user={user}> <ViewingRoomAppFragmentContainer viewingRoom={viewingRoom}> some child </ViewingRoomAppFragmentContainer> </SystemContextProvider> </MockBoot> ) }, mockData: response, query: graphql` query ViewingRoomApp_DraftTest_Query($slug: ID!) @raw_response_type { viewingRoom(id: $slug) { ...ViewingRoomApp_viewingRoom } } `, variables: { slug, }, }) } it("renders the correct components", async () => { const wrapper = await getWrapper() expect(wrapper.find("ViewingRoomMeta").length).toBe(1) expect(wrapper.find("ViewingRoomHeader").length).toBe(1) expect(wrapper.find("ViewingRoomTabBar").length).toBe(1) expect(wrapper.find("ViewingRoomContentNotAccessible").length).toBe(0) const html = wrapper.html() expect(html).toContain("This is a preview of your viewing room.") }) }) // SCHEDULED viewing room describe("with scheduled viewing room", () => { const getWrapper = async ( breakpoint: Breakpoint = "lg", response: ViewingRoomApp_ScheduledTest_QueryRawResponse = ScheduledViewingRoomAppFixture ) => { return renderRelayTree({ Component: ({ viewingRoom }) => { return ( <MockBoot breakpoint={breakpoint}> <SystemContextProvider user={user}> <ViewingRoomAppFragmentContainer viewingRoom={viewingRoom}> some child </ViewingRoomAppFragmentContainer> </SystemContextProvider> </MockBoot> ) }, mockData: response, query: graphql` query ViewingRoomApp_ScheduledTest_Query($slug: ID!) @raw_response_type { viewingRoom(id: $slug) { ...ViewingRoomApp_viewingRoom } } `, variables: { slug, }, }) } it("renders the correct components", async () => { const wrapper = await getWrapper() expect(wrapper.find("ViewingRoomMeta").length).toBe(1) expect(wrapper.find("ViewingRoomHeader").length).toBe(1) expect(wrapper.find("ViewingRoomTabBar").length).toBe(0) expect(wrapper.find("ViewingRoomContentNotAccessible").length).toBe(1) expect(wrapper.html()).not.toContain("some child") }) describe("ViewingRoomHeader", () => { describe("desktop", () => { it("renders correctly", async () => { const wrapper = await getWrapper() const html = wrapper.html() expect(html).toContain("<img") expect(html).toContain("Guy Yanai") expect(html).toContain("Subscription Demo GG") expect(html).toContain("Opens in 8 days") }) }) describe("mobile", () => { it("renders correctly", async () => { const wrapper = await getWrapper() const html = wrapper.html() expect(html).toContain("<img") expect(html).toContain("Guy Yanai") expect(html).toContain("Subscription Demo GG") expect(html).toContain("Opens in 8 days") }) }) }) }) // OPEN Viewing Room describe("with open viewing room", () => { const getWrapper = async ( breakpoint: Breakpoint = "lg", response: ViewingRoomApp_OpenTest_QueryRawResponse = OpenViewingRoomAppFixture ) => { return renderRelayTree({ Component: ({ viewingRoom }) => { return ( <MockBoot breakpoint={breakpoint}> <SystemContextProvider user={user}> <ViewingRoomAppFragmentContainer viewingRoom={viewingRoom}> some child </ViewingRoomAppFragmentContainer> </SystemContextProvider> </MockBoot> ) }, mockData: response, query: graphql` query ViewingRoomApp_OpenTest_Query($slug: ID!) @raw_response_type { viewingRoom(id: $slug) { ...ViewingRoomApp_viewingRoom } } `, variables: { slug, }, }) } it("renders the correct components", async () => { const wrapper = await getWrapper() expect(wrapper.find("ViewingRoomMeta").length).toBe(1) expect(wrapper.find("ViewingRoomHeader").length).toBe(1) expect(wrapper.find("ViewingRoomTabBar").length).toBe(1) expect(wrapper.find("ViewingRoomContentNotAccessible").length).toBe(0) expect(wrapper.html()).toContain("some child") }) describe("ViewingRoomHeader", () => { describe("desktop", () => { it("renders correctly", async () => { const wrapper = await getWrapper() const html = wrapper.html() expect(html).toContain("<img") expect(html).toContain("Guy Yanai") expect(html).toContain("Subscription Demo GG") expect(html).toContain("1 month left") }) }) describe("mobile", () => { it("renders correctly", async () => { const wrapper = await getWrapper() const html = wrapper.html() expect(html).toContain("<img") expect(html).toContain("Guy Yanai") expect(html).toContain("Subscription Demo GG") expect(html).toContain("1 month left") }) }) }) describe("ViewingRoomTabBar", () => { it("renders correct tabs", async () => { const wrapper = await getWrapper() expect(wrapper.find("RouteTab").length).toBe(2) const html = wrapper.html() expect(html).toContain(`href="/viewing-room/${slug}"`) expect(html).toContain(`href="/viewing-room/${slug}/artworks"`) }) }) }) // CLOSED viewing room describe("with closed viewing room", () => { const getWrapper = async ( breakpoint: Breakpoint = "lg", response: ViewingRoomApp_ClosedTest_QueryRawResponse = ClosedViewingRoomAppFixture ) => { return renderRelayTree({ Component: ({ viewingRoom }) => { return ( <MockBoot breakpoint={breakpoint}> <SystemContextProvider user={user}> <ViewingRoomAppFragmentContainer viewingRoom={viewingRoom}> some child </ViewingRoomAppFragmentContainer> </SystemContextProvider> </MockBoot> ) }, mockData: response, query: graphql` query ViewingRoomApp_ClosedTest_Query($slug: ID!) @raw_response_type { viewingRoom(id: $slug) { ...ViewingRoomApp_viewingRoom } } `, variables: { slug, }, }) } it("renders the correct components", async () => { const wrapper = await getWrapper() expect(wrapper.find("ViewingRoomMeta").length).toBe(1) expect(wrapper.find("ViewingRoomHeader").length).toBe(1) expect(wrapper.find("ViewingRoomTabBar").length).toBe(0) expect(wrapper.find("ViewingRoomContentNotAccessible").length).toBe(1) expect(wrapper.html()).not.toContain("some child") }) describe("ViewingRoomHeader", () => { describe("desktop", () => { it("renders correctly", async () => { const wrapper = await getWrapper() const html = wrapper.html() expect(html).toContain("<img") expect(html).toContain("Guy Yanai") expect(html).toContain("Subscription Demo GG") expect(html).toContain("Closed") }) }) describe("mobile", () => { it("renders correctly", async () => { const wrapper = await getWrapper() const html = wrapper.html() expect(html).toContain("<img") expect(html).toContain("Guy Yanai") expect(html).toContain("Subscription Demo GG") expect(html).toContain("Closed") }) }) }) }) describe("with logged out user", () => { const getWrapper = async ( breakpoint: Breakpoint = "lg", response: ViewingRoomApp_LoggedOutTest_QueryRawResponse = LoggedOutViewingRoomAppFixture ) => { return renderRelayTree({ Component: ({ viewingRoom }) => { return ( <MockBoot breakpoint={breakpoint} user={null}> <ViewingRoomAppFragmentContainer viewingRoom={viewingRoom}> some child </ViewingRoomAppFragmentContainer> </MockBoot> ) }, mockData: response, query: graphql` query ViewingRoomApp_LoggedOutTest_Query($slug: ID!) @raw_response_type { viewingRoom(id: $slug) { ...ViewingRoomApp_viewingRoom } } `, variables: { slug, }, }) } it("shows viewing room content", async () => { const wrapper = await getWrapper() expect(wrapper.find("ViewingRoomMeta").length).toBe(1) expect(wrapper.find("ViewingRoomHeader").length).toBe(1) expect(wrapper.find("ViewingRoomTabBar").length).toBe(1) expect(wrapper.find("ViewingRoomContentNotAccessible").length).toBe(0) expect(wrapper.html()).toContain("some child") jest.runAllTimers() }) }) }) const DraftViewingRoomAppFixture: ViewingRoomApp_DraftTest_QueryRawResponse = { viewingRoom: { href: "/viewing-room/example", pullQuote: "Example pull quote", distanceToClose: null, distanceToOpen: null, image: { imageURLs: { normalized: "https://artsy-media-uploads.s3.amazonaws.com/0RnxWDsVmKuALfpmd75YyA/CTPHSEPT19_018_JO_Guy_Yanai_TLV_031_20190913.jpg", }, }, partner: { href: "/partner-demo-gg", id: "UGFydG5lcjo1NTQxMjM3MzcyNjE2OTJiMTk4YzAzMDA=", internalID: "00001", name: "Subscription Demo GG", }, status: "draft", title: "Not published room", }, } const ScheduledViewingRoomAppFixture: ViewingRoomApp_ScheduledTest_QueryRawResponse = { viewingRoom: { href: "/viewing-room/example", pullQuote: "Example pull quote", distanceToClose: null, distanceToOpen: "8 days", image: { imageURLs: { normalized: "https://artsy-media-uploads.s3.amazonaws.com/0RnxWDsVmKuALfpmd75YyA/CTPHSEPT19_018_JO_Guy_Yanai_TLV_031_20190913.jpg", }, }, partner: { href: "/partner-demo-gg", id: "UGFydG5lcjo1NTQxMjM3MzcyNjE2OTJiMTk4YzAzMDA=", internalID: "12345", name: "Subscription Demo GG", }, status: "scheduled", title: "Guy Yanai", }, } const OpenViewingRoomAppFixture: ViewingRoomApp_OpenTest_QueryRawResponse = { viewingRoom: { href: "/viewing-room/example", pullQuote: "Example pull quote", distanceToClose: "1 month", distanceToOpen: null, image: { imageURLs: { normalized: "https://artsy-media-uploads.s3.amazonaws.com/0RnxWDsVmKuALfpmd75YyA/CTPHSEPT19_018_JO_Guy_Yanai_TLV_031_20190913.jpg", }, }, partner: { href: "/partner-demo-gg", id: "UGFydG5lcjo1NTQxMjM3MzcyNjE2OTJiMTk4YzAzMDA=", internalID: "6789", name: "Subscription Demo GG", }, status: "live", title: "Guy Yanai", }, } const ClosedViewingRoomAppFixture: ViewingRoomApp_ClosedTest_QueryRawResponse = { viewingRoom: { href: "/viewing-room/example", pullQuote: "Example pull quote", distanceToClose: null, distanceToOpen: null, image: { imageURLs: { normalized: "https://artsy-media-uploads.s3.amazonaws.com/0RnxWDsVmKuALfpmd75YyA/CTPHSEPT19_018_JO_Guy_Yanai_TLV_031_20190913.jpg", }, }, partner: { href: "/partner-demo-gg", id: "UGFydG5lcjo1NTQxMjM3MzcyNjE2OTJiMTk4YzAzMDA=", internalID: "212121", name: "Subscription Demo GG", }, status: "closed", title: "Guy Yanai", }, } const LoggedOutViewingRoomAppFixture: ViewingRoomApp_LoggedOutTest_QueryRawResponse = { viewingRoom: { href: "/viewing-room/example", pullQuote: "Example pull quote", distanceToClose: "1 month", distanceToOpen: null, image: { imageURLs: { normalized: "https://artsy-media-uploads.s3.amazonaws.com/0RnxWDsVmKuALfpmd75YyA/CTPHSEPT19_018_JO_Guy_Yanai_TLV_031_20190913.jpg", }, }, partner: { href: "/partner-demo-gg", id: "UGFydG5lcjo1NTQxMjM3MzcyNjE2OTJiMTk4YzAzMDA=", internalID: "123123123", name: "Subscription Demo GG", }, status: "live", title: "Guy Yanai", }, }
the_stack
import * as chai from 'chai'; // tslint:disable-next-line:no-var-requires const { balance, BN, constants, ether, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); import { DAOInstance, VentureEthInstance, OneTokenOneVoteInstance } from '../../types/truffle-contracts'; const DAO = artifacts.require( 'DAO', ) as Truffle.Contract<DAOInstance>; const VentureEth = artifacts.require( 'VentureEth', ) as Truffle.Contract<VentureEthInstance>; const Voting = artifacts.require( 'OneTokenOneVote', ) as Truffle.Contract<OneTokenOneVoteInstance>; // tslint:disable-next-line:no-var-requires chai.use(require('chai-bn')(require('bn.js'))); chai.should(); contract('DAO', (accounts) => { const [ holder1, holder2, holder3, holder4, ventureHolder1, ventureHolder2, ventureClient1, ventureClient2 ] = accounts; let dao: DAOInstance; let venture1: VentureEthInstance; let venture2: VentureEthInstance; let voting1: OneTokenOneVoteInstance; let voting2: OneTokenOneVoteInstance; describe('once DAO tokens issued to investors', () => { beforeEach(async () => { dao = await DAO.new('DAOToken', 'DAO', 18, 5001); venture1 = await VentureEth.new('VentureToken1', 'VNT1', 19); venture2 = await VentureEth.new('VentureToken2', 'VNT2', 17); await dao.setIssuePrice(ether('0.2')); await dao.startIssuance(); await dao.invest({ from: holder1, value: ether('1').toString() }); await dao.invest({ from: holder2, value: ether('3').toString() }); await dao.startDistribution(); await dao.claim({ from: holder1 }); await dao.claim({ from: holder2 }); await venture1.setIssuePrice(ether('1')); await venture2.setIssuePrice(ether('1')); await venture1.startIssuance(); await venture2.startIssuance(); }); /** * @test {DAO#investVenture} */ it('cannot invest in venture from outside voting contract', async () => { await expectRevert( dao.investVenture(venture1.address, ether('1')), 'Restricted to proposals.', ); }); /** * @test {DAO#propose} */ it('can propose venture', async () => { expectEvent( await dao.propose( web3.eth.abi.encodeFunctionCall({ type: 'function', name: 'investVenture', payable: false, inputs: [{ name: 'venture', type: 'address', }, { name: 'investment', type: 'uint256', }], }, [venture1.address, ether('1').toString()]) ), 'Proposal', ); }); describe('once ventures are proposed and invested in', () => { beforeEach(async () => { voting1 = await Voting.at( (await dao.propose( web3.eth.abi.encodeFunctionCall({ type: 'function', name: 'investVenture', payable: false, inputs: [{ name: 'venture', type: 'address', }, { name: 'investment', type: 'uint256', }], }, [venture1.address, ether('1').toString()]) )).logs[1].args.proposal ); voting2 = await Voting.at( (await dao.propose( web3.eth.abi.encodeFunctionCall({ type: 'function', name: 'investVenture', payable: false, inputs: [{ name: 'venture', type: 'address', }, { name: 'investment', type: 'uint256', }], }, [venture2.address, ether('2').toString()]) )).logs[1].args.proposal ); await dao.approve(voting1.address, ether('10'), { from: holder1 }); await dao.approve(voting1.address, ether('10'), { from: holder2 }); await dao.approve(voting2.address, ether('10'), { from: holder1 }); await dao.approve(voting2.address, ether('10'), { from: holder2 }); await voting1.vote(ether('3'), { from: holder1 }); await voting1.vote(ether('8'), { from: holder2 }); await voting1.validate(); await voting1.cancel({ from: holder1 }); await voting1.cancel({ from: holder2 }); await voting1.enact(); await voting2.vote(ether('2'), { from: holder1 }); await voting2.vote(ether('10'), { from: holder2 }); await voting2.validate(); await voting2.cancel({ from: holder1 }); await voting2.cancel({ from: holder2 }); await voting2.enact(); }); it('can retrieve tokens from invested venture', async () => { await venture1.startDistribution(); await venture2.startDistribution(); await dao.retrieveVentureTokens(venture1.address); await dao.retrieveVentureTokens(venture2.address); BN(await venture1.balanceOf(dao.address)).should.be.bignumber.equal(ether('10')); BN(await venture2.balanceOf(dao.address)).should.be.bignumber.equal(ether('0.2')); }); it('can cancel investment in venture', async () => { const daoTracker = await balance.tracker(dao.address); await daoTracker.get(); voting1 = await Voting.at( (await dao.propose( web3.eth.abi.encodeFunctionCall({ type: 'function', name: 'cancelVenture', payable: false, inputs: [{ name: 'venture', type: 'address', }], }, [venture1.address]) )).logs[1].args.proposal ); await dao.approve(voting1.address, ether('10'), { from: holder1 }); await dao.approve(voting1.address, ether('10'), { from: holder2 }); await voting1.vote(ether('3'), { from: holder1 }); await voting1.vote(ether('8'), { from: holder2 }); await voting1.validate(); await voting1.cancel({ from: holder1 }); await voting1.cancel({ from: holder2 }); await voting1.enact(); BN(await daoTracker.delta()).should.be.bignumber.equal(ether('1')); }); describe('once venture tokens are retrieved', async () => { let dividends1: BN; let dividends2: BN; beforeEach(async () => { await venture1.invest({ from: ventureHolder1, value: ether('2').toString() }); await venture1.invest({ from: ventureHolder2, value: ether('1').toString() }); await venture2.invest({ from: ventureHolder1, value: ether('1').toString() }); await venture2.invest({ from: ventureHolder2, value: ether('1').toString() }); await venture1.startDistribution(); await venture2.startDistribution(); await dao.retrieveVentureTokens(venture1.address); await dao.retrieveVentureTokens(venture2.address); await venture1.claim({ from: ventureHolder1 }); await venture1.claim({ from: ventureHolder2 }); await venture2.claim({ from: ventureHolder1 }); await venture2.claim({ from: ventureHolder2 }); await venture1.releaseDividends({ from: ventureClient1, value: ether('1').toString() }); await venture1.releaseDividends({ from: ventureClient2, value: ether('3').toString() }); await venture2.releaseDividends({ from: ventureClient1, value: ether('1').toString() }); await venture2.releaseDividends({ from: ventureClient2, value: ether('5').toString() }); dividends1 = new BN((await dao.claimDividendsFromVenture.call(venture1.address)).toString()); dividends2 = new BN((await dao.claimDividendsFromVenture.call(venture2.address)).toString()); await dao.claimDividendsFromVenture(venture1.address); await dao.claimDividendsFromVenture(venture2.address); }); it('investors can profit from venture dividends', async () => { voting1 = await Voting.at( (await dao.propose( web3.eth.abi.encodeFunctionCall({ type: 'function', name: 'releaseDividends', payable: false, inputs: [{ name: 'amount', type: 'uint256', }], }, [dividends1.add(dividends2).toString()]) )).logs[1].args.proposal ); await dao.approve(voting1.address, ether('10'), { from: holder1 }); await dao.approve(voting1.address, ether('10'), { from: holder2 }); await voting1.vote(ether('3'), { from: holder1 }); await voting1.vote(ether('8'), { from: holder2 }); await voting1.validate(); await voting1.cancel({ from: holder1 }); await voting1.cancel({ from: holder2 }); await voting1.enact(); BN(await dao.claimDividends.call({ from: holder1 })).should.be .bignumber.gt(ether('0.95')).and.bignumber.lt(ether('1.05')); BN(await dao.claimDividends.call({ from: holder2 })).should.be .bignumber.gt(ether('2.95')).and.bignumber.lt(ether('3.05')); }); it('investors can reopen an investor round', async () => { voting1 = await Voting.at( (await dao.propose( web3.eth.abi.encodeFunctionCall({ type: 'function', name: 'restartInvestorRound', payable: false, inputs: [{ name: '_issuePrice', type: 'uint256', }], }, [ether('1').toString()]) )).logs[1].args.proposal ); await dao.approve(voting1.address, ether('10'), { from: holder1 }); await dao.approve(voting1.address, ether('10'), { from: holder2 }); await voting1.vote(ether('3'), { from: holder1 }); await voting1.vote(ether('8'), { from: holder2 }); await voting1.validate(); await voting1.cancel({ from: holder1 }); await voting1.cancel({ from: holder2 }); await voting1.enact(); bytes32ToString(await dao.currentState()).should.be.equal('OPEN'); }); describe('once investing round is restarted', () => { beforeEach(async () => { voting1 = await Voting.at( (await dao.propose( web3.eth.abi.encodeFunctionCall({ type: 'function', name: 'restartInvestorRound', payable: false, inputs: [{ name: '_issuePrice', type: 'uint256', }], }, [ether('1').toString()]) )).logs[1].args.proposal ); await dao.approve(voting1.address, ether('10'), { from: holder1 }); await dao.approve(voting1.address, ether('10'), { from: holder2 }); await voting1.vote(ether('3'), { from: holder1 }); await voting1.vote(ether('8'), { from: holder2 }); await voting1.validate(); await voting1.cancel({ from: holder1 }); await voting1.cancel({ from: holder2 }); await voting1.enact(); }); it('new investors can claim dao tokens', async () => { await dao.invest({ from: holder3, value: ether('1').toString() }); await dao.invest({ from: holder4, value: ether('3').toString() }); voting1 = await Voting.at( (await dao.propose( web3.eth.abi.encodeFunctionCall({ type: 'function', name: 'restartDistribution', payable: false, inputs: [], }, []), )).logs[1].args.proposal ); await dao.approve(voting1.address, ether('10'), { from: holder1 }); await dao.approve(voting1.address, ether('10'), { from: holder2 }); await voting1.vote(ether('3'), { from: holder1 }); await voting1.vote(ether('8'), { from: holder2 }); await voting1.validate(); await voting1.cancel({ from: holder1 }); await voting1.cancel({ from: holder2 }); await voting1.enact(); await dao.claim({ from: holder3 }); await dao.claim({ from: holder4 }); BN(await dao.balanceOf(holder3)).should.be.bignumber.equal(ether('1')); BN(await dao.balanceOf(holder4)).should.be.bignumber.equal(ether('3')); }); it('investors can cancel new founding round', async () => { const daoTracker = await balance.tracker(dao.address); await daoTracker.get(); await dao.invest({ from: holder3, value: ether('1').toString() }); await dao.invest({ from: holder4, value: ether('3').toString() }); voting1 = await Voting.at( (await dao.propose( web3.eth.abi.encodeFunctionCall({ type: 'function', name: 'cancelInvestmentRound', payable: false, inputs: [], }, []), )).logs[1].args.proposal ); await dao.approve(voting1.address, ether('10'), { from: holder1 }); await dao.approve(voting1.address, ether('10'), { from: holder2 }); await voting1.vote(ether('3'), { from: holder1 }); await voting1.vote(ether('8'), { from: holder2 }); await voting1.validate(); await voting1.cancel({ from: holder1 }); await voting1.cancel({ from: holder2 }); await voting1.enact(); await dao.cancelInvestment({ from: holder3 }); await dao.cancelInvestment({ from: holder4 }); BN(await daoTracker.delta()).should.be.bignumber.equal(ether('0')); }); }); }); }); }); }); function bytes32ToString(text: string) { return web3.utils.toAscii(text).replace(/\0/g, ''); }
the_stack
import { Inject, Injectable, isDevMode, OnDestroy, Optional } from '@angular/core'; import { Params } from '@angular/router'; import { EMPTY, from, Observable, Subject } from 'rxjs'; import { catchError, concatMap, debounceTime, distinctUntilChanged, filter, map, startWith, switchMap, takeUntil, tap } from 'rxjs/operators'; import { compareParamMaps, filterParamMap, isMissing, isPresent, NOP } from '../util'; import { Unpack } from '../types'; import { QueryParamGroup } from '../model/query-param-group'; import { QueryParam } from '../model/query-param'; import { NGQP_ROUTER_ADAPTER, NGQP_ROUTER_OPTIONS, RouterAdapter, RouterOptions } from '../router-adapter/router-adapter.interface'; import { QueryParamAccessor } from './query-param-accessor.interface'; /** @internal */ function isMultiQueryParam<T>( queryParam: QueryParam<T> | QueryParam<T[]> ): queryParam is QueryParam<T[]> { return queryParam.multi; } /** @internal */ function hasArrayValue<T>( queryParam: QueryParam<T> | QueryParam<T[]>, value: T | T[] ): value is T[] { return isMultiQueryParam(queryParam); } /** @internal */ function hasArraySerialization( queryParam: QueryParam<any>, values: string | string[] | null ): values is string[] { return isMultiQueryParam(queryParam); } /** @internal */ class NavigationData { constructor(public params: Params, public synthetic: boolean = false) {} } /** * Service implementing the synchronization logic * * This service is the key to the synchronization process by binding a {@link QueryParamGroup} * to the router. * * @internal */ @Injectable() export class QueryParamGroupService implements OnDestroy { /** The {@link QueryParamGroup} to bind. */ private queryParamGroup: QueryParamGroup; /** List of {@link QueryParamAccessor} registered to this service. */ private directives = new Map<string, QueryParamAccessor[]>(); /** * Queue of navigation parameters * * A queue is used for navigations as we need to make sure all parameter changes * are executed in sequence as otherwise navigations might overwrite each other. */ private queue$ = new Subject<NavigationData>(); /** @ignore */ private synchronizeRouter$ = new Subject<void>(); /** @ignore */ private destroy$ = new Subject<void>(); constructor( @Inject(NGQP_ROUTER_ADAPTER) private routerAdapter: RouterAdapter, @Optional() @Inject(NGQP_ROUTER_OPTIONS) private globalRouterOptions: RouterOptions ) { this.setupNavigationQueue(); } /** @ignore */ public ngOnDestroy() { this.destroy$.next(); this.destroy$.complete(); this.synchronizeRouter$.complete(); if (this.queryParamGroup) { this.queryParamGroup._clearChangeFunctions(); } } /** * Uses the given {@link QueryParamGroup} for synchronization. */ public setQueryParamGroup(queryParamGroup: QueryParamGroup): void { // FIXME: If this is called when we already have a group, we probably need to do // some cleanup first. if (this.queryParamGroup) { throw new Error( `A QueryParamGroup has already been setup. Changing the group is currently not supported.` ); } this.queryParamGroup = queryParamGroup; this.startSynchronization(); } /** * Registers a {@link QueryParamAccessor}. */ public registerQueryParamDirective(directive: QueryParamAccessor): void { // Capture the name here, particularly for the queue below to avoid re-evaluating // it as it might change over time. const queryParamName = directive.name; const queryParam: QueryParam<any> = this.queryParamGroup.get(queryParamName); if (!queryParam) { throw new Error( `Could not find query param with name ${queryParamName}. Did you forget to add it to your QueryParamGroup?` ); } if (!directive.valueAccessor) { throw new Error( `No value accessor found for the form control. Please make sure to implement ControlValueAccessor on this component.` ); } // Chances are that we read the initial route before a directive has been registered here. // The value in the model will be correct, but we need to sync it to the view once initially. directive.valueAccessor.writeValue(queryParam.value); // Proxy updates from the view to debounce them (if needed). const debouncedQueue$ = new Subject<any>(); debouncedQueue$ .pipe( // Do not synchronize while the param is detached from the group filter(() => !!this.queryParamGroup.get(queryParamName)), isPresent(queryParam.debounceTime) ? debounceTime(queryParam.debounceTime) : tap(), map((newValue: any) => this.getParamsForValue(queryParam, newValue)), takeUntil(this.destroy$) ) .subscribe(params => this.enqueueNavigation(new NavigationData(params))); directive.valueAccessor.registerOnChange((newValue: any) => debouncedQueue$.next(newValue)); this.directives.set(queryParamName, [ ...(this.directives.get(queryParamName) || []), directive ]); } /** * Deregisters a {@link QueryParamAccessor} by referencing its name. */ public deregisterQueryParamDirective(queryParamName: string): void { if (!queryParamName) { return; } const directives = this.directives.get(queryParamName); if (!directives) { return; } directives.forEach(directive => { directive.valueAccessor.registerOnChange(NOP); directive.valueAccessor.registerOnTouched(NOP); }); this.directives.delete(queryParamName); const queryParam: QueryParam<any> = this.queryParamGroup.get(queryParamName); if (queryParam) { queryParam._clearChangeFunctions(); } } private startSynchronization() { this.setupGroupChangeListener(); this.setupParamChangeListeners(); this.setupRouterListener(); this.watchNewParams(); } /** Listens for programmatic changes on group level and synchronizes to the router. */ private setupGroupChangeListener(): void { this.queryParamGroup._registerOnChange((newValue: Record<string, any>) => { let params: Params = {}; Object.keys(newValue).forEach(queryParamName => { const queryParam: QueryParam<any> = this.queryParamGroup.get(queryParamName); if (isMissing(queryParam)) { return; } params = { ...params, ...this.getParamsForValue(queryParam, newValue[queryParamName]) }; }); this.enqueueNavigation(new NavigationData(params, true)); }); } /** Listens for programmatic changes on parameter level and synchronizes to the router. */ private setupParamChangeListeners(): void { Object.keys(this.queryParamGroup.queryParams).forEach(queryParamName => this.setupParamChangeListener(queryParamName) ); } private setupParamChangeListener(queryParamName: string): void { const queryParam: QueryParam<any> = this.queryParamGroup.get(queryParamName); if (!queryParam) { throw new Error(`No param in group found for name ${queryParamName}`); } queryParam._registerOnChange((newValue: any) => this.enqueueNavigation( new NavigationData(this.getParamsForValue(queryParam, newValue), true) ) ); } /** Listens for changes in the router and synchronizes to the model. */ private setupRouterListener(): void { this.synchronizeRouter$ .pipe( startWith(undefined), switchMap(() => this.routerAdapter.queryParamMap.pipe( // We want to ignore changes to query parameters which aren't related to this // particular group; however, we do need to react if one of our parameters has // vanished when it was set before. distinctUntilChanged((previousMap, currentMap) => { const keys = Object.values(this.queryParamGroup.queryParams).map( queryParam => queryParam.urlParam ); // It is important that we filter the maps only here so that both are filtered // with the same set of keys; otherwise, e.g. removing a parameter from the group // would interfere. return compareParamMaps( filterParamMap(previousMap, keys), filterParamMap(currentMap, keys) ); }) ) ), takeUntil(this.destroy$) ) .subscribe(queryParamMap => { const synthetic = this.isSyntheticNavigation(); const groupValue: Record<string, any> = {}; Object.keys(this.queryParamGroup.queryParams).forEach(queryParamName => { const queryParam: QueryParam<any> = this.queryParamGroup.get(queryParamName); const newValue = queryParam.multi ? this.deserialize(queryParam, queryParamMap.getAll(queryParam.urlParam)) : this.deserialize(queryParam, queryParamMap.get(queryParam.urlParam)); const directives = this.directives.get(queryParamName); if (directives) { directives.forEach(directive => directive.valueAccessor.writeValue(newValue) ); } groupValue[queryParamName] = newValue; }); this.queryParamGroup.setValue(groupValue, { emitEvent: !synthetic, emitModelToViewChange: false }); }); } /** Listens for newly added parameters and starts synchronization for them. */ private watchNewParams(): void { this.queryParamGroup.queryParamAdded$ .pipe(takeUntil(this.destroy$)) .subscribe(queryParamName => { this.setupParamChangeListener(queryParamName); this.synchronizeRouter$.next(); }); } /** Returns true if the current navigation is synthetic. */ private isSyntheticNavigation(): boolean { const navigation = this.routerAdapter.getCurrentNavigation(); if (!navigation || navigation.trigger !== 'imperative') { // When using the back / forward buttons, the state is passed along with it, even though // for us it's now a navigation initiated by the user. Therefore, a navigation can only // be synthetic if it has been triggered imperatively. // See https://github.com/angular/angular/issues/28108. return false; } return navigation.extras && navigation.extras.state && navigation.extras.state['synthetic']; } /** Subscribes to the parameter queue and executes navigations in sequence. */ private setupNavigationQueue() { this.queue$ .pipe( takeUntil(this.destroy$), concatMap(data => this.navigateSafely(data)) ) .subscribe(); } private navigateSafely(data: NavigationData): Observable<any> { return from( this.routerAdapter.navigate(data.params, { ...this.routerOptions, state: { synthetic: data.synthetic } }) ).pipe( catchError((err: any) => { if (isDevMode()) { console.error(`There was an error while navigating`, err); } return EMPTY; }) ); } /** Sends a change of parameters to the queue. */ private enqueueNavigation(data: NavigationData): void { this.queue$.next(data); } /** * Returns the full set of parameters given a value for a parameter model. * * This consists mainly of properly serializing the model value and ensuring to take * side effect changes into account that may have been configured. */ private getParamsForValue<T>(queryParam: QueryParam<any>, value: T | undefined | null): Params { const newValue = this.serialize(queryParam, value); const combinedParams: Params = isMissing(queryParam.combineWith) ? {} : queryParam.combineWith(value); // Note that we list the side-effect parameters first so that our actual parameter can't be // overridden by it. return { ...(combinedParams || {}), [queryParam.urlParam]: newValue }; } private serialize<T>(queryParam: QueryParam<any>, value: T): string | string[] { if (hasArrayValue(queryParam, value)) { return (value || []).map(queryParam.serialize); } else { return queryParam.serialize(value); } } private deserialize<T>( queryParam: QueryParam<T>, values: string | string[] ): Unpack<T> | Unpack<T>[] { if (hasArraySerialization(queryParam, values)) { return values.map(queryParam.deserialize); } else { return queryParam.deserialize(values); } } /** * Returns the current set of options to pass to the router. * * This merges the global configuration with the group specific configuration. */ private get routerOptions(): RouterOptions { const groupOptions = this.queryParamGroup ? this.queryParamGroup.routerOptions : {}; return { ...(this.globalRouterOptions || {}), ...groupOptions }; } }
the_stack
import { MountingOptions, mount } from '@vue/test-utils' import { h } from 'vue' import { renderWork, wait } from '@tests' import { IxEmpty } from '@idux/components/empty' import { IxIcon } from '@idux/components/icon' import Tree from '../src/Tree' import { TreeNode, TreeProps } from '../src/types' const dataSource: TreeNode[] = [ { label: 'Node 0', key: '0', children: [ { label: 'Node 0-0', key: '0-0', children: [ { label: 'Node 0-0-0', key: '0-0-0' }, { label: 'Node 0-0-1', key: '0-0-1' }, { label: 'Node 0-0-2', key: '0-0-2' }, ], }, { label: 'Node 0-1', key: '0-1', disabled: true, children: [ { label: 'Node 0-1-0', key: '0-1-0' }, { label: 'Node 0-1-1', key: '0-1-1' }, { label: 'Node 0-1-2', key: '0-1-2' }, ], }, ], }, { label: 'Node 1', key: '1', children: [ { label: 'Node 1-0', key: '1-0', children: [ { label: 'Node 1-0-0', key: '1-0-0' }, { label: 'Node 1-0-1', key: '1-0-1' }, { label: 'Node 1-0-2', key: '1-0-2' }, ], }, { label: 'Node 1-1', key: '1-1', children: [ { label: 'Node 1-1-0', key: '1-1-0' }, { label: 'Node 1-1-1', key: '1-1-1' }, { label: 'Node 1-1-2', key: '1-1-2' }, ], }, ], }, { label: 'Node 2', key: '2' }, ] const simpleDataSource = [ { label: 'Node 0', key: '0', children: [ { label: 'Node 0-0', key: '0-0', }, { label: 'Node 0-1', key: '0-1', }, { label: 'Node 0-2', key: '0-2', }, ], }, ] const checkedKeys = ['0-0', '0-1'] const expandedKeys = ['0', '0-0', '0-1'] const selectedKeys = ['0-1'] describe('Tree', () => { const TreeMount = (options?: MountingOptions<Partial<TreeProps>>) => { const { props, ...rest } = options || {} return mount(Tree, { ...rest, props: { dataSource, expandedKeys, checkedKeys, selectedKeys, checkable: true, ...props }, }) } renderWork<TreeProps>(Tree, { props: { dataSource, expandedKeys, checkedKeys, selectedKeys, checkable: true }, }) describe('v-model:checkedKeys work', () => { test('with cascade', async () => { const onUpdateCheckedKeys = jest.fn() const wrapper = TreeMount({ props: { dataSource: simpleDataSource, cascade: true, checkedKeys: ['0'], 'onUpdate:checkedKeys': onUpdateCheckedKeys, }, }) const allNodes = wrapper.findAll('.ix-tree-node') allNodes.forEach(node => { expect(node.find('.ix-checkbox-checked').exists()).toBe(true) }) // 0-0, unchecked await allNodes[1].find('input').setValue(false) expect(onUpdateCheckedKeys).toBeCalledWith(['0-1', '0-2']) await wrapper.setProps({ checkedKeys: ['0-0'] }) // 0 indeterminate expect(allNodes[0].find('.ix-checkbox-indeterminate').exists()).toBe(true) }) test('with checkStrategy: all', async () => { const onUpdateCheckedKeys = jest.fn() const wrapper = TreeMount({ props: { dataSource: simpleDataSource, checkedKeys: ['0', '0-0'], checkStrategy: 'all', 'onUpdate:checkedKeys': onUpdateCheckedKeys, }, }) const allNodes = wrapper.findAll('.ix-tree-node') expect(allNodes[0].find('.ix-checkbox-checked').exists()).toBe(true) expect(allNodes[1].find('.ix-checkbox-checked').exists()).toBe(true) expect(allNodes[2].find('.ix-checkbox-checked').exists()).toBe(false) expect(allNodes[3].find('.ix-checkbox-checked').exists()).toBe(false) // 0-0, unchecked await allNodes[1].find('input').setValue(false) expect(onUpdateCheckedKeys).toBeCalledWith(['0']) await wrapper.setProps({ cascade: true, checkedKeys: [] }) // 0, checked await allNodes[0].find('input').setValue(true) expect(onUpdateCheckedKeys).toBeCalledWith(['0', '0-0', '0-1', '0-2']) }) test('with checkStrategy: parent', async () => { const onUpdateCheckedKeys = jest.fn() const wrapper = TreeMount({ props: { dataSource: [ { label: 'Node 0', key: '0', children: [ { label: 'Node 0-0', key: '0-0', }, { label: 'Node 0-1', key: '0-1', disabled: true, }, { label: 'Node 0-2', key: '0-2', }, ], }, ], checkedKeys: ['0'], cascade: true, checkStrategy: 'parent', 'onUpdate:checkedKeys': onUpdateCheckedKeys, }, }) const allNodes = wrapper.findAll('.ix-tree-node') expect(allNodes[0].find('.ix-checkbox-checked').exists()).toBe(false) expect(allNodes[1].find('.ix-checkbox-checked').exists()).toBe(true) // 0-1 exclude disabled expect(allNodes[2].find('.ix-checkbox-checked').exists()).toBe(false) expect(allNodes[3].find('.ix-checkbox-checked').exists()).toBe(true) // 0-0, unchecked await allNodes[1].find('input').setValue(false) expect(onUpdateCheckedKeys).toBeCalledWith(['0-2']) await wrapper.setProps({ checkedKeys: [] }) expect(allNodes[0].find('.ix-checkbox-checked').exists()).toBe(false) expect(allNodes[1].find('.ix-checkbox-checked').exists()).toBe(false) expect(allNodes[3].find('.ix-checkbox-checked').exists()).toBe(false) // 0-0 checked await allNodes[1].find('input').setValue(true) expect(onUpdateCheckedKeys).toBeCalledWith(['0-0']) // 0 checked await allNodes[0].find('input').setValue(true) expect(onUpdateCheckedKeys).toBeCalledWith(['0-0', '0-2']) }) test('with checkStrategy: child', async () => { const onUpdateCheckedKeys = jest.fn() const wrapper = TreeMount({ props: { dataSource: [ { label: 'Node 0', key: '0', children: [ { label: 'Node 0-0', key: '0-0', }, { label: 'Node 0-1', key: '0-1', disabled: true, }, ], }, ], checkedKeys: ['0-0', '0-1'], cascade: true, checkStrategy: 'child', 'onUpdate:checkedKeys': onUpdateCheckedKeys, }, }) const allNodes = wrapper.findAll('.ix-tree-node') expect(allNodes[0].find('.ix-checkbox-checked').exists()).toBe(true) expect(allNodes[0].find('.ix-checkbox-checked').exists()).toBe(true) expect(allNodes[0].find('.ix-checkbox-checked').exists()).toBe(true) //0-0, unchecked await allNodes[1].find('input').setValue(false) expect(onUpdateCheckedKeys).toBeCalledWith(['0-1']) await wrapper.setProps({ checkedKeys: [] }) expect(allNodes[0].find('.ix-checkbox-checked').exists()).toBe(false) expect(allNodes[0].find('.ix-checkbox-checked').exists()).toBe(false) expect(allNodes[0].find('.ix-checkbox-checked').exists()).toBe(false) //0, checked await allNodes[0].find('input').setValue(true) expect(onUpdateCheckedKeys).toBeCalledWith(['0-0']) }) test('with all children disabled', async () => { const onUpdateCheckedKeys = jest.fn() const wrapper = TreeMount({ props: { dataSource: [ { label: 'Node 0', key: '0', children: [ { label: 'Node 0-0', key: '0-0', disabled: true, }, { label: 'Node 0-1', key: '0-1', disabled: true, }, ], }, ], checkedKeys: [], cascade: true, checkStrategy: 'child', 'onUpdate:checkedKeys': onUpdateCheckedKeys, }, }) const allNodes = wrapper.findAll('.ix-tree-node') //0, checked await allNodes[0].find('input').setValue(true) expect(onUpdateCheckedKeys).toBeCalledWith([]) }) }) test('v-model:expandedKeys work', async () => { const onUpdateExpandedKeys = jest.fn() const wrapper = TreeMount({ props: { expandedKeys: ['0'], 'onUpdate:expandedKeys': onUpdateExpandedKeys }, }) const allNodes = wrapper.findAll('.ix-tree-node') expect(allNodes[0].classes()).toContain('ix-tree-node-expanded') await wrapper.setProps({ expandedKeys: ['0', '0-0'] }) expect(allNodes[0].classes()).toContain('ix-tree-node-expanded') expect(allNodes[1].classes()).toContain('ix-tree-node-expanded') // 0-0 await allNodes[1].find('.ix-tree-node-expand').trigger('click') expect(onUpdateExpandedKeys).toBeCalledWith(['0']) await wrapper.setProps({ expandedKeys: ['0'] }) expect(allNodes[0].classes()).toContain('ix-tree-node-expanded') expect(allNodes[1].classes()).not.toContain('ix-tree-node-expanded') // 0-0 await allNodes[1].find('.ix-tree-node-expand').trigger('click') expect(onUpdateExpandedKeys).toBeCalledWith(['0', '0-0']) await wrapper.setProps({ expandedKeys: ['0', '0-0'] }) expect(allNodes[0].classes()).toContain('ix-tree-node-expanded') expect(allNodes[1].classes()).toContain('ix-tree-node-expanded') }) test('v-model:selectedKeys work', async () => { const onUpdateSelectedKeys = jest.fn() const wrapper = TreeMount({ props: { selectedKeys: ['0'], 'onUpdate:selectedKeys': onUpdateSelectedKeys }, }) const allNodes = wrapper.findAll('.ix-tree-node') expect(allNodes[0].classes()).toContain('ix-tree-node-selected') await wrapper.setProps({ selectedKeys: ['0', '0-0'] }) expect(allNodes[0].classes()).toContain('ix-tree-node-selected') expect(allNodes[1].classes()).toContain('ix-tree-node-selected') // 0-0 await allNodes[1].find('.ix-tree-node-content').trigger('click') expect(onUpdateSelectedKeys).toBeCalledWith([]) await wrapper.setProps({ selectedKeys: [] }) expect(allNodes[0].classes()).not.toContain('ix-tree-node-selected') expect(allNodes[1].classes()).not.toContain('ix-tree-node-selected') // 0-0 await allNodes[1].find('.ix-tree-node-content').trigger('click') expect(onUpdateSelectedKeys).toBeCalledWith(['0-0']) await wrapper.setProps({ selectedKeys: ['0-0'] }) expect(allNodes[0].classes()).not.toContain('ix-tree-node-selected') expect(allNodes[1].classes()).toContain('ix-tree-node-selected') }) test('selectable work', async () => { const onUpdateSelectedKeys = jest.fn() const wrapper = TreeMount({ props: { selectable: false, selectedKeys: [], 'onUpdate:selectedKeys': onUpdateSelectedKeys }, }) const allNodes = wrapper.findAll('.ix-tree-node') // 0 await allNodes[0].find('.ix-tree-node-content').trigger('click') expect(allNodes[0].classes()).not.toContain('ix-tree-node-selected') expect(onUpdateSelectedKeys).not.toBeCalled() // 0-0 await wrapper.setProps({ selectable: true }) await allNodes[0].find('.ix-tree-node-content').trigger('click') expect(onUpdateSelectedKeys).toBeCalledWith(['0']) await wrapper.setProps({ selectedKeys: ['0'] }) expect(allNodes[0].classes()).toContain('ix-tree-node-selected') await allNodes[1].find('.ix-tree-node-content').trigger('click') expect(onUpdateSelectedKeys).toBeCalledWith(['0-0']) await wrapper.setProps({ selectedKeys: ['0-0'] }) expect(allNodes[0].classes()).not.toContain('ix-tree-node-selected') expect(allNodes[1].classes()).toContain('ix-tree-node-selected') await wrapper.setProps({ selectable: 'multiple' }) await allNodes[0].find('.ix-tree-node-content').trigger('click') expect(onUpdateSelectedKeys).toBeCalledWith(['0-0', '0']) await wrapper.setProps({ selectedKeys: ['0-0', '0'] }) expect(allNodes[0].classes()).toContain('ix-tree-node-selected') expect(allNodes[1].classes()).toContain('ix-tree-node-selected') }) test('blocked work', async () => { const wrapper = TreeMount({ props: { blocked: true }, }) expect(wrapper.classes()).toContain('ix-tree-blocked') await wrapper.setProps({ blocked: false }) expect(wrapper.classes()).not.toContain('ix-tree-blocked') }) test('checkable work', async () => { const wrapper = TreeMount({ props: { checkable: true }, }) expect(wrapper.find('.ix-checkbox').exists()).toBe(true) await wrapper.setProps({ checkable: false }) expect(wrapper.find('.ix-checkbox').exists()).toBe(false) }) test('childrenKey work', async () => { const dataSource: TreeNode[] = [ { label: 'Node 0', key: '0', test: [ { label: 'Node 0-0', key: '0-0', test: [ { label: 'Node 0-0-0', key: '0-0-0' }, { label: 'Node 0-0-1', key: '0-0-1' }, ], }, { label: 'Node 0-1', key: '0-1', disabled: true, test: [ { label: 'Node 0-1-0', key: '0-1-0' }, { label: 'Node 0-1-1', key: '0-1-1' }, ], }, ], }, ] const wrapper = TreeMount({ props: { dataSource, childrenKey: 'test' }, }) expect(wrapper.html()).toMatchSnapshot() }) test('labelKey work', async () => { const dataSource: TreeNode[] = [ { test: 'Node 0', key: '0', children: [ { test: 'Node 0-0', key: '0-0', children: [ { test: 'Node 0-0-0', key: '0-0-0' }, { test: 'Node 0-0-1', key: '0-0-1' }, ], }, { test: 'Node 0-1', key: '0-1', disabled: true, children: [ { test: 'Node 0-1-0', key: '0-1-0' }, { test: 'Node 0-1-1', key: '0-1-1' }, ], }, ], }, ] const wrapper = TreeMount({ props: { dataSource, labelKey: 'test' }, }) expect(wrapper.html()).toMatchSnapshot() }) test('dataSource work', async () => { const wrapper = TreeMount() expect(wrapper.html()).toMatchSnapshot() await wrapper.setProps({ dataSource: [ { label: 'Node 0-change', key: '0', children: [ { label: 'Node 0-0-change', key: '0-0', children: [ { label: 'Node 0-0-0', key: '0-0-0' }, { label: 'Node 0-0-1', key: '0-0-1' }, ], }, { label: 'Node 0-1', key: '0-1', disabled: true, children: [ { label: 'Node 0-1-0', key: '0-1-0' }, { label: 'Node 0-1-1', key: '0-1-1' }, ], }, ], }, { label: 'Node 1', key: '1', children: [ { label: 'Node 1-0', key: '1-0', children: [ { label: 'Node 1-0-0', key: '1-0-0' }, { label: 'Node 1-0-1', key: '1-0-1' }, ], }, ], }, ], }) expect(wrapper.html()).toMatchSnapshot() }) test('disabled work', async () => { const onUpdateCheckedKeys = jest.fn() const wrapper = TreeMount({ props: { disabled: node => node.key === '0', 'onUpdate:checkedKeys': onUpdateCheckedKeys, }, }) const allNodes = wrapper.findAll('.ix-tree-node') expect(allNodes[0].classes()).toContain('ix-tree-node-disabled') expect(allNodes[0].find('.ix-checkbox').classes()).toContain('ix-checkbox-disabled') expect(allNodes[1].classes()).not.toContain('ix-tree-node-disabled') expect(allNodes[1].find('.ix-checkbox').classes()).not.toContain('ix-checkbox-disabled') await allNodes[0].find('input').setValue(true) expect(onUpdateCheckedKeys).not.toBeCalled() await wrapper.setProps({ disabled: (node: TreeNode) => node.key === '0-0' }) expect(allNodes[0].classes()).not.toContain('ix-tree-node-disabled') expect(allNodes[0].find('.ix-checkbox').classes()).not.toContain('ix-checkbox-disabled') expect(allNodes[1].classes()).toContain('ix-tree-node-disabled') expect(allNodes[1].find('.ix-checkbox').classes()).toContain('ix-checkbox-disabled') await allNodes[0].find('input').setValue(false) expect(onUpdateCheckedKeys).toBeCalled() }) test('empty work', async () => { let emptyDescription = 'This is an empty tree' const wrapper = TreeMount({ props: { dataSource: [], empty: emptyDescription }, }) expect(wrapper.find('.ix-empty').text()).toBe(emptyDescription) emptyDescription = 'This is an empty tree2' await wrapper.setProps({ empty: { description: emptyDescription } }) expect(wrapper.find('.ix-empty').text()).toBe(emptyDescription) }) test('empty slot work', async () => { const wrapper = TreeMount({ props: { dataSource: [] }, slots: { empty: () => h(IxEmpty, { description: 'empty slot' }) }, }) expect(wrapper.find('.ix-empty-description').text()).toBe('empty slot') }) test('expandIcon work', async () => { const wrapper = TreeMount({ props: { expandIcon: 'up' }, }) expect(wrapper.find('.ix-tree-node-expand').find('.ix-icon-up').exists()).toBe(true) await wrapper.setProps({ expandIcon: 'down' }) expect(wrapper.find('.ix-tree-node-expand').find('.ix-icon-up').exists()).toBe(false) expect(wrapper.find('.ix-tree-node-expand').find('.ix-icon-down').exists()).toBe(true) }) test('expandIcon slot work', async () => { const onUpdateExpandedKeys = jest.fn() const wrapper = TreeMount({ props: { expandIcon: 'right', 'onUpdate:expandedKeys': onUpdateExpandedKeys }, slots: { expandIcon: ({ expanded }: { expanded: boolean }) => h(IxIcon, { name: expanded ? 'down' : 'up' }), }, }) const allNodes = wrapper.findAll('.ix-tree-node') expect(allNodes[0].find('.ix-icon-down').exists()).toBe(true) await allNodes[0].find('.ix-tree-node-expand').trigger('click') expect(onUpdateExpandedKeys).toBeCalledWith(['0-0', '0-1']) await wrapper.setProps({ expandedKeys: ['0-0', '0-1'] }) expect(wrapper.find('.ix-tree-node-expand').find('.ix-icon-up').exists()).toBe(true) expect(wrapper.find('.ix-tree-node-expand').find('.ix-icon-down').exists()).toBe(false) }) test('height and virtual work', async () => { const wrapper = TreeMount({ props: { height: 100, virtual: true }, }) expect(wrapper.find('.cdk-virtual-scroll').exists()).toBe(true) expect(wrapper.html()).toMatchSnapshot() await wrapper.setProps({ virtual: false }) expect(wrapper.find('.ix-virtual-scroll').exists()).toBe(false) expect(wrapper.html()).toMatchSnapshot() }) test('leafLineIcon and showLine work', async () => { const wrapper = TreeMount({ props: { showLine: true, leafLineIcon: 'up' }, }) // 0-0-0 const leafNode = wrapper.findAll('.ix-tree-node')[2] expect(wrapper.classes()).toContain('ix-tree-show-line') expect(leafNode.find('.ix-tree-node-leaf').find('.ix-icon-up').exists()).toBe(true) expect(leafNode.find('.ix-tree-node-leaf').find('.ix-tree-node-leaf-line').exists()).toBe(false) await wrapper.setProps({ leafLineIcon: undefined }) expect(leafNode.find('.ix-tree-node-leaf').find('.ix-icon-up').exists()).toBe(false) expect(leafNode.find('.ix-tree-node-leaf').find('.ix-tree-node-leaf-line').exists()).toBe(true) await wrapper.setProps({ showLine: false }) expect(wrapper.classes()).not.toContain('ix-tree-show-line') expect(leafNode.find('.ix-tree-node-leaf').exists()).toBe(false) }) test('leafLineIcon slot work', async () => { const wrapper = TreeMount({ props: { showLine: true, leafLineIcon: 'up' }, slots: { leafLineIcon: () => 'test', }, }) // 0-0-0 const leafNode = wrapper.findAll('.ix-tree-node')[2] expect(leafNode.find('.ix-tree-node-leaf').find('.ix-icon-up').exists()).toBe(false) expect(leafNode.find('.ix-tree-node-leaf').text()).toBe('test') }) test('loadChildren work', async () => { const loadChildren = (node: TreeNode) => { return new Promise<TreeNode[]>(resolve => { setTimeout(() => { const parentKey = node.key as string const children = [ { label: `Child ${parentKey}-0 `, key: `${parentKey}-0` }, { label: `Child ${parentKey}-1 `, key: `${parentKey}-1` }, ] resolve(children) }, 50) }) } const onUpdateExpandedKeys = jest.fn() const wrapper = TreeMount({ props: { dataSource: [ { key: '0', label: '0' }, { key: '1', label: '1', isLeaf: true }, ], expandedKeys: undefined, checkedKeys: undefined, selectedKeys: undefined, 'onUpdate:expandedKeys': onUpdateExpandedKeys, loadChildren, }, }) const allNodes = wrapper.findAll('.ix-tree-node') expect(allNodes.length).toBe(2) expect(allNodes[0].find('.ix-tree-node-expand').exists()).toBe(true) expect(allNodes[1].find('.ix-tree-node-expand-noop').exists()).toBe(true) await allNodes[0].find('.ix-tree-node-expand').trigger('click') expect(allNodes[0].find('.ix-tree-node-expand').find('.ix-icon-loading').exists()).toBe(true) await wait(50) expect(wrapper.findAll('.ix-tree-node').length).toBe(4) expect(allNodes[0].find('.ix-tree-node-expand').find('.ix-icon-loading').exists()).toBe(false) expect(allNodes[0].find('.ix-tree-node-expand').find('.ix-icon-right').exists()).toBe(true) }) test('loadedKeys work', async () => { const loadChildren = (node: TreeNode) => { return new Promise<TreeNode[]>(resolve => { setTimeout(() => { const parentKey = node.key as string const children = [ { label: `Child ${parentKey}-0 `, key: `${parentKey}-0` }, { label: `Child ${parentKey}-1 `, key: `${parentKey}-1` }, ] resolve(children) }, 50) }) } const wrapper = TreeMount({ props: { dataSource: [ { key: '0', label: '0' }, { key: '1', label: '1', isLeaf: true }, ], expandedKeys: undefined, checkedKeys: undefined, selectedKeys: undefined, loadChildren, loadedKeys: ['0'], }, }) const allNodes = wrapper.findAll('.ix-tree-node') expect(allNodes.length).toBe(2) await allNodes[0].find('.ix-tree-node-expand').trigger('click') expect(allNodes[0].find('.ix-tree-node-expand').find('.ix-icon-loading').exists()).toBe(false) await wait(50) expect(wrapper.findAll('.ix-tree-node').length).toBe(2) await wrapper.setProps({ loadedKeys: [] }) await allNodes[0].find('.ix-tree-node-expand').trigger('click') expect(allNodes[0].find('.ix-tree-node-expand').find('.ix-icon-loading').exists()).toBe(true) await wait(50) expect(wrapper.findAll('.ix-tree-node').length).toBe(4) }) test('nodeKey work', async () => { const wrapper = TreeMount({ props: { nodeKey: 'label' }, }) expect(wrapper.html()).toMatchSnapshot() await wrapper.setProps({ nodeKey: (node: TreeNode) => node.key }) expect(wrapper.html()).toMatchSnapshot() }) test('searchValue work', async () => { const wrapper = TreeMount({ props: { searchValue: 'node' }, }) expect(wrapper.html()).toMatchSnapshot() await wrapper.setProps({ searchValue: '0-0' }) expect(wrapper.html()).toMatchSnapshot() // not match await wrapper.setProps({ searchValue: '0-0-0-0' }) expect(wrapper.html()).toMatchSnapshot() // setValue = '' await wrapper.setProps({ searchValue: '' }) expect(wrapper.html()).toMatchSnapshot() }) test('searchFn work', async () => { const wrapper = TreeMount({ props: { searchValue: 'node', searchFn: (node, searchValue) => { if (searchValue === 'node') { return false } if (searchValue === 'all') { return true } return node.key === '0' }, }, }) expect(wrapper.html()).toMatchSnapshot() await wrapper.setProps({ searchValue: 'all' }) expect(wrapper.html()).toMatchSnapshot() // only math 0 await wrapper.setProps({ searchValue: 'test' }) expect(wrapper.html()).toMatchSnapshot() }) test('focus and blur work', async () => { const focusFn = jest.fn() const blurFn = jest.fn() const wrapper = TreeMount({ props: { onFocus: focusFn, onBlur: blurFn, }, attachTo: 'body', }) await wrapper.vm.focus() expect(focusFn).toBeCalled() await wrapper.vm.blur() expect(blurFn).toBeCalled() }) })
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * LinkedServices * __NOTE__: An instance of this class is automatically created for an * instance of the OperationalInsightsManagementClient. */ export interface LinkedServices { /** * Create or update a linked service. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace that will * contain the linkedServices resource * * @param {string} linkedServiceName Name of the linkedServices resource * * @param {object} parameters The parameters required to create or update a * linked service. * * @param {string} parameters.resourceId The resource id of the resource that * will be linked to the workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LinkedService>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, linkedServiceName: string, parameters: models.LinkedService, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LinkedService>>; /** * Create or update a linked service. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace that will * contain the linkedServices resource * * @param {string} linkedServiceName Name of the linkedServices resource * * @param {object} parameters The parameters required to create or update a * linked service. * * @param {string} parameters.resourceId The resource id of the resource that * will be linked to the workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LinkedService} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {LinkedService} [result] - The deserialized result object if an error did not occur. * See {@link LinkedService} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, workspaceName: string, linkedServiceName: string, parameters: models.LinkedService, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LinkedService>; createOrUpdate(resourceGroupName: string, workspaceName: string, linkedServiceName: string, parameters: models.LinkedService, callback: ServiceCallback<models.LinkedService>): void; createOrUpdate(resourceGroupName: string, workspaceName: string, linkedServiceName: string, parameters: models.LinkedService, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LinkedService>): void; /** * Deletes a linked service instance. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace that * contains the linkedServices resource * * @param {string} linkedServiceName Name of the linked service. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, linkedServiceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes a linked service instance. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace that * contains the linkedServices resource * * @param {string} linkedServiceName Name of the linked service. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, workspaceName: string, linkedServiceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, workspaceName: string, linkedServiceName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, workspaceName: string, linkedServiceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Gets a linked service instance. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace that * contains the linkedServices resource * * @param {string} linkedServiceName Name of the linked service. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LinkedService>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, linkedServiceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LinkedService>>; /** * Gets a linked service instance. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace that * contains the linkedServices resource * * @param {string} linkedServiceName Name of the linked service. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LinkedService} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {LinkedService} [result] - The deserialized result object if an error did not occur. * See {@link LinkedService} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, workspaceName: string, linkedServiceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LinkedService>; get(resourceGroupName: string, workspaceName: string, linkedServiceName: string, callback: ServiceCallback<models.LinkedService>): void; get(resourceGroupName: string, workspaceName: string, linkedServiceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LinkedService>): void; /** * Gets the linked services instances in a workspace. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace that * contains the linked services. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LinkedServiceListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByWorkspaceWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LinkedServiceListResult>>; /** * Gets the linked services instances in a workspace. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace that * contains the linked services. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LinkedServiceListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {LinkedServiceListResult} [result] - The deserialized result object if an error did not occur. * See {@link LinkedServiceListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByWorkspace(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LinkedServiceListResult>; listByWorkspace(resourceGroupName: string, workspaceName: string, callback: ServiceCallback<models.LinkedServiceListResult>): void; listByWorkspace(resourceGroupName: string, workspaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LinkedServiceListResult>): void; } /** * @class * DataSources * __NOTE__: An instance of this class is automatically created for an * instance of the OperationalInsightsManagementClient. */ export interface DataSources { /** * Create or update a data source. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace that will * contain the datasource * * @param {string} dataSourceName The name of the datasource resource. * * @param {object} parameters The parameters required to create or update a * datasource. * * @param {object} parameters.properties The data source properties in raw json * format, each kind of data source have it's own schema. * * @param {string} [parameters.eTag] The ETag of the data source. * * @param {string} parameters.kind Possible values include: 'AzureActivityLog', * 'ChangeTrackingPath', 'ChangeTrackingDefaultPath', * 'ChangeTrackingDefaultRegistry', 'ChangeTrackingCustomRegistry', * 'CustomLog', 'CustomLogCollection', 'GenericDataSource', 'IISLogs', * 'LinuxPerformanceObject', 'LinuxPerformanceCollection', 'LinuxSyslog', * 'LinuxSyslogCollection', 'WindowsEvent', 'WindowsPerformanceCounter' * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DataSource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, dataSourceName: string, parameters: models.DataSource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DataSource>>; /** * Create or update a data source. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace that will * contain the datasource * * @param {string} dataSourceName The name of the datasource resource. * * @param {object} parameters The parameters required to create or update a * datasource. * * @param {object} parameters.properties The data source properties in raw json * format, each kind of data source have it's own schema. * * @param {string} [parameters.eTag] The ETag of the data source. * * @param {string} parameters.kind Possible values include: 'AzureActivityLog', * 'ChangeTrackingPath', 'ChangeTrackingDefaultPath', * 'ChangeTrackingDefaultRegistry', 'ChangeTrackingCustomRegistry', * 'CustomLog', 'CustomLogCollection', 'GenericDataSource', 'IISLogs', * 'LinuxPerformanceObject', 'LinuxPerformanceCollection', 'LinuxSyslog', * 'LinuxSyslogCollection', 'WindowsEvent', 'WindowsPerformanceCounter' * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DataSource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DataSource} [result] - The deserialized result object if an error did not occur. * See {@link DataSource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, workspaceName: string, dataSourceName: string, parameters: models.DataSource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DataSource>; createOrUpdate(resourceGroupName: string, workspaceName: string, dataSourceName: string, parameters: models.DataSource, callback: ServiceCallback<models.DataSource>): void; createOrUpdate(resourceGroupName: string, workspaceName: string, dataSourceName: string, parameters: models.DataSource, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DataSource>): void; /** * Deletes a data source instance. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace that * contains the datasource. * * @param {string} dataSourceName Name of the datasource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, dataSourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes a data source instance. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace that * contains the datasource. * * @param {string} dataSourceName Name of the datasource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, workspaceName: string, dataSourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, workspaceName: string, dataSourceName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, workspaceName: string, dataSourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Gets a datasource instance. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace that * contains the datasource. * * @param {string} dataSourceName Name of the datasource * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DataSource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, dataSourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DataSource>>; /** * Gets a datasource instance. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace that * contains the datasource. * * @param {string} dataSourceName Name of the datasource * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DataSource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DataSource} [result] - The deserialized result object if an error did not occur. * See {@link DataSource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, workspaceName: string, dataSourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DataSource>; get(resourceGroupName: string, workspaceName: string, dataSourceName: string, callback: ServiceCallback<models.DataSource>): void; get(resourceGroupName: string, workspaceName: string, dataSourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DataSource>): void; /** * Gets the first page of data source instances in a workspace with the link to * the next page. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName The workspace that contains the data sources. * * @param {string} filter The filter to apply on the operation. * * @param {object} [options] Optional Parameters. * * @param {string} [options.skiptoken] Starting point of the collection of data * source instances. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DataSourceListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByWorkspaceWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, filter: string, options?: { skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DataSourceListResult>>; /** * Gets the first page of data source instances in a workspace with the link to * the next page. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName The workspace that contains the data sources. * * @param {string} filter The filter to apply on the operation. * * @param {object} [options] Optional Parameters. * * @param {string} [options.skiptoken] Starting point of the collection of data * source instances. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DataSourceListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DataSourceListResult} [result] - The deserialized result object if an error did not occur. * See {@link DataSourceListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByWorkspace(resourceGroupName: string, workspaceName: string, filter: string, options?: { skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.DataSourceListResult>; listByWorkspace(resourceGroupName: string, workspaceName: string, filter: string, callback: ServiceCallback<models.DataSourceListResult>): void; listByWorkspace(resourceGroupName: string, workspaceName: string, filter: string, options: { skiptoken? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DataSourceListResult>): void; /** * Gets the first page of data source instances in a workspace with the link to * the next page. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DataSourceListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByWorkspaceNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DataSourceListResult>>; /** * Gets the first page of data source instances in a workspace with the link to * the next page. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DataSourceListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DataSourceListResult} [result] - The deserialized result object if an error did not occur. * See {@link DataSourceListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByWorkspaceNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DataSourceListResult>; listByWorkspaceNext(nextPageLink: string, callback: ServiceCallback<models.DataSourceListResult>): void; listByWorkspaceNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DataSourceListResult>): void; } /** * @class * Workspaces * __NOTE__: An instance of this class is automatically created for an * instance of the OperationalInsightsManagementClient. */ export interface Workspaces { /** * Disables an intelligence pack for a given workspace. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace. * * @param {string} intelligencePackName The name of the intelligence pack to be * disabled. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ disableIntelligencePackWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, intelligencePackName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Disables an intelligence pack for a given workspace. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace. * * @param {string} intelligencePackName The name of the intelligence pack to be * disabled. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ disableIntelligencePack(resourceGroupName: string, workspaceName: string, intelligencePackName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; disableIntelligencePack(resourceGroupName: string, workspaceName: string, intelligencePackName: string, callback: ServiceCallback<void>): void; disableIntelligencePack(resourceGroupName: string, workspaceName: string, intelligencePackName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Enables an intelligence pack for a given workspace. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace. * * @param {string} intelligencePackName The name of the intelligence pack to be * enabled. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ enableIntelligencePackWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, intelligencePackName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Enables an intelligence pack for a given workspace. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace. * * @param {string} intelligencePackName The name of the intelligence pack to be * enabled. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ enableIntelligencePack(resourceGroupName: string, workspaceName: string, intelligencePackName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; enableIntelligencePack(resourceGroupName: string, workspaceName: string, intelligencePackName: string, callback: ServiceCallback<void>): void; enableIntelligencePack(resourceGroupName: string, workspaceName: string, intelligencePackName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Lists all the intelligence packs possible and whether they are enabled or * disabled for a given workspace. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Array>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listIntelligencePacksWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IntelligencePack[]>>; /** * Lists all the intelligence packs possible and whether they are enabled or * disabled for a given workspace. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Array} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Array} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listIntelligencePacks(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IntelligencePack[]>; listIntelligencePacks(resourceGroupName: string, workspaceName: string, callback: ServiceCallback<models.IntelligencePack[]>): void; listIntelligencePacks(resourceGroupName: string, workspaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IntelligencePack[]>): void; /** * Gets the shared keys for a workspace. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SharedKeys>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getSharedKeysWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SharedKeys>>; /** * Gets the shared keys for a workspace. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName Name of the Log Analytics Workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SharedKeys} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SharedKeys} [result] - The deserialized result object if an error did not occur. * See {@link SharedKeys} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getSharedKeys(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SharedKeys>; getSharedKeys(resourceGroupName: string, workspaceName: string, callback: ServiceCallback<models.SharedKeys>): void; getSharedKeys(resourceGroupName: string, workspaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SharedKeys>): void; /** * Gets a list of usage metrics for a workspace. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName The name of the workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<WorkspaceListUsagesResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listUsagesWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkspaceListUsagesResult>>; /** * Gets a list of usage metrics for a workspace. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName The name of the workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {WorkspaceListUsagesResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {WorkspaceListUsagesResult} [result] - The deserialized result object if an error did not occur. * See {@link WorkspaceListUsagesResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listUsages(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkspaceListUsagesResult>; listUsages(resourceGroupName: string, workspaceName: string, callback: ServiceCallback<models.WorkspaceListUsagesResult>): void; listUsages(resourceGroupName: string, workspaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkspaceListUsagesResult>): void; /** * Gets a list of management groups connected to a workspace. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName The name of the workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<WorkspaceListManagementGroupsResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listManagementGroupsWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkspaceListManagementGroupsResult>>; /** * Gets a list of management groups connected to a workspace. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {string} workspaceName The name of the workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {WorkspaceListManagementGroupsResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {WorkspaceListManagementGroupsResult} [result] - The deserialized result object if an error did not occur. * See {@link WorkspaceListManagementGroupsResult} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listManagementGroups(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkspaceListManagementGroupsResult>; listManagementGroups(resourceGroupName: string, workspaceName: string, callback: ServiceCallback<models.WorkspaceListManagementGroupsResult>): void; listManagementGroups(resourceGroupName: string, workspaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkspaceListManagementGroupsResult>): void; /** * Gets workspaces in a resource group. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<WorkspaceListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkspaceListResult>>; /** * Gets workspaces in a resource group. * * @param {string} resourceGroupName The name of the resource group to get. The * name is case insensitive. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {WorkspaceListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {WorkspaceListResult} [result] - The deserialized result object if an error did not occur. * See {@link WorkspaceListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkspaceListResult>; listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.WorkspaceListResult>): void; listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkspaceListResult>): void; /** * Gets the workspaces in a subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<WorkspaceListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkspaceListResult>>; /** * Gets the workspaces in a subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {WorkspaceListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {WorkspaceListResult} [result] - The deserialized result object if an error did not occur. * See {@link WorkspaceListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkspaceListResult>; list(callback: ServiceCallback<models.WorkspaceListResult>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkspaceListResult>): void; /** * Create or update a workspace. * * @param {string} resourceGroupName The resource group name of the workspace. * * @param {string} workspaceName The name of the workspace. * * @param {object} parameters The parameters required to create or update a * workspace. * * @param {string} [parameters.provisioningState] The provisioning state of the * workspace. Possible values include: 'Creating', 'Succeeded', 'Failed', * 'Canceled', 'Deleting', 'ProvisioningAccount' * * @param {string} [parameters.source] The source of the workspace. Source * defines where the workspace was created. 'Azure' implies it was created in * Azure. 'External' implies it was created via the Operational Insights * Portal. This value is set on the service side and read-only on the client * side. * * @param {string} [parameters.customerId] The ID associated with the * workspace. Setting this value at creation time allows the workspace being * created to be linked to an existing workspace. * * @param {string} [parameters.portalUrl] The URL of the Operational Insights * portal for this workspace. This value is set on the service side and * read-only on the client side. * * @param {object} [parameters.sku] The SKU of the workspace. * * @param {string} parameters.sku.name The name of the SKU. Possible values * include: 'Free', 'Standard', 'Premium', 'Unlimited', 'PerNode', 'PerGB2018', * 'Standalone' * * @param {number} [parameters.retentionInDays] The workspace data retention in * days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the * maximum allowed for all other Skus. * * @param {string} [parameters.eTag] The ETag of the workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Workspace>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, parameters: models.Workspace, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Workspace>>; /** * Create or update a workspace. * * @param {string} resourceGroupName The resource group name of the workspace. * * @param {string} workspaceName The name of the workspace. * * @param {object} parameters The parameters required to create or update a * workspace. * * @param {string} [parameters.provisioningState] The provisioning state of the * workspace. Possible values include: 'Creating', 'Succeeded', 'Failed', * 'Canceled', 'Deleting', 'ProvisioningAccount' * * @param {string} [parameters.source] The source of the workspace. Source * defines where the workspace was created. 'Azure' implies it was created in * Azure. 'External' implies it was created via the Operational Insights * Portal. This value is set on the service side and read-only on the client * side. * * @param {string} [parameters.customerId] The ID associated with the * workspace. Setting this value at creation time allows the workspace being * created to be linked to an existing workspace. * * @param {string} [parameters.portalUrl] The URL of the Operational Insights * portal for this workspace. This value is set on the service side and * read-only on the client side. * * @param {object} [parameters.sku] The SKU of the workspace. * * @param {string} parameters.sku.name The name of the SKU. Possible values * include: 'Free', 'Standard', 'Premium', 'Unlimited', 'PerNode', 'PerGB2018', * 'Standalone' * * @param {number} [parameters.retentionInDays] The workspace data retention in * days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the * maximum allowed for all other Skus. * * @param {string} [parameters.eTag] The ETag of the workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Workspace} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Workspace} [result] - The deserialized result object if an error did not occur. * See {@link Workspace} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, workspaceName: string, parameters: models.Workspace, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Workspace>; createOrUpdate(resourceGroupName: string, workspaceName: string, parameters: models.Workspace, callback: ServiceCallback<models.Workspace>): void; createOrUpdate(resourceGroupName: string, workspaceName: string, parameters: models.Workspace, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Workspace>): void; /** * Deletes a workspace instance. * * @param {string} resourceGroupName The resource group name of the workspace. * * @param {string} workspaceName Name of the Log Analytics Workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes a workspace instance. * * @param {string} resourceGroupName The resource group name of the workspace. * * @param {string} workspaceName Name of the Log Analytics Workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, workspaceName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, workspaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Gets a workspace instance. * * @param {string} resourceGroupName The resource group name of the workspace. * * @param {string} workspaceName Name of the Log Analytics Workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Workspace>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Workspace>>; /** * Gets a workspace instance. * * @param {string} resourceGroupName The resource group name of the workspace. * * @param {string} workspaceName Name of the Log Analytics Workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Workspace} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Workspace} [result] - The deserialized result object if an error did not occur. * See {@link Workspace} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Workspace>; get(resourceGroupName: string, workspaceName: string, callback: ServiceCallback<models.Workspace>): void; get(resourceGroupName: string, workspaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Workspace>): void; /** * Updates a workspace. * * @param {string} resourceGroupName The resource group name of the workspace. * * @param {string} workspaceName The name of the workspace. * * @param {object} parameters The parameters required to patch a workspace. * * @param {string} [parameters.provisioningState] The provisioning state of the * workspace. Possible values include: 'Creating', 'Succeeded', 'Failed', * 'Canceled', 'Deleting', 'ProvisioningAccount' * * @param {string} [parameters.source] The source of the workspace. Source * defines where the workspace was created. 'Azure' implies it was created in * Azure. 'External' implies it was created via the Operational Insights * Portal. This value is set on the service side and read-only on the client * side. * * @param {string} [parameters.customerId] The ID associated with the * workspace. Setting this value at creation time allows the workspace being * created to be linked to an existing workspace. * * @param {string} [parameters.portalUrl] The URL of the Operational Insights * portal for this workspace. This value is set on the service side and * read-only on the client side. * * @param {object} [parameters.sku] The SKU of the workspace. * * @param {string} parameters.sku.name The name of the SKU. Possible values * include: 'Free', 'Standard', 'Premium', 'Unlimited', 'PerNode', 'PerGB2018', * 'Standalone' * * @param {number} [parameters.retentionInDays] The workspace data retention in * days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the * maximum allowed for all other Skus. * * @param {string} [parameters.eTag] The ETag of the workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Workspace>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, parameters: models.Workspace, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Workspace>>; /** * Updates a workspace. * * @param {string} resourceGroupName The resource group name of the workspace. * * @param {string} workspaceName The name of the workspace. * * @param {object} parameters The parameters required to patch a workspace. * * @param {string} [parameters.provisioningState] The provisioning state of the * workspace. Possible values include: 'Creating', 'Succeeded', 'Failed', * 'Canceled', 'Deleting', 'ProvisioningAccount' * * @param {string} [parameters.source] The source of the workspace. Source * defines where the workspace was created. 'Azure' implies it was created in * Azure. 'External' implies it was created via the Operational Insights * Portal. This value is set on the service side and read-only on the client * side. * * @param {string} [parameters.customerId] The ID associated with the * workspace. Setting this value at creation time allows the workspace being * created to be linked to an existing workspace. * * @param {string} [parameters.portalUrl] The URL of the Operational Insights * portal for this workspace. This value is set on the service side and * read-only on the client side. * * @param {object} [parameters.sku] The SKU of the workspace. * * @param {string} parameters.sku.name The name of the SKU. Possible values * include: 'Free', 'Standard', 'Premium', 'Unlimited', 'PerNode', 'PerGB2018', * 'Standalone' * * @param {number} [parameters.retentionInDays] The workspace data retention in * days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the * maximum allowed for all other Skus. * * @param {string} [parameters.eTag] The ETag of the workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Workspace} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Workspace} [result] - The deserialized result object if an error did not occur. * See {@link Workspace} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName: string, workspaceName: string, parameters: models.Workspace, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Workspace>; update(resourceGroupName: string, workspaceName: string, parameters: models.Workspace, callback: ServiceCallback<models.Workspace>): void; update(resourceGroupName: string, workspaceName: string, parameters: models.Workspace, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Workspace>): void; /** * Create or update a workspace. * * @param {string} resourceGroupName The resource group name of the workspace. * * @param {string} workspaceName The name of the workspace. * * @param {object} parameters The parameters required to create or update a * workspace. * * @param {string} [parameters.provisioningState] The provisioning state of the * workspace. Possible values include: 'Creating', 'Succeeded', 'Failed', * 'Canceled', 'Deleting', 'ProvisioningAccount' * * @param {string} [parameters.source] The source of the workspace. Source * defines where the workspace was created. 'Azure' implies it was created in * Azure. 'External' implies it was created via the Operational Insights * Portal. This value is set on the service side and read-only on the client * side. * * @param {string} [parameters.customerId] The ID associated with the * workspace. Setting this value at creation time allows the workspace being * created to be linked to an existing workspace. * * @param {string} [parameters.portalUrl] The URL of the Operational Insights * portal for this workspace. This value is set on the service side and * read-only on the client side. * * @param {object} [parameters.sku] The SKU of the workspace. * * @param {string} parameters.sku.name The name of the SKU. Possible values * include: 'Free', 'Standard', 'Premium', 'Unlimited', 'PerNode', 'PerGB2018', * 'Standalone' * * @param {number} [parameters.retentionInDays] The workspace data retention in * days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the * maximum allowed for all other Skus. * * @param {string} [parameters.eTag] The ETag of the workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Workspace>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateOrUpdateWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, parameters: models.Workspace, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Workspace>>; /** * Create or update a workspace. * * @param {string} resourceGroupName The resource group name of the workspace. * * @param {string} workspaceName The name of the workspace. * * @param {object} parameters The parameters required to create or update a * workspace. * * @param {string} [parameters.provisioningState] The provisioning state of the * workspace. Possible values include: 'Creating', 'Succeeded', 'Failed', * 'Canceled', 'Deleting', 'ProvisioningAccount' * * @param {string} [parameters.source] The source of the workspace. Source * defines where the workspace was created. 'Azure' implies it was created in * Azure. 'External' implies it was created via the Operational Insights * Portal. This value is set on the service side and read-only on the client * side. * * @param {string} [parameters.customerId] The ID associated with the * workspace. Setting this value at creation time allows the workspace being * created to be linked to an existing workspace. * * @param {string} [parameters.portalUrl] The URL of the Operational Insights * portal for this workspace. This value is set on the service side and * read-only on the client side. * * @param {object} [parameters.sku] The SKU of the workspace. * * @param {string} parameters.sku.name The name of the SKU. Possible values * include: 'Free', 'Standard', 'Premium', 'Unlimited', 'PerNode', 'PerGB2018', * 'Standalone' * * @param {number} [parameters.retentionInDays] The workspace data retention in * days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the * maximum allowed for all other Skus. * * @param {string} [parameters.eTag] The ETag of the workspace. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Workspace} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Workspace} [result] - The deserialized result object if an error did not occur. * See {@link Workspace} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCreateOrUpdate(resourceGroupName: string, workspaceName: string, parameters: models.Workspace, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Workspace>; beginCreateOrUpdate(resourceGroupName: string, workspaceName: string, parameters: models.Workspace, callback: ServiceCallback<models.Workspace>): void; beginCreateOrUpdate(resourceGroupName: string, workspaceName: string, parameters: models.Workspace, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Workspace>): void; } /** * @class * Operations * __NOTE__: An instance of this class is automatically created for an * instance of the OperationalInsightsManagementClient. */ export interface Operations { /** * Lists all of the available OperationalInsights Rest API operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>; /** * Lists all of the available OperationalInsights Rest API operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>; list(callback: ServiceCallback<models.OperationListResult>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void; /** * Lists all of the available OperationalInsights Rest API operations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>; /** * Lists all of the available OperationalInsights Rest API operations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.OperationListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void; }
the_stack
import { v4 as uuidV4 } from 'uuid' import { mocked } from 'ts-jest/utils' import adapterFactory, { SubscriptionAdapter, } from '../../src/subscribe-adapter' import { subscriptionAdapterAlreadyInitialized, subscriptionAdapterClosed, subscriptionAdapterNotInitialized, } from '../../src/subscribe-adapter-constants' import { SubscriptionAdapterStatus } from '../../src/types' jest.mock('uuid', () => ({ v4: jest.fn(), })) let ws: { readyState: number onopen: Function onmessage: Function send: jest.Mock close: jest.Mock } let uuidV4Mock = mocked(uuidV4) beforeAll(() => { ws = { readyState: 0, onopen: jest.fn(), onmessage: jest.fn(), send: jest.fn(), close: jest.fn(), } const browserGlobal = global as any browserGlobal.WebSocket = jest.fn(() => ws) as any }) let adapter: SubscriptionAdapter let onEvent: jest.Mock beforeEach(() => { onEvent = jest.fn() adapter = adapterFactory({ url: 'url', cursor: 'A', onEvent, }) }) afterEach(() => { uuidV4Mock.mockRestore() onEvent.mockRestore() ws.send.mockRestore() ws.close.mockRestore() }) describe('construction', () => { test('status "initializing" after creation', () => { expect(adapter.status()).toEqual(SubscriptionAdapterStatus.Initializing) }) }) describe('init', () => { afterEach(() => { try { adapter.close() } catch (e) { // empty } }) test('status "connecting" after init', () => { adapter.init() expect(adapter.status()).toEqual(SubscriptionAdapterStatus.Connecting) }) test('status "connected" after connection opened', () => { adapter.init() ws.onopen() expect(adapter.status()).toEqual(SubscriptionAdapterStatus.Connected) }) test('status "ready" if connected and underlying connection ready', () => { adapter.init() ws.onopen() ws.readyState = 1 expect(adapter.status()).toEqual(SubscriptionAdapterStatus.Ready) }) test('error if adapter already in "connecting" status', () => { adapter.init() expect(adapter.init).toThrow(subscriptionAdapterAlreadyInitialized) }) test('error if adapter already in "connected" status', () => { adapter.init() ws.onopen() expect(adapter.init).toThrow(subscriptionAdapterAlreadyInitialized) }) test('error if adapter closed (disposed)', () => { adapter.init() ws.onopen() adapter.close() expect(adapter.init).toThrow(subscriptionAdapterClosed) }) }) describe('messaging', () => { let originalConsoleWarn: typeof console.warn beforeEach(() => { jest.useFakeTimers() // eslint-disable-next-line no-console originalConsoleWarn = console.warn // eslint-disable-next-line no-console console.warn = jest.fn() }) afterEach(() => { adapter.close() jest.clearAllTimers() // eslint-disable-next-line no-console console.warn = originalConsoleWarn }) const events = [ { threadCounter: 0, threadId: 0, type: 'ItemUpdated', timestamp: 1, aggregateId: 'test-aggregate', aggregateVersion: 0, payload: { isUpdated: true, }, }, { threadCounter: 1, threadId: 0, type: 'ItemUpdated', timestamp: 2, aggregateId: 'test-aggregate', aggregateVersion: 1, payload: { isUpdated: true, }, }, ] test('sends "pullEvents" message on connection open', () => { uuidV4Mock.mockReturnValueOnce('request-id-1') adapter.init() ws.onopen() expect(ws.send).toBeCalledWith( JSON.stringify({ type: 'pullEvents', requestId: 'request-id-1', payload: { cursor: 'A', }, }) ) }) test('calls onEvent with pulled events', () => { uuidV4Mock.mockReturnValueOnce('request-id-1') adapter.init() ws.onopen() ws.onmessage({ data: JSON.stringify({ type: 'pullEvents', requestId: 'request-id-1', payload: { cursor: 'B', events, }, }), }) expect(onEvent).toBeCalledWith(events[0]) expect(onEvent).toBeCalledWith(events[1]) }) test('pulls event on event message with new cursor', () => { uuidV4Mock .mockReturnValueOnce('request-id-1') .mockReturnValueOnce('request-id-2') adapter.init() ws.onopen() ws.onmessage({ data: JSON.stringify({ type: 'pullEvents', requestId: 'request-id-1', payload: { cursor: 'B', events: [events[0]], }, }), }) ws.onmessage({ data: JSON.stringify({ type: 'events', payload: { events: [events[1]], }, }), }) expect(ws.send).toBeCalledWith( JSON.stringify({ type: 'pullEvents', requestId: 'request-id-2', payload: { cursor: 'B', }, }) ) }) test('pulls events exactly once on ws connection', () => { uuidV4Mock.mockReturnValueOnce('request-id-1') adapter.init() ws.onopen() ws.onmessage({ data: JSON.stringify({ type: 'events', payload: { events: [events[0]], }, }), }) ws.onmessage({ data: JSON.stringify({ type: 'events', payload: { events: [events[1]], }, }), }) expect(ws.send).toBeCalledTimes(1) }) test('pulls events exactly once due to ordinary work', () => { uuidV4Mock .mockReturnValueOnce('request-id-1') .mockReturnValueOnce('request-id-2') adapter.init() ws.onopen() ws.onmessage({ data: JSON.stringify({ type: 'pullEvents', requestId: 'request-id-1', payload: { cursor: 'B', events: [], }, }), }) ws.onmessage({ data: JSON.stringify({ type: 'events', payload: { events: [events[0]], }, }), }) ws.onmessage({ data: JSON.stringify({ type: 'events', payload: { events: [events[1]], }, }), }) expect(ws.send).toBeCalledTimes(2) }) test('waits for pullEvents message by requestId', () => { uuidV4Mock .mockReturnValueOnce('request-id-1') .mockReturnValueOnce('request-id-2') adapter.init() ws.onopen() ws.onmessage({ data: JSON.stringify({ type: 'pullEvents', requestId: 'request-id-5', payload: { cursor: 'B', events, }, }), }) expect(onEvent).toBeCalledTimes(0) }) test('pulls events again after initial request is timed out', () => { uuidV4Mock .mockReturnValueOnce('request-id-1') .mockReturnValueOnce('request-id-2') adapter.init() ws.onopen() expect(ws.send).toBeCalledTimes(1) jest.advanceTimersByTime(30000) expect(ws.send).toBeCalledTimes(2) expect(ws.send).toBeCalledWith( JSON.stringify({ type: 'pullEvents', requestId: 'request-id-2', payload: { cursor: 'A', }, }) ) }) test('pulls events again after request is timed out', () => { uuidV4Mock .mockReturnValueOnce('request-id-1') .mockReturnValueOnce('request-id-2') .mockReturnValueOnce('request-id-3') adapter.init() ws.onopen() ws.onmessage({ data: JSON.stringify({ type: 'pullEvents', requestId: 'request-id-1', payload: { cursor: 'B', events: [], }, }), }) ws.onmessage({ data: JSON.stringify({ type: 'events', payload: { events: [events[0]], }, }), }) expect(ws.send).toBeCalledTimes(2) jest.advanceTimersByTime(30000) expect(ws.send).toBeCalledTimes(3) expect(ws.send).toBeCalledWith( JSON.stringify({ type: 'pullEvents', requestId: 'request-id-3', payload: { cursor: 'B', }, }) ) }) test('pulls events at most 10 times', () => { uuidV4Mock.mockReturnValue('request-id') adapter.init() ws.onopen() jest.advanceTimersByTime(10000000) expect(ws.send).toBeCalledTimes(10) // eslint-disable-next-line no-console expect(console.warn).toBeCalledWith( 'WebSocket pullEvents max attempts reached out' ) }) test('pulls events again if some event are delivered while previous pulling', () => { uuidV4Mock .mockReturnValueOnce('request-id-1') .mockReturnValueOnce('request-id-2') .mockReturnValueOnce('request-id-3') adapter.init() ws.onopen() ws.onmessage({ data: JSON.stringify({ type: 'pullEvents', requestId: 'request-id-1', payload: { cursor: 'B', events: [], }, }), }) ws.onmessage({ data: JSON.stringify({ type: 'events', payload: { events: [events[0]], }, }), }) ws.onmessage({ data: JSON.stringify({ type: 'events', payload: { events: [events[1]], }, }), }) ws.onmessage({ data: JSON.stringify({ type: 'pullEvents', requestId: 'request-id-2', payload: { cursor: 'C', events: [events[0]], }, }), }) expect(ws.send).toBeCalledTimes(3) expect(ws.send).toBeCalledWith( JSON.stringify({ type: 'pullEvents', requestId: 'request-id-3', payload: { cursor: 'C', }, }) ) }) test('does not pull events infinitely if new events are not delivered', () => { uuidV4Mock .mockReturnValueOnce('request-id-1') .mockReturnValueOnce('request-id-2') .mockReturnValueOnce('request-id-3') adapter.init() ws.onopen() ws.onmessage({ data: JSON.stringify({ type: 'pullEvents', requestId: 'request-id-1', payload: { cursor: 'B', events: [], }, }), }) ws.onmessage({ data: JSON.stringify({ type: 'events', payload: { events: [events[0]], }, }), }) ws.onmessage({ data: JSON.stringify({ type: 'events', payload: { events: [events[1]], }, }), }) ws.onmessage({ data: JSON.stringify({ type: 'pullEvents', requestId: 'request-id-2', payload: { cursor: 'C', events: [events[0]], }, }), }) ws.onmessage({ data: JSON.stringify({ type: 'pullEvents', requestId: 'request-id-3', payload: { cursor: 'D', events: [], }, }), }) expect(ws.send).toBeCalledTimes(3) }) }) describe('close', () => { test('status "closed" after closing connecting adapter', () => { adapter.init() adapter.close() expect(adapter.status()).toEqual(SubscriptionAdapterStatus.Closed) }) test('status "closed" after closing connected adapter', () => { adapter.init() ws.onopen() adapter.close() expect(adapter.status()).toEqual(SubscriptionAdapterStatus.Closed) }) test('error if adapter not initialized', () => { expect(adapter.close).toThrow(subscriptionAdapterNotInitialized) }) test('error if adapter already closed', () => { expect(adapter.close).toThrow(subscriptionAdapterNotInitialized) }) test('status "closed" after closing connected adapter', () => { adapter.init() ws.onopen() adapter.close() expect(adapter.close).toThrow(subscriptionAdapterNotInitialized) }) })
the_stack
import options from '../../util/options'; import Settings from '../../Settings'; import Math from '../../common/Math'; import Vec2 from '../../common/Vec2'; import Rot from '../../common/Rot'; import Joint, { JointOpt, JointDef } from '../Joint'; import Body from '../Body'; import { TimeStep } from "../Solver"; /** * Wheel joint definition. This requires defining a line of motion using an axis * and an anchor point. The definition uses local anchor points and a local axis * so that the initial configuration can violate the constraint slightly. The * joint translation is zero when the local anchor points coincide in world * space. Using local anchors and a local axis helps when saving and loading a * game. */ export interface WheelJointOpt extends JointOpt { /** * Enable/disable the joint motor. */ enableMotor?: boolean; /** * The maximum motor torque, usually in N-m. */ maxMotorTorque?: number; /** * The desired motor speed in radians per second. */ motorSpeed?: number; /** * Suspension frequency, zero indicates no suspension. */ frequencyHz?: number; /** * Suspension damping ratio, one indicates critical damping. */ dampingRatio?: number; } /** * Wheel joint definition. This requires defining a line of motion using an axis * and an anchor point. The definition uses local anchor points and a local axis * so that the initial configuration can violate the constraint slightly. The * joint translation is zero when the local anchor points coincide in world * space. Using local anchors and a local axis helps when saving and loading a * game. */ export interface WheelJointDef extends JointDef, WheelJointOpt { /** * The local anchor point relative to bodyA's origin. */ localAnchorA: Vec2; /** * The local anchor point relative to bodyB's origin. */ localAnchorB: Vec2; /** * The local translation axis in bodyA. */ localAxisA: Vec2; } const DEFAULTS = { enableMotor : false, maxMotorTorque : 0.0, motorSpeed : 0.0, frequencyHz : 2.0, dampingRatio : 0.7, }; /** * A wheel joint. This joint provides two degrees of freedom: translation along * an axis fixed in bodyA and rotation in the plane. In other words, it is a * point to line constraint with a rotational motor and a linear spring/damper. * This joint is designed for vehicle suspensions. */ export default class WheelJoint extends Joint { static TYPE: 'wheel-joint' = 'wheel-joint'; /** @internal */ m_type: 'wheel-joint'; /** @internal */ m_localAnchorA: Vec2; /** @internal */ m_localAnchorB: Vec2; /** @internal */ m_localXAxisA: Vec2; /** @internal */ m_localYAxisA: Vec2; /** @internal */ m_mass: number; /** @internal */ m_impulse: number; /** @internal */ m_motorMass: number; /** @internal */ m_motorImpulse: number; /** @internal */ m_springMass: number; /** @internal */ m_springImpulse: number; /** @internal */ m_maxMotorTorque: number; /** @internal */ m_motorSpeed: number; /** @internal */ m_enableMotor: boolean; /** @internal */ m_frequencyHz: number; /** @internal */ m_dampingRatio: number; /** @internal */ m_bias: number; /** @internal */ m_gamma: number; // Solver temp /** @internal */ m_localCenterA: Vec2; /** @internal */ m_localCenterB: Vec2; /** @internal */ m_invMassA: number; /** @internal */ m_invMassB: number; /** @internal */ m_invIA: number; /** @internal */ m_invIB: number; /** @internal */ m_ax: Vec2 = Vec2.zero(); /** @internal */ m_ay: Vec2 = Vec2.zero(); /** @internal */ m_sAx: number; /** @internal */ m_sBx: number; /** @internal */ m_sAy: number; /** @internal */ m_sBy: number; constructor(def: WheelJointDef); constructor(def: WheelJointOpt, bodyA: Body, bodyB: Body, anchor: Vec2, axis: Vec2); // @ts-ignore constructor(def: WheelJointDef, bodyA?: Body, bodyB?: Body, anchor?: Vec2, axis?: Vec2) { // @ts-ignore if (!(this instanceof WheelJoint)) { return new WheelJoint(def, bodyA, bodyB, anchor, axis); } def = options(def, DEFAULTS); super(def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = WheelJoint.TYPE; this.m_localAnchorA = Vec2.clone(anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero()); this.m_localAnchorB = Vec2.clone(anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero()); // @ts-ignore localAxis this.m_localXAxisA = Vec2.clone(axis ? bodyA.getLocalVector(axis) : def.localAxisA || def.localAxis || Vec2.neo(1.0, 0.0)); this.m_localYAxisA = Vec2.cross(1.0, this.m_localXAxisA); this.m_mass = 0.0; this.m_impulse = 0.0; this.m_motorMass = 0.0; this.m_motorImpulse = 0.0; this.m_springMass = 0.0; this.m_springImpulse = 0.0; this.m_maxMotorTorque = def.maxMotorTorque; this.m_motorSpeed = def.motorSpeed; this.m_enableMotor = def.enableMotor; this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_bias = 0.0; this.m_gamma = 0.0; // Linear constraint (point-to-line) // d = pB - pA = xB + rB - xA - rA // C = dot(ay, d) // Cdot = dot(d, cross(wA, ay)) + dot(ay, vB + cross(wB, rB) - vA - cross(wA, // rA)) // = -dot(ay, vA) - dot(cross(d + rA, ay), wA) + dot(ay, vB) + dot(cross(rB, // ay), vB) // J = [-ay, -cross(d + rA, ay), ay, cross(rB, ay)] // Spring linear constraint // C = dot(ax, d) // Cdot = = -dot(ax, vA) - dot(cross(d + rA, ax), wA) + dot(ax, vB) + // dot(cross(rB, ax), vB) // J = [-ax -cross(d+rA, ax) ax cross(rB, ax)] // Motor rotational constraint // Cdot = wB - wA // J = [0 0 -1 0 0 1] } /** @internal */ _serialize(): object { return { type: this.m_type, bodyA: this.m_bodyA, bodyB: this.m_bodyB, collideConnected: this.m_collideConnected, enableMotor: this.m_enableMotor, maxMotorTorque: this.m_maxMotorTorque, motorSpeed: this.m_motorSpeed, frequencyHz: this.m_frequencyHz, dampingRatio: this.m_dampingRatio, localAnchorA: this.m_localAnchorA, localAnchorB: this.m_localAnchorB, localAxisA: this.m_localXAxisA, }; } /** @internal */ static _deserialize(data: any, world: any, restore: any): WheelJoint { data = {...data}; data.bodyA = restore(Body, data.bodyA, world); data.bodyB = restore(Body, data.bodyB, world); const joint = new WheelJoint(data); return joint; } /** @internal */ _setAnchors(def: { anchorA?: Vec2, localAnchorA?: Vec2, anchorB?: Vec2, localAnchorB?: Vec2, localAxisA?: Vec2, }): void { if (def.anchorA) { this.m_localAnchorA.set(this.m_bodyA.getLocalPoint(def.anchorA)); } else if (def.localAnchorA) { this.m_localAnchorA.set(def.localAnchorA); } if (def.anchorB) { this.m_localAnchorB.set(this.m_bodyB.getLocalPoint(def.anchorB)); } else if (def.localAnchorB) { this.m_localAnchorB.set(def.localAnchorB); } if (def.localAxisA) { this.m_localXAxisA.set(def.localAxisA); this.m_localYAxisA.set(Vec2.cross(1.0, def.localAxisA)); } } /** * The local anchor point relative to bodyA's origin. */ getLocalAnchorA(): Vec2 { return this.m_localAnchorA; } /** * The local anchor point relative to bodyB's origin. */ getLocalAnchorB(): Vec2 { return this.m_localAnchorB; } /** * The local joint axis relative to bodyA. */ getLocalAxisA(): Vec2 { return this.m_localXAxisA; } /** * Get the current joint translation, usually in meters. */ getJointTranslation(): number { const bA = this.m_bodyA; const bB = this.m_bodyB; const pA = bA.getWorldPoint(this.m_localAnchorA); // Vec2 const pB = bB.getWorldPoint(this.m_localAnchorB); // Vec2 const d = Vec2.sub(pB, pA); // Vec2 const axis = bA.getWorldVector(this.m_localXAxisA); // Vec2 const translation = Vec2.dot(d, axis); // float return translation; } /** * Get the current joint translation speed, usually in meters per second. */ getJointSpeed(): number { const wA = this.m_bodyA.m_angularVelocity; const wB = this.m_bodyB.m_angularVelocity; return wB - wA; } /** * Is the joint motor enabled? */ isMotorEnabled(): boolean { return this.m_enableMotor; } /** * Enable/disable the joint motor. */ enableMotor(flag: boolean): void { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableMotor = flag; } /** * Set the motor speed, usually in radians per second. */ setMotorSpeed(speed: number): void { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_motorSpeed = speed; } /** * Get the motor speed, usually in radians per second. */ getMotorSpeed(): number { return this.m_motorSpeed; } /** * Set/Get the maximum motor force, usually in N-m. */ setMaxMotorTorque(torque: number): void { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_maxMotorTorque = torque; } getMaxMotorTorque(): number { return this.m_maxMotorTorque; } /** * Get the current motor torque given the inverse time step, usually in N-m. */ getMotorTorque(inv_dt: number): number { return inv_dt * this.m_motorImpulse; } /** * Set/Get the spring frequency in hertz. Setting the frequency to zero disables * the spring. */ setSpringFrequencyHz(hz: number): void { this.m_frequencyHz = hz; } getSpringFrequencyHz(): number { return this.m_frequencyHz; } /** * Set/Get the spring damping ratio */ setSpringDampingRatio(ratio: number): void { this.m_dampingRatio = ratio; } getSpringDampingRatio(): number { return this.m_dampingRatio; } /** * Get the anchor point on bodyA in world coordinates. */ getAnchorA(): Vec2 { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); } /** * Get the anchor point on bodyB in world coordinates. */ getAnchorB(): Vec2 { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); } /** * Get the reaction force on bodyB at the joint anchor in Newtons. */ getReactionForce(inv_dt: number): Vec2 { return Vec2.combine(this.m_impulse, this.m_ay, this.m_springImpulse, this.m_ax).mul(inv_dt); } /** * Get the reaction torque on bodyB in N*m. */ getReactionTorque(inv_dt: number): number { return inv_dt * this.m_motorImpulse; } initVelocityConstraints(step: TimeStep): void { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; const mA = this.m_invMassA; const mB = this.m_invMassB; // float const iA = this.m_invIA; const iB = this.m_invIB; // float const cA = this.m_bodyA.c_position.c; const aA = this.m_bodyA.c_position.a; const vA = this.m_bodyA.c_velocity.v; let wA = this.m_bodyA.c_velocity.w; const cB = this.m_bodyB.c_position.c; const aB = this.m_bodyB.c_position.a; const vB = this.m_bodyB.c_velocity.v; let wB = this.m_bodyB.c_velocity.w; const qA = Rot.neo(aA); const qB = Rot.neo(aB); // Compute the effective masses. const rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); const rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); const d = Vec2.zero(); d.addCombine(1, cB, 1, rB); d.subCombine(1, cA, 1, rA); // Vec2 // Point to line constraint { this.m_ay = Rot.mulVec2(qA, this.m_localYAxisA); this.m_sAy = Vec2.cross(Vec2.add(d, rA), this.m_ay); this.m_sBy = Vec2.cross(rB, this.m_ay); this.m_mass = mA + mB + iA * this.m_sAy * this.m_sAy + iB * this.m_sBy * this.m_sBy; if (this.m_mass > 0.0) { this.m_mass = 1.0 / this.m_mass; } } // Spring constraint this.m_springMass = 0.0; this.m_bias = 0.0; this.m_gamma = 0.0; if (this.m_frequencyHz > 0.0) { this.m_ax = Rot.mulVec2(qA, this.m_localXAxisA); this.m_sAx = Vec2.cross(Vec2.add(d, rA), this.m_ax); this.m_sBx = Vec2.cross(rB, this.m_ax); const invMass = mA + mB + iA * this.m_sAx * this.m_sAx + iB * this.m_sBx * this.m_sBx; // float if (invMass > 0.0) { this.m_springMass = 1.0 / invMass; const C = Vec2.dot(d, this.m_ax); // float // Frequency const omega = 2.0 * Math.PI * this.m_frequencyHz; // float // Damping coefficient const damp = 2.0 * this.m_springMass * this.m_dampingRatio * omega; // float // Spring stiffness const k = this.m_springMass * omega * omega; // float // magic formulas const h = step.dt; // float this.m_gamma = h * (damp + h * k); if (this.m_gamma > 0.0) { this.m_gamma = 1.0 / this.m_gamma; } this.m_bias = C * h * k * this.m_gamma; this.m_springMass = invMass + this.m_gamma; if (this.m_springMass > 0.0) { this.m_springMass = 1.0 / this.m_springMass; } } } else { this.m_springImpulse = 0.0; } // Rotational motor if (this.m_enableMotor) { this.m_motorMass = iA + iB; if (this.m_motorMass > 0.0) { this.m_motorMass = 1.0 / this.m_motorMass; } } else { this.m_motorMass = 0.0; this.m_motorImpulse = 0.0; } if (step.warmStarting) { // Account for variable time step. this.m_impulse *= step.dtRatio; this.m_springImpulse *= step.dtRatio; this.m_motorImpulse *= step.dtRatio; const P = Vec2.combine(this.m_impulse, this.m_ay, this.m_springImpulse, this.m_ax); const LA = this.m_impulse * this.m_sAy + this.m_springImpulse * this.m_sAx + this.m_motorImpulse; const LB = this.m_impulse * this.m_sBy + this.m_springImpulse * this.m_sBx + this.m_motorImpulse; vA.subMul(this.m_invMassA, P); wA -= this.m_invIA * LA; vB.addMul(this.m_invMassB, P); wB += this.m_invIB * LB; } else { this.m_impulse = 0.0; this.m_springImpulse = 0.0; this.m_motorImpulse = 0.0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; } solveVelocityConstraints(step: TimeStep): void { const mA = this.m_invMassA; const mB = this.m_invMassB; // float const iA = this.m_invIA; const iB = this.m_invIB; // float const vA = this.m_bodyA.c_velocity.v; let wA = this.m_bodyA.c_velocity.w; const vB = this.m_bodyB.c_velocity.v; let wB = this.m_bodyB.c_velocity.w; // Solve spring constraint { const Cdot = Vec2.dot(this.m_ax, vB) - Vec2.dot(this.m_ax, vA) + this.m_sBx * wB - this.m_sAx * wA; // float const impulse = -this.m_springMass * (Cdot + this.m_bias + this.m_gamma * this.m_springImpulse); // float this.m_springImpulse += impulse; const P = Vec2.mul(impulse, this.m_ax); // Vec2 const LA = impulse * this.m_sAx; // float const LB = impulse * this.m_sBx; // float vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } // Solve rotational motor constraint { const Cdot = wB - wA - this.m_motorSpeed; // float let impulse = -this.m_motorMass * Cdot; // float const oldImpulse = this.m_motorImpulse; // float const maxImpulse = step.dt * this.m_maxMotorTorque; // float this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // Solve point to line constraint { const Cdot = Vec2.dot(this.m_ay, vB) - Vec2.dot(this.m_ay, vA) + this.m_sBy * wB - this.m_sAy * wA; // float const impulse = -this.m_mass * Cdot; // float this.m_impulse += impulse; const P = Vec2.mul(impulse, this.m_ay); // Vec2 const LA = impulse * this.m_sAy; // float const LB = impulse * this.m_sBy; // float vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; } /** * This returns true if the position errors are within tolerance. */ solvePositionConstraints(step: TimeStep): boolean { const cA = this.m_bodyA.c_position.c; let aA = this.m_bodyA.c_position.a; const cB = this.m_bodyB.c_position.c; let aB = this.m_bodyB.c_position.a; const qA = Rot.neo(aA); const qB = Rot.neo(aB); const rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); const rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); const d = Vec2.zero(); d.addCombine(1, cB, 1, rB); d.subCombine(1, cA, 1, rA); const ay = Rot.mulVec2(qA, this.m_localYAxisA); const sAy = Vec2.cross(Vec2.add(d, rA), ay); // float const sBy = Vec2.cross(rB, ay); // float const C = Vec2.dot(d, ay); // float const k = this.m_invMassA + this.m_invMassB + this.m_invIA * this.m_sAy * this.m_sAy + this.m_invIB * this.m_sBy * this.m_sBy; // float let impulse; // float if (k != 0.0) { impulse = -C / k; } else { impulse = 0.0; } const P = Vec2.mul(impulse, ay); // Vec2 const LA = impulse * sAy; // float const LB = impulse * sBy; // float cA.subMul(this.m_invMassA, P); aA -= this.m_invIA * LA; cB.addMul(this.m_invMassB, P); aB += this.m_invIB * LB; this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return Math.abs(C) <= Settings.linearSlop; } }
the_stack
import { ClassType, GenericsType, EnumType, InterfaceType } from "./AstTypes"; import { Expression } from "./Expressions"; import { ClassReference, EnumReference, ThisReference, MethodParameterReference, SuperReference, StaticFieldReference, EnumMemberReference, InstanceFieldReference, StaticPropertyReference, InstancePropertyReference, IReferencable, Reference, GlobalFunctionReference, StaticThisReference, VariableReference } from "./References"; import { AstHelper } from "./AstHelper"; import { Block } from "./Statements"; import { IType } from "./Interfaces"; export interface IAstNode { } export enum Visibility { Public, Protected, Private } export class MutabilityInfo { constructor(public unused: boolean, public reassigned: boolean, public mutated: boolean) { } } /// types: ForeachVariable, Property /// IVariableWithInitializer: VariableDeclaration, ForVariable, Field, MethodParameter export interface IVariable { name: string; type: IType; mutability: MutabilityInfo; } export interface IClassMember { name: string; visibility: Visibility; isStatic: boolean; getParentInterface(): IInterface; } /// types: VariableDeclaration, ForVariable, Field, MethodParameter export interface IVariableWithInitializer extends IVariable { initializer: Expression; } export interface IHasAttributesAndTrivia { leadingTrivia: string; attributes: { [name: string]: string }; } export interface ISourceFileMember { parentFile: SourceFile; } export class ExportedScope { exports = new Map<string, IImportable>(); getExport(name: string): IImportable { const exp = this.exports.get(name) || null; if (exp === null) throw new Error(`Export ${name} was not found in exported symbols.`); return exp; } addExport(name: string, value: IImportable): void { this.exports.set(name, value); } getAllExports(): IImportable[] { return Array.from(this.exports.values()); } } export class Package { constructor(public name: string, public definitionOnly: boolean) { } static readonly INDEX = "index"; files: { [name: string]: SourceFile } = {}; exportedScopes: { [name: string]: ExportedScope } = {}; static collectExportsFromFile(file: SourceFile, exportAll: boolean, scope: ExportedScope = null): ExportedScope { if (scope === null) scope = new ExportedScope(); for (const cls of file.classes.filter(x => x.isExported || exportAll)) scope.addExport(cls.name, cls); for (const intf of file.interfaces.filter(x => x.isExported || exportAll)) scope.addExport(intf.name, intf); for (const enum_ of file.enums.filter(x => x.isExported || exportAll)) scope.addExport(enum_.name, enum_); for (const func of file.funcs.filter(x => x.isExported || exportAll)) scope.addExport(func.name, func); return scope; } addFile(file: SourceFile, exportAll = false): void { if (file.sourcePath.pkg !== this || file.exportScope.packageName !== this.name) throw new Error("This file belongs to another package!"); this.files[file.sourcePath.path] = file; const scopeName = file.exportScope.scopeName; this.exportedScopes[scopeName] = Package.collectExportsFromFile(file, exportAll, this.exportedScopes[scopeName]); } getExportedScope(name: string): ExportedScope { const scope = this.exportedScopes[name] || null; if (scope === null) throw new Error(`Scope "${name}" was not found in package "${this.name}"`); return scope; } } export class Workspace { packages: { [name: string]: Package } = {}; addPackage(pkg: Package): void { this.packages[pkg.name] = pkg; } getPackage(name: string): Package { const pkg = this.packages[name] || null; if (pkg === null) throw new Error(`Package was not found: "${name}"`); return pkg; } } export class SourcePath { constructor( // @json-ignore public pkg: Package, public path: string) { } toString() { return `${this.pkg.name}/${this.path}`; } } export class LiteralTypes { constructor( public boolean: ClassType, public numeric: ClassType, public string: ClassType, public regex: ClassType, public array: ClassType, public map: ClassType, public error: ClassType, public promise: ClassType) { } } export class SourceFile { /** @creator TypeScriptParser2 */ constructor( public imports: Import[], public interfaces: Interface[], public classes: Class[], public enums: Enum[], public funcs: GlobalFunction[], public mainBlock: Block, public sourcePath: SourcePath, public exportScope: ExportScopeRef) { const fileScope = Package.collectExportsFromFile(this, true); this.addAvailableSymbols(fileScope.getAllExports()); } /** @creator ResolveImports */ availableSymbols = new Map<string, IImportable>(); addAvailableSymbols(items: IImportable[]): void { for (const item of items) this.availableSymbols.set(item.name, item); } // @json-ignore literalTypes: LiteralTypes; // @json-ignore arrayTypes: ClassType[] = []; } export class ExportScopeRef { constructor( public packageName: string, public scopeName: string) { } getId(): string { return `${this.packageName}.${this.scopeName}`; } } /** * The following object types can be imported: Enum, Interface, Class */ export class Import implements IHasAttributesAndTrivia, ISourceFileMember { /** @creator TypeScriptParser2 */ constructor( /** module and filename in TS, namespace in C#, package name in Go, etc */ public exportScope: ExportScopeRef, public importAll: boolean, // @json-ignore public imports: IImportable[], public importAs: string, public leadingTrivia: string) { if (importAs !== null && !importAll) throw new Error("importAs only supported with importAll!"); } /** @creator FillParent */ // @json-ignore parentFile: SourceFile = null; /** @creator FillAttributesFromTrivia */ attributes: { [name: string]: string } = null; } export class Enum implements IAstNode, IHasAttributesAndTrivia, IResolvedImportable, ISourceFileMember, IReferencable { /** @creator TypeScriptParser2 */ constructor( public name: string, public values: EnumMember[], public isExported: boolean, public leadingTrivia: string) { } /** @creator FillParent */ parentFile: SourceFile = null; /** @creator FillAttributesFromTrivia */ attributes: { [name: string]: string } = null; /** @creator ResolveIdentifiers */ references: EnumReference[] = []; createReference(): Reference { return new EnumReference(this); } type = new EnumType(this); } export class EnumMember implements IAstNode { /** @creator TypeScriptParser2 */ constructor(public name: string) { } /** @creator FillParent */ parentEnum: Enum; /** @creator ResolveEnumMemberAccess */ references: EnumMemberReference[] = []; } export interface IInterface { name: string; typeArguments: string[]; baseInterfaces: IType[]; fields: Field[]; methods: Method[]; leadingTrivia: string; parentFile: SourceFile; getAllBaseInterfaces(): IInterface[]; } export interface IImportable { name: string; isExported: boolean; } export interface IResolvedImportable extends IImportable { /** @creator FillParent */ parentFile: SourceFile; } export class UnresolvedImport implements IImportable { constructor(public name: string) { } isExported = true; } export class Interface implements IHasAttributesAndTrivia, IInterface, IResolvedImportable, ISourceFileMember { /** @creator TypeScriptParser2 */ constructor( public name: string, public typeArguments: string[], public baseInterfaces: IType[], public fields: Field[], public methods: Method[], public isExported: boolean, public leadingTrivia: string) { } /** @creator FillParent */ parentFile: SourceFile = null; /** @creator FillAttributesFromTrivia */ attributes: { [name: string]: string } = null; type = new InterfaceType(this, this.typeArguments.map(x => new GenericsType(x))); _baseInterfaceCache: IInterface[] = null; getAllBaseInterfaces(): IInterface[] { if (this._baseInterfaceCache === null) this._baseInterfaceCache = AstHelper.collectAllBaseInterfaces(this); return this._baseInterfaceCache; } } export class Class implements IHasAttributesAndTrivia, IInterface, IResolvedImportable, ISourceFileMember, IReferencable { /** @creator TypeScriptParser2 */ constructor( public name: string, public typeArguments: string[], public baseClass: IType, public baseInterfaces: IType[], public fields: Field[], public properties: Property[], public constructor_: Constructor, public methods: Method[], public isExported: boolean, public leadingTrivia: string) { } /** @creator FillParent */ // @json-ignore parentFile: SourceFile = null; /** @creator FillAttributesFromTrivia */ attributes: { [name: string]: string } = null; /** @creator ResolveIdentifiers */ // @json-ignore classReferences: ClassReference[] = []; /** @creator ResolveIdentifiers */ // @json-ignore thisReferences: ThisReference[] = []; /** @creator ResolveIdentifiers */ // @json-ignore staticThisReferences: StaticThisReference[] = []; /** @creator ResolveIdentifiers */ // @json-ignore superReferences: SuperReference[] = []; createReference(): Reference { return new ClassReference(this); } // @json-ignore type = new ClassType(this, this.typeArguments.map(x => new GenericsType(x))); // @json-ignore _baseInterfaceCache: IInterface[] = null; getAllBaseInterfaces(): IInterface[] { if (this._baseInterfaceCache === null) this._baseInterfaceCache = AstHelper.collectAllBaseInterfaces(this); return this._baseInterfaceCache; } } export class Field implements IVariableWithInitializer, IHasAttributesAndTrivia, IClassMember, IAstNode { /** @creator TypeScriptParser2 */ constructor( public name: string, public type: IType, public initializer: Expression, public visibility: Visibility, public isStatic: boolean, // @json-ignore public constructorParam: MethodParameter, public leadingTrivia: string) { } /** @creator FillParent */ // @json-ignore parentInterface: IInterface = null; /** @creator FillAttributesFromTrivia */ attributes: { [name: string]: string } = null; /** @creator ResolveFieldAndPropertyAccess */ // @json-ignore staticReferences: StaticFieldReference[] = []; /** @creator ResolveFieldAndPropertyAccess */ // @json-ignore instanceReferences: InstanceFieldReference[] = []; /** @creator CollectInheritanceInfo */ // @json-ignore interfaceDeclarations: Field[] = null; /** @creator FillMutability */ mutability: MutabilityInfo = null; getParentInterface(): IInterface { return this.parentInterface; } } export class Property implements IVariable, IHasAttributesAndTrivia, IClassMember, IAstNode { /** @creator TypeScriptParser2 */ constructor( public name: string, public type: IType, public getter: Block, public setter: Block, public visibility: Visibility, public isStatic: boolean, public leadingTrivia: string) { } /** @creator FillParent */ // @json-ignore parentClass: Class = null; /** @creator FillAttributesFromTrivia */ attributes: { [name: string]: string } = null; /** @creator ResolveFieldAndPropertyAccess */ // @json-ignore staticReferences: StaticPropertyReference[] = []; /** @creator ResolveFieldAndPropertyAccess */ // @json-ignore instanceReferences: InstancePropertyReference[] = []; /** @creator FillMutability */ mutability: MutabilityInfo = null; getParentInterface(): IInterface { return this.parentClass; } } export class MethodParameter implements IVariableWithInitializer, IReferencable, IHasAttributesAndTrivia { /** @creator TypeScriptParser2 */ constructor( public name: string, public type: IType, public initializer: Expression, public leadingTrivia: string) { } /** @creator TypeScriptParser2 */ // @json-ignore fieldDecl: Field = null; /** @creator FillParent */ // @json-ignore parentMethod: IMethodBase = null; /** @creator FillAttributesFromTrivia */ attributes: { [name: string]: string } = null; /** @creator ResolveIdentifiers */ // @json-ignore references: MethodParameterReference[] = []; createReference(): Reference { return new MethodParameterReference(this); } /** @creator FillMutability */ mutability: MutabilityInfo = null; } export interface IMethodBase extends IAstNode { parameters: MethodParameter[]; body: Block; throws: boolean; } export interface IMethodBaseWithTrivia extends IMethodBase, IHasAttributesAndTrivia { } export class Constructor implements IMethodBaseWithTrivia { /** @creator TypeScriptParser2 */ constructor( public parameters: MethodParameter[], public body: Block, public superCallArgs: Expression[], public leadingTrivia: string) { } /** @creator FillParent */ // @json-ignore parentClass: Class = null; /** @creator FillAttributesFromTrivia */ attributes: { [name: string]: string } = null; throws: boolean; } export class Method implements IMethodBaseWithTrivia, IClassMember { /** @creator TypeScriptParser2 */ constructor( public name: string, public typeArguments: string[], public parameters: MethodParameter[], public body: Block, public visibility: Visibility, public isStatic: boolean, public returns: IType, public async: boolean, public leadingTrivia: string) { } /** @creator FillParent */ // @json-ignore parentInterface: IInterface = null; /** @creator FillAttributesFromTrivia */ attributes: { [name: string]: string } = null; /** @creator CollectInheritanceInfo */ // @json-ignore interfaceDeclarations: Method[] = null; /** @creator CollectInheritanceInfo */ // @json-ignore overrides: Method = null; /** @creator CollectInheritanceInfo */ // @json-ignore overriddenBy: Method[] = []; throws: boolean; getParentInterface(): IInterface { return this.parentInterface; } } export class GlobalFunction implements IMethodBaseWithTrivia, IResolvedImportable, IReferencable { /** @creator TypeScriptParser2 */ constructor( public name: string, public parameters: MethodParameter[], public body: Block, public returns: IType, public isExported: boolean, public leadingTrivia: string) { } /** @creator FillParent */ parentFile: SourceFile = null; /** @creator FillAttributesFromTrivia */ attributes: { [name: string]: string } = null; throws: boolean; /** @creator ResolveIdentifiers */ references: GlobalFunctionReference[] = []; createReference(): Reference { return new GlobalFunctionReference(this); } } export class Lambda extends Expression implements IMethodBase { constructor( public parameters: MethodParameter[], public body: Block) { super(); } returns: IType = null; throws: boolean; /** @creator LambdaCaptureCollector */ captures: IVariable[] = null; }
the_stack
import addon from '../utils/addon'; import { Component, NativeElement } from '../core/Component'; import { QPainterPath } from '../QtWidgets/QPainterPath'; import { PenStyle } from '../QtEnums'; import { QBrush } from '../QtGui/QBrush'; import { QColor } from '../QtGui/QColor'; import { QPoint } from '../QtCore/QPoint'; import { QPen } from '../QtGui/QPen'; import { QWidget } from './QWidget'; import { QImage } from '../QtGui/QImage'; import { QFont } from '../QtGui/QFont'; import { QRect } from '../QtCore/QRect'; /** > Lets you paint on widgets. * **This class is a JS wrapper around Qt's [QPainter class](https://doc.qt.io/qt-5/qpainter.html)** Note: QPainter works only inside the paint event. ### Example ```javascript import { FlexLayout, WidgetEventTypes, QMainWindow, QPainter, QWidget } from '@nodegui/nodegui'; const win = new QMainWindow(); const center = new QWidget(); const layout = new FlexLayout(); center.setLayout(layout); win.resize(200, 200); win.addEventListener(WidgetEventTypes.Paint, () => { const painter = new QPainter(win); painter.drawText(20, 20, 'Hello'); painter.end(); }); win.show(); (global as any).win = win; ``` ## Advanced example: https://github.com/nodegui/examples/blob/master/nodegui/custom-native-widget-qpainter */ export class QPainter extends Component { native: NativeElement; constructor(); constructor(device: Component); constructor(device?: Component) { let native; if (device) { native = new addon.QPainter(device.native); } else { native = new addon.QPainter(); } super(); this.native = native; } // *** Public Functions *** // TODO: const QBrush & background() const // TODO: Qt::BGMode backgroundMode() const begin(device: QWidget | QImage): boolean { if (device instanceof QWidget) { return this.native.begin(device.native, 'widget'); } else { return this.native.begin(device.native, 'image'); } } beginNativePainting(): void { this.native.beginNativePainting(); } // TODO: QRectF boundingRect(const QRectF &rectangle, int flags, const QString &text) // TODO: QRect boundingRect(const QRect &rectangle, int flags, const QString &text) boundingRect(x: number, y: number, w: number, h: number, flags: number, text: string): QRect { return new QRect(this.native.boundingRect(x, y, w, h, flags, text)); } // TODO: QRectF boundingRect(const QRectF &rectangle, const QString &text, const QTextOption &option = QTextOption()) // TODO: const QBrush & brush() const // TODO: QPoint brushOrigin() const // TODO: QRectF clipBoundingRect() const // TODO: QPainterPath clipPath() const // TODO: QRegion clipRegion() const // TODO: QTransform combinedTransform() const compositionMode(): CompositionMode { return this.native.compositionMode(); } // TODO: QPaintDevice * device() const // TODO: const QTransform & deviceTransform() const // TODO: void drawArc(const QRectF &rectangle, int startAngle, int spanAngle) drawArc(x: number, y: number, width: number, height: number, startAngle: number, spanAngle: number): void { this.native.drawArc(x, y, width, height, startAngle, spanAngle); } // TODO: void drawChord(const QRectF &rectangle, int startAngle, int spanAngle) drawChord(x: number, y: number, width: number, height: number, startAngle: number, spanAngle: number): void { this.native.drawChord(x, y, width, height, startAngle, spanAngle); } // TODO: void drawChord(const QRect &rectangle, int startAngle, int spanAngle) drawConvexPolygon(points: QPoint[]): void { const nativePoints = points.map((point) => point.native); this.native.drawConvexPolygon(nativePoints); } // TODO: void drawConvexPolygon(const QPolygonF &polygon) drawEllipse(x: number, y: number, width: number, height: number): void { return this.native.drawEllipse(x, y, width, height); } // TODO: void drawEllipse(const QRectF &rectangle) // TODO: void drawGlyphRun(const QPointF &position, const QGlyphRun &glyphs) drawImage(x: number, y: number, image: QImage, sx = 0, sy = 0, sw = -1, sh = -1): void { this.native.drawImage(x, y, image.native, sx, sy, sw, sh); } drawLine(x1: number, y1: number, x2: number, y2: number): void { this.native.drawLine(x1, y1, x2, y2); } // TODO: void drawLines(const QVector<QLineF> &lines) drawPath(path: QPainterPath): void { return this.native.drawPath(path.native); } // TODO: void drawPicture(int x, int y, const QPicture &picture) drawPie(x: number, y: number, width: number, height: number, startAngle: number, sweepLength: number): void { return this.native.drawPie(x, y, width, height, startAngle, sweepLength); } // TODO: void drawPixmap(int x, int y, int w, int h, const QPixmap &pixmap, int sx, int sy, int sw, int sh) // TODO: void drawPixmapFragments(const QPainter::PixmapFragment *fragments, int fragmentCount, const QPixmap &pixmap, QPainter::PixmapFragmentHints hints = PixmapFragmentHints()) drawPoint(x: number, y: number): void { this.native.drawPoint(x, y); } // TODO: void drawPoints(const QPointF *points, int pointCount) // TODO: void drawPolygon(const QPointF *points, int pointCount, Qt::FillRule fillRule = Qt::OddEvenFill) drawRect(x: number, y: number, width: number, height: number): void { this.native.drawRect(x, y, width, height); } // TODO: void drawRects(const QVector<QRectF> &rectangles) // TODO: void drawRoundedRect(int x, int y, int w, int h, qreal xRadius, qreal yRadius, Qt::SizeMode mode = Qt::AbsoluteSize) // TODO: void drawStaticText(int left, int top, const QStaticText &staticText) drawText(x: number, y: number, text: string): void { return this.native.drawText(x, y, text); } // TODO: void drawText(int x, int y, int width, int height, int flags, const QString &text, QRect *boundingRect = nullptr) // TODO: void drawTiledPixmap(int x, int y, int width, int height, const QPixmap &pixmap, int sx = 0, int sy = 0) end(): boolean { return this.native.end(); } endNativePainting(): void { this.native.endNativePainting(); } eraseRect(x: number, y: number, width: number, height: number): void { this.native.eraseRect(x, y, width, height); } fillRect(x: number, y: number, width: number, height: number, color: QColor): void { this.native.fillRect(x, y, width, height, color.native); } // TODO: const QFont & font() const // TODO: QFontInfo fontInfo() const // TODO: QFontMetrics fontMetrics() const // TODO: bool hasClipping() const // CLASS: QPainter // TODO: bool isActive() const // TODO: Qt::LayoutDirection layoutDirection() const opacity(): number { return this.native.opacity(); } // TODO: QPaintEngine * paintEngine() const // TODO: const QPen & pen() const // TODO: QPainter::RenderHints renderHints() const // TODO: void resetTransform() restore(): void { this.native.restore(); } rotate(angle: number): void { this.native.rotate(angle); } save(): void { this.native.save(); } scale(sx: number, sy: number): void { this.native.scale(sx, sy); } // TODO: void setBackground(const QBrush &brush) // TODO: void setBackgroundMode(Qt::BGMode mode) setBrush(colorOrBrush: QColor | QBrush): void { if (colorOrBrush instanceof QColor) { this.native.setBrush(colorOrBrush.native, 'color'); } else { this.native.setBrush(colorOrBrush.native, 'brush'); } } setBrushOrigin(x: number, y: number): void { this.native.setBrushOrigin(x, y); } setCompositionMode(mode: CompositionMode): void { this.native.setCompositionMode(mode); } // TODO: void setClipRect(int x, int y, int width, int height, Qt::ClipOperation operation = Qt::ReplaceClip) // TODO: void setClipRegion(const QRegion &region, Qt::ClipOperation operation = Qt::ReplaceClip) // TODO: void setClipping(bool enable) // TODO: void setCompositionMode(QPainter::CompositionMode mode) setFont(font: QFont): void { this.native.setFont(font.native); } // TODO: void setLayoutDirection(Qt::LayoutDirection direction) setOpacity(opacity: number): void { this.native.setOpacity(opacity); } setPen(arg: PenStyle | QColor | QPen): void { if (typeof arg == 'number') { this.native.setPen(arg, 'style'); } else if (arg instanceof QColor) { this.native.setPen(arg.native, 'color'); } else if (arg instanceof QPen) { this.native.setPen(arg.native, 'pen'); } } setRenderHint(hint: RenderHint, on = true): void { this.native.setRenderHint(hint, on); } /** * Sets the world transformation matrix. * * @param matrix2x3 An array of length 6 representing a 2x3 transformation * matrix. The order of elements corresponds to the * convention used in QTransform, i.e. m11, m12, m21, m22, * dx, and dy. * @param combine If set then this transform will be combining with the * curent one. Otherwise it replaces it completely. */ setTransform(matrix2x3: number[] | Float32Array, combine = false): void { if (matrix2x3.length !== 6) { throw new Error('Parameter "matrix2x3" to QPainter.setTransform() must have length 6.'); } this.native.setTransform( 'matrix2x3', combine, matrix2x3[0], matrix2x3[1], matrix2x3[2], matrix2x3[3], matrix2x3[4], matrix2x3[5], ); } // TODO: void setViewTransformEnabled(bool enable) // TODO: void setViewport(const QRect &rectangle) // TODO: void setViewport(int x, int y, int width, int height) // TODO: void setWindow(const QRect &rectangle) // TODO: void setWindow(int x, int y, int width, int height) // TODO: void setWorldMatrixEnabled(bool enable) // TODO: void setWorldTransform(const QTransform &matrix, bool combine = false) // TODO: void shear(qreal sh, qreal sv) strokePath(path: QPainterPath, pen: QPen): void { return this.native.strokePath(path.native, pen.native); } // TODO: bool testRenderHint(QPainter::RenderHint hint) const // TODO: const QTransform & transform() const translate(dx: number, dy: number): void { this.native.translate(dx, dy); } // TODO: bool viewTransformEnabled() const // TODO: QRect viewport() const // TODO: QRect window() const // TODO: bool worldMatrixEnabled() const // TODO: const QTransform & worldTransform() const } export enum RenderHint { Antialiasing = 0x01, TextAntialiasing = 0x02, SmoothPixmapTransform = 0x04, HighQualityAntialiasing = 0x08, NonCosmeticDefaultPen = 0x10, Qt4CompatiblePainting = 0x20, LosslessImageRendering = 0x40, } export enum CompositionMode { CompositionMode_SourceOver = 0, CompositionMode_DestinationOver = 1, CompositionMode_Clear = 2, CompositionMode_Source = 3, CompositionMode_Destination = 4, CompositionMode_SourceIn = 5, CompositionMode_DestinationIn = 6, CompositionMode_SourceOut = 7, CompositionMode_DestinationOut = 8, CompositionMode_SourceAtop = 9, CompositionMode_DestinationAtop = 10, CompositionMode_Xor = 11, CompositionMode_Plus = 12, CompositionMode_Multiply = 13, CompositionMode_Screen = 14, CompositionMode_Overlay = 15, CompositionMode_Darken = 16, CompositionMode_Lighten = 17, CompositionMode_ColorDodge = 18, CompositionMode_ColorBurn = 19, CompositionMode_HardLight = 20, CompositionMode_SoftLight = 21, CompositionMode_Difference = 22, CompositionMode_Exclusion = 23, RasterOp_SourceOrDestination = 24, RasterOp_SourceAndDestination = 25, RasterOp_SourceXorDestination = 26, RasterOp_NotSourceAndNotDestination = 27, RasterOp_NotSourceOrNotDestination = 28, RasterOp_NotSourceXorDestination = 29, RasterOp_NotSource = 30, RasterOp_NotSourceAndDestination = 31, RasterOp_SourceAndNotDestination = 32, RasterOp_NotSourceOrDestination = 33, RasterOp_ClearDestination = 35, RasterOp_SetDestination = 36, RasterOp_NotDestination = 37, RasterOp_SourceOrNotDestination = 34, }
the_stack
"use strict"; /* (hapi)nes WebSocket Client (https://github.com/hapijs/nes) Copyright (c) 2015-2016, Eran Hammer <eran@hammer.io> and other contributors BSD Licensed */ import WebSocket from "ws"; import { parseNesMessage, stringifyNesMessage } from "./utils"; /* eslint no-undef: 0 */ const version = "2"; const ignore = function () {}; const nextTick = function (callback) { return (err) => { setTimeout(() => callback(err), 0); }; }; // NesError types const errorTypes = { TIMEOUT: "timeout", DISCONNECT: "disconnect", SERVER: "server", PROTOCOL: "protocol", WS: "ws", USER: "user", }; const NesError = function (err, type) { if (typeof err === "string") { err = new Error(err); } err.type = type; err.isNes = true; try { throw err; // ensure stack trace for IE11 } catch (withStack) { return withStack; } }; // Error codes const errorCodes = { 1000: "Normal closure", 1001: "Going away", 1002: "Protocol error", 1003: "Unsupported data", 1004: "Reserved", 1005: "No status received", 1006: "Abnormal closure", 1007: "Invalid frame payload data", 1008: "Policy violation", 1009: "Message too big", 1010: "Mandatory extension", 1011: "Internal server error", 1015: "TLS handshake", }; const DEFAULT_MAX_PAYLOAD_CLIENT = 100 * 1024; // Client export class Client { public onError; public onConnect; public onDisconnect; public onHeartbeatTimeout; public id; private _url; private _settings; private _heartbeatTimeout; private _ws; private _reconnection; private _reconnectionTimer; private _ids; private _requests; private _heartbeat; private _disconnectListeners; private _disconnectRequested; private _lastPinged; public constructor(url, options?) { options = options || {}; options.ws = options.ws || {}; options.ws = { maxPayload: DEFAULT_MAX_PAYLOAD_CLIENT, ...options.ws, perMessageDeflate: false } // Configuration this._url = url; this._settings = options; this._heartbeatTimeout = false; // Server heartbeat configuration // State this._ws = null; this._reconnection = null; this._reconnectionTimer = null; this._ids = 0; // Id counter this._requests = {}; // id -> { resolve, reject, timeout } this._heartbeat = null; this._disconnectListeners = null; this._disconnectRequested = false; // Events this.onError = (err) => console.error(err); // General error handler (only when an error cannot be associated with a request) this.onConnect = ignore; // Called whenever a connection is established this.onDisconnect = ignore; // Called whenever a connection is lost: function(willReconnect) this.onHeartbeatTimeout = ignore; // Called when a heartbeat timeout will cause a disconnection // Public properties this.id = null; // Assigned when hello response is received } public connect(options?) { options = options || {}; if (this._reconnection) { return Promise.reject(NesError("Cannot connect while client attempts to reconnect", errorTypes.USER)); } if (this._ws) { return Promise.reject(NesError("Already connected", errorTypes.USER)); } if (options.reconnect !== false) { // Defaults to true this._reconnection = { // Options: reconnect, delay, maxDelay wait: 0, delay: options.delay || 1000, // 1 second maxDelay: options.maxDelay || 5000, // 5 seconds retries: options.retries || Infinity, // Unlimited settings: { auth: options.auth, timeout: options.timeout, }, }; } else { this._reconnection = null; } return new Promise((resolve, reject) => { this._connect(options, true, (err) => { if (err) { return reject(err); } return resolve(); }); }); } public disconnect() { return new Promise((resolve) => this._disconnect(resolve, false)); } public terminate() { return new Promise((resolve) => this._disconnect(resolve, false, true)); } public request(options) { if (typeof options === "string") { options = { path: options, }; } const request = { type: "request", method: "POST", path: options.path, headers: options.headers, payload: options.payload, }; return this._send(request, true); } public _isReady() { return this._ws && this._ws.readyState === WebSocket.OPEN; } public setMaxPayload(maxPayload: number) { if (this._ws?._receiver) { this._ws._receiver._maxPayload = maxPayload; } } public setTimeout(timeout: number) { this._settings.timeout = timeout; } private _connect(options, initial, next) { const ws = new WebSocket(this._url, this._settings.ws); this._ws = ws; clearTimeout(this._reconnectionTimer); this._reconnectionTimer = null; const reconnect = (event) => { if (ws.onopen) { finalize(NesError("Connection terminated while waiting to connect", errorTypes.WS)); } const wasRequested = this._disconnectRequested; // Get value before _cleanup() this._cleanup(); const log = { code: event.code, explanation: errorCodes[event.code] || "Unknown", reason: event.reason, wasClean: event.wasClean, willReconnect: this._willReconnect(), wasRequested, }; this.onDisconnect(log.willReconnect, log); this._reconnect(); }; const finalize = (err) => { if (next) { // Call only once when connect() is called const nextHolder = next; next = null; return nextHolder(err); } return this.onError(err); }; const timeoutHandler = () => { this._cleanup(); finalize(NesError("Connection timed out", errorTypes.TIMEOUT)); if (initial) { return this._reconnect(); } }; const timeout = options.timeout ? setTimeout(timeoutHandler, options.timeout) : null; ws.onopen = () => { if (timeout) { clearTimeout(timeout); } ws.onopen = null; this._hello(options.auth) .then(() => { this.onConnect(); finalize(undefined); }) .catch((err) => { this._disconnect(() => nextTick(finalize)(err), true); // Stop reconnection when the hello message returns error }); }; ws.onerror = (event) => { /* istanbul ignore next */ if (timeout) { clearTimeout(timeout); } if (this._willReconnect()) { return reconnect(event); } this._cleanup(); const error = NesError("Socket error", errorTypes.WS); return finalize(error); }; ws.onclose = reconnect; ws.onmessage = (message) => { return this._onMessage(message); }; ws.on("ping", () => this._disconnect(() => {}, true, true)); ws.on("pong", () => this._disconnect(() => {}, true, true)); } private _disconnect(next, isInternal, terminate = false) { this._reconnection = null; clearTimeout(this._reconnectionTimer); this._reconnectionTimer = null; const requested = this._disconnectRequested || !isInternal; // Retain true if (this._disconnectListeners) { this._disconnectRequested = requested; this._disconnectListeners.push(next); return; } if (!this._ws || (this._ws.readyState !== WebSocket.OPEN && this._ws.readyState !== WebSocket.CONNECTING)) { return next(); } this._disconnectRequested = requested; this._disconnectListeners = [next]; if (terminate) { this._ws.terminate(); } else { this._ws.close(); } } private _cleanup() { if (this._ws) { const ws = this._ws; this._ws = null; if (ws.readyState !== WebSocket.CLOSED && ws.readyState !== WebSocket.CLOSING) { ws.close(); } ws.onopen = null; ws.onclose = null; ws.onerror = ignore; ws.onmessage = null; } this.id = null; clearTimeout(this._heartbeat); this._heartbeat = null; // Flush pending requests const error = NesError("Request failed - server disconnected", errorTypes.DISCONNECT); const requests = this._requests; this._requests = {}; const ids = Object.keys(requests); for (let i = 0; i < ids.length; ++i) { const id = ids[i]; const request = requests[id]; clearTimeout(request.timeout); request.reject(error); } if (this._disconnectListeners) { const listeners = this._disconnectListeners; this._disconnectListeners = null; this._disconnectRequested = false; listeners.forEach((listener) => listener()); } } private _reconnect() { // Reconnect const reconnection = this._reconnection; if (!reconnection) { return; } if (reconnection.retries < 1) { return this._disconnect(ignore, true); // Clear _reconnection state } --reconnection.retries; reconnection.wait = reconnection.wait + reconnection.delay; const timeout = Math.min(reconnection.wait, reconnection.maxDelay); this._reconnectionTimer = setTimeout(() => { this._connect(reconnection.settings, false, (err) => { if (err) { this.onError(err); return this._reconnect(); } }); }, timeout); } private _send(request, track) { if (!this._isReady()) { return Promise.reject(NesError("Failed to send message - server disconnected", errorTypes.DISCONNECT)); } request.id = ++this._ids; let encoded; try { encoded = stringifyNesMessage(request); } catch (err) { return Promise.reject(err); } // Ignore errors if (!track) { try { this._ws.send(encoded); return Promise.resolve(); } catch (err) { return Promise.reject(NesError(err, errorTypes.WS)); } } // Track errors const record: { resolve: any; reject: any; timeout: any } = { resolve: null, reject: null, timeout: null, }; const promise = new Promise((resolve, reject) => { record.resolve = resolve; record.reject = reject; }); /* istanbul ignore next */ if (this._settings.timeout) { record.timeout = setTimeout(() => { record.timeout = null; delete this._requests[request.id]; return record.reject(NesError("Request timed out", errorTypes.TIMEOUT)); }, this._settings.timeout); } this._requests[request.id] = record; try { this._ws.send(encoded); } catch (err) { clearTimeout(this._requests[request.id].timeout); delete this._requests[request.id]; return Promise.reject(NesError(err, errorTypes.WS)); } return promise; } private _hello(auth) { const request: any = { type: "hello", version, }; return this._send(request, true); } private _resetMaxPayload() { this.setMaxPayload(this._settings.ws.maxPayload); } private _onMessage(message) { this._beat(); let update; try { if (!(message.data instanceof Buffer)) { return this.onError(NesError("Received message is not a Buffer", errorTypes.PROTOCOL)); } update = parseNesMessage(message.data); } catch (err) { return this.onError(NesError(err, errorTypes.PROTOCOL)); } // Recreate error let error: any = null; if (update.statusCode && update.statusCode >= 400) { /* istanbul ignore next */ update.payload = update.payload instanceof Buffer ? (update.payload as Buffer).slice(0, 512).toString() // slicing to reduce possible intensive toString() call : "Error"; error = NesError(update.payload, errorTypes.SERVER); error.statusCode = update.statusCode; error.data = update.payload; error.headers = update.headers; error.path = update.path; } // Ping if (update.type === "ping") { if (this._lastPinged && Date.now() < this._lastPinged + 1000) { this._lastPinged = Date.now(); return this.onError(NesError("Ping exceeded limit", errorTypes.PROTOCOL)); } this._lastPinged = Date.now(); return this._send({ type: "ping" }, false).catch(ignore); // Ignore errors } this._resetMaxPayload(); // Lookup request (message must include an id from this point) const request = this._requests[update.id]; if (!request) { return this.onError(NesError("Received response for unknown request", errorTypes.PROTOCOL)); } clearTimeout(request.timeout); delete this._requests[update.id]; const next = (err, args?) => { if (err) { return request.reject(err); } return request.resolve(args); }; // Response if (update.type === "request") { return next(error, { payload: update.payload, statusCode: update.statusCode, headers: update.headers }); } // Authentication if (update.type === "hello") { this.id = update.socket; if (update.heartbeat) { this._heartbeatTimeout = update.heartbeat.interval + update.heartbeat.timeout; if (this._heartbeatTimeout === 0) { this._heartbeatTimeout = false; } this._beat(); // Call again once timeout is set } return next(error); } next(NesError("Received invalid response", errorTypes.PROTOCOL)); return this.onError(NesError("Received unknown response type: " + update.type, errorTypes.PROTOCOL)); } private _beat() { if (!this._heartbeatTimeout) { return; } clearTimeout(this._heartbeat); this._heartbeat = setTimeout(() => { this.onError(NesError("Disconnecting due to heartbeat timeout", errorTypes.TIMEOUT)); this.onHeartbeatTimeout(this._willReconnect()); this._ws.close(); }, this._heartbeatTimeout); } private _willReconnect() { return !!(this._reconnection && this._reconnection.retries >= 1); } }
the_stack
import { CustomPropertyHandler, PropertyResolveResult, WidgetResolveResult } from "../providers/property-handler-provider"; import * as parseXml from '../parser/types'; import { WidgetModel, ExtraDataModel, AttributeModel, PropertyModel, AttributeInfo } from '../models/models'; import { extractForLoopParams, makeTabs, sortProperties, spaceAfter } from "../utils"; import { PropertyResolver } from "../resolvers/property-resolver"; export class BuilderHandler extends CustomPropertyHandler { priority = -100000; // lowest priority isElement = true; elementAttributes: AttributeInfo[] = [ { name: 'name' }, { name: 'data', snippet: 'item of ${0:ctrl.items}' }, { name: 'params' } ]; valueSnippet = 'name="${0:builderName}" data="${1:item of ${2:ctrl.items}}" params="${3:context}"'; constructor(private readonly propertyResolver: PropertyResolver) { super(); } canResolve(element: parseXml.Element, handlerProperty: string, widget: WidgetModel): boolean { return true; } // canResolvePropertyElement(): boolean { // return true; // } // resolvePropertyElement(element: parseXml.Element, widgetResolveResult: WidgetResolveResult, parent: parseXml.Element, parentChildren: parseXml.Element[], resolveWidget: (element: parseXml.Element, parent: parseXml.Element) => WidgetResolveResult): WidgetModel | null { // const res = this.resolve(element, { // value: { value: widgetResolveResult.propertyElementProperties.filter(a => a.name === 'data')[0].value }, // name: widgetResolveResult.propertyElementProperties.filter(a => a.name === 'name')[0].value || 'builder' // } as any, widgetResolveResult.widget); // return res.wrapperWidget; // } resolve(element: parseXml.Element, attr: AttributeModel, widget: WidgetModel): PropertyResolveResult { let wrapperWidget: WidgetModel | null = null; let extraData: ExtraDataModel | null = null; // retreive all builder(s) inside the widget let propertyValue = (attr.value as any); let builders = [propertyValue]; if (propertyValue instanceof Array) { builders = [...propertyValue]; } // const use = element.attributes.use; const buildersData: any[] = []; const contentWidget: WidgetModel = { controllers: [], vars: [], formControls: [], properties: [ { dataType: 'function', name: 'builder', value: '' } ], type: widget.type, tempData: { buildersData }, wrappedWidgets: [widget], onResolved: [] }; builders.forEach(builder => { const result = this.resolveBuilder(element, attr, builder, wrapperWidget, contentWidget); if (result) { wrapperWidget = result.wrapperWidget; buildersData.push(result.tempData); } }); return { extraData, wrapperWidget, value: null as any, handled: true }; } private resolveBuilder(element: parseXml.Element, attr: AttributeModel, builderData: any, wrapperWidget: WidgetModel | null, contentWidget: WidgetModel): { tempData: any, wrapperWidget: WidgetModel | null } | null { let childWidget = builderData.value; if (!childWidget) { return null; } let arrayOfIfWidgets = null; let hasArrayProp = false; if (childWidget instanceof Array) { // get (if) widgets arrayOfIfWidgets = childWidget.filter(a => a.type === ':if'); // if there are no (if) widgets, get first widget anyway if (arrayOfIfWidgets.length) { childWidget = null; } else { hasArrayProp = builderData.extraData.properties.filter((a: any) => a.name === 'array').length > 0; if (!hasArrayProp) { childWidget = childWidget[0]; } } contentWidget.wrappedWidgets.push(...arrayOfIfWidgets); } if (!hasArrayProp && childWidget) { contentWidget.wrappedWidgets.push(childWidget); } const properties: any[] = builderData.extraData.properties; const builderName = properties.filter(a => a.name === 'name').map(a => a.value)[0]; const value = properties.filter(a => a.name === 'data').map(a => a.value)[0] || ''; let params = properties.filter(a => a.name === 'params').map(a => a.value)[0]; const { listName, indexName, itemName, typeName } = extractForLoopParams(value); const listNameWithPipes = value.substr(value.indexOf(listName)); const tempData: any = { listName, indexName, itemName, typeName, builderName, params, childWidget: childWidget, arrayOfIfWidgets }; // contentWidget.properties[1].value = childWidget; // todo review const result = this.propertyResolver.pipeValueResolver.resolve(element, attr.name, listNameWithPipes, wrapperWidget || contentWidget); wrapperWidget = result.wrapperWidget || wrapperWidget || contentWidget; tempData.listValueVariableName = result.wrapperWidget ? result.value : tempData.listName; // if the childWidget is the same as the result.wrapperWidget that means they are StreamBuilder // and we need to unwrap the original child widget then make it a child // in other words: replace the StreamBuilder with its child (that wrapped by this StreamBuilder) // This is intended to prevent code-generating the StreamBuilder twice // one from the hierarchy, and the other in the generate(...) method below // which generating the tempData.childWidget as a child of each 'builder' if (result.wrapperWidget && tempData.childWidget && tempData.childWidget.tempData === result.wrapperWidget.tempData && !!result.wrapperWidget.tempData) { tempData.childWidget = tempData.childWidget.wrappedWidgets[0]; } return { tempData, wrapperWidget }; } canGenerate(widget: WidgetModel): boolean { const builderProp = widget.properties.filter(a => a.name === 'builder')[0]; if (builderProp && builderProp.extraData) { return false; } // because the StreamBuilder also has a 'builder' property const widgetsThatHaveItsOwnBuilderProperty = ['StreamBuilder', 'FutureBuilder']; return widgetsThatHaveItsOwnBuilderProperty .filter(a => a === widget.type).length === 0; } generate(widget: WidgetModel, tabsLevel: number, generateChildWidgetCode: (widget: WidgetModel, tabsLevel: number) => string, generatePropertyCode: (widget: WidgetModel, property: PropertyModel, tabsLevel: number) => string): string { const tempData: any = widget.tempData; const originalWidget = widget.wrappedWidgets[0]; const buildersData: any[] = tempData.buildersData; let code = ''; // generate builders code (builder that have no names) let codes = buildersData.filter(a => !a.builderName).map(data => this.generateBuilderCode(data, generateChildWidgetCode, tabsLevel)); code += codes.join(',\n'); if (codes.length) { code += ',\n'; } // generate other user-defined properties let propCode = originalWidget.properties.sort(sortProperties) .filter(a => !a.skipGeneratingCode && ['children', 'builder'].indexOf(a.name) === -1) .map(p => { return generatePropertyCode(originalWidget, p, tabsLevel); }) .join(`,\n`); code += propCode; // generate builders code (builder that have names) let codes2 = buildersData.filter(a => !!a.builderName).map(data => this.generateBuilderCode(data, generateChildWidgetCode, tabsLevel)); if (propCode.length && codes2.length) { code += ',\n'; } code += codes2.join(',\n'); return code; } private generateBuilderCode(data: any, generateChildWidgetCode: (widget: WidgetModel, tabsLevel: number) => string, tabsLevel: number): string { const tabs = makeTabs(tabsLevel); let childWidget = data.childWidget as WidgetModel; let ifWidgets = data.arrayOfIfWidgets as WidgetModel[]; const isChildWidgetArray = (childWidget as any) instanceof Array; const hasItemList = data.listValueVariableName && data.itemName; const indexName = data.indexName || 'index'; // generate itemBuilder function let code = `${tabs}${data.builderName ? data.builderName + ': ' : ''}(${data.params || 'BuildContext context'}${data.params ? '' : (hasItemList ? `, ${indexName}` : '')}) {`; // if (hasItemList && (!data.params || data.indexName)) { if (hasItemList) { code += ` ${tabs} final ${spaceAfter(data.typeName)}${data.itemName} = ${data.listValueVariableName} == null || ${data.listValueVariableName}.length <= ${indexName} || ${data.listValueVariableName}.length == 0 ? null : ${data.listValueVariableName}[${indexName}];`; } if (ifWidgets && ifWidgets.length) { code += '\n' + this.generateIfWidgetsCode(ifWidgets, tabsLevel + 1, generateChildWidgetCode); return code + `\n${tabs}}`; } let childWidgetCode = ''; if (isChildWidgetArray) { childWidgetCode = `[\n${tabs}${(childWidget as any).map((child: WidgetModel) => ' ' + generateChildWidgetCode(child, tabsLevel + 2)).join(',\n' + tabs)}\n${tabs} ]`; } else { if (childWidget.type === 'builder') { childWidget = childWidget.properties.filter(a => a.name === 'child' || a.name === 'children')[0].value as any; } childWidgetCode = childWidget ? generateChildWidgetCode(childWidget, tabsLevel + 1) : 'Container(width: 0, height: 0)'; } if (childWidgetCode.startsWith('...')) { childWidgetCode = childWidgetCode.substring(3); } code += ` ${tabs} return ${childWidgetCode}; ${tabs}}`; return code; } private generateIfWidgetsCode(ifWidgets: WidgetModel[], tabsLevel: number, generateChildWidgetCode: (widget: WidgetModel, tabsLevel: number) => string): string { const tabs = makeTabs(tabsLevel); const code = ifWidgets .filter(w => w.wrappedWidgets[0]) .map(w => { const child = w.wrappedWidgets[0]; let code = `${tabs}if (${w.tempData.condition}) {\n`; code += `${tabs} return ${generateChildWidgetCode(child, tabsLevel + 1)};\n`; code += `${tabs}}`; return code; }).join('\n'); return code; } }
the_stack
import { TransferCallTrace, Fiber, FiberDispatchCall, FiberRoot, ReactContext, ReactDispatcherTrapApi, ReactInternals, RerenderState, TransferCallTracePoint, HookInfo, HookCompute, } from "../types"; import { CoreApi } from "./core"; import { extractCallLoc, parseStackTraceLine } from "./utils/stackTrace"; type StateHookName = "useState" | "useReducer"; type MemoHookName = "useMemo" | "useCallback"; type EffectHookName = "useEffect" | "useLayoutEffect"; type Dispatcher = { useState(...args: any[]): [any, DispatchFn]; useReducer(...args: any[]): [any, DispatchFn]; useMemo(cb: () => any, deps?: any[]): any; useCallback(cb: () => any, deps?: any[]): () => any; useEffect(create: () => any, deps?: any[]): void; useLayoutEffect(create: () => any, deps?: any[]): void; useContext(context: ReactContext<any>, ...rest: any[]): any; readContext(context: ReactContext<any>): any; }; type DispatchFn = (value: any) => any; type FiberDispatcherInfo = { hooks: HookInfo[]; }; function extractHookPath(depth = 0) { const stack = String(new Error().stack) .split("\n") .slice(4 + depth); const path = []; const result: TransferCallTrace = { path: undefined, loc: null, }; let prev: TransferCallTrace | TransferCallTracePoint = result; for (const line of stack) { const parsed = parseStackTraceLine(line); if (!parsed) { break; } prev.loc = parsed.loc; if (!parsed.name.startsWith("use")) { break; } path.unshift( (prev = { name: parsed.name, loc: null, }) ); } if (path.length) { result.path = path; } // console.log(String(new Error().stack).split("\n")); // console.log(path); return result; } export function dispatcherTrap( renderer: ReactInternals, { getFiberTypeId, isFiberRoot }: CoreApi ): ReactDispatcherTrapApi { let currentDispatcher: Dispatcher | null = null; let currentRoot: FiberRoot | null = null; let currentFiber: Fiber | null = null; let currentFiberCollectInfo: FiberDispatcherInfo | null = null; let currentEffectFiber: Fiber | null = null; let currentEffectName: "effect" | "layout-effect" | null = null; let currentFiberHookIndex = 0; let dispatchCalls: FiberDispatchCall[] = []; // let currentFiberRerenderState: RerenderState | null = null; const knownDispatcher = new Set<Dispatcher>(); const ignoreDispatcherTransition = new Set<Dispatcher>(); const fiberTypeInfo = new Map<number, any>(); const fiberRoot = new WeakMap<Fiber, FiberRoot>(); const rerenderStates = new WeakMap<Fiber, RerenderState[]>(); const fiberComputedMemo = new WeakMap<Fiber, HookCompute[]>(); const patchedHookFn = new WeakMap< DispatchFn, { hook: number; fn: DispatchFn } >(); function trackUseHook( name: string, deps: number | null = null, context: ReactContext<any> | null = null ) { if (currentFiberCollectInfo !== null) { currentFiberCollectInfo.hooks?.push({ name, deps, context, trace: extractHookPath(1), }); } return currentFiberHookIndex++; } function patchMemoHook(hookName: MemoHookName, dispatcher: Dispatcher) { const orig = dispatcher[hookName]; dispatcher[hookName] = (fn: () => any, deps?: any[]) => { trackUseHook(hookName, Array.isArray(deps) ? deps.length : null); return orig(fn, deps); }; } function patchEffectHook(hookName: EffectHookName, dispatcher: Dispatcher) { const orig = dispatcher[hookName]; dispatcher[hookName] = function (create: any, deps?: any[]) { trackUseHook(hookName); const hookOwnerFiber = currentFiber; // const path = trackHookLocation(); const wrappedCreate = () => { currentEffectFiber = hookOwnerFiber; currentEffectName = hookName === "useEffect" ? "effect" : "layout-effect"; const destroy = create(); currentEffectFiber = null; currentEffectName = null; // const fiberId = getOrGenerateFiberId(fiber); // recordEvent({ // op: "effect-create", // commitId: -1, // fiberId, // path, // }); if (typeof destroy === "function") { return () => { // recordEvent({ // op: "effect-destroy", // commitId: -1, // fiberId, // path, // }); return destroy(); }; } return destroy; }; return orig(wrappedCreate, deps); }; } function patchStateHook(hookName: StateHookName, dispatcher: Dispatcher) { const orig = dispatcher[hookName]; dispatcher[hookName] = (...args: any[]) => { const currentFiberHookIndex = trackUseHook(hookName); const [state, dispatch] = orig(...args); let dispatchWrapper = patchedHookFn.get(dispatch); if (dispatchWrapper === undefined) { const hookOwnerFiber = currentFiber as Fiber; const hookOwnerFiberRoot = currentRoot as FiberRoot; dispatchWrapper = { hook: currentFiberHookIndex, fn: value => { // if ( // !currentFiberRerenderState && // currentFiber !== null && // (currentFiber === hookOwnerFiber || // currentFiber?.alternate === hookOwnerFiber) // ) { // currentFiberRerenderState = { // state: currentFiber.memoizedState, // }; // } // console.log(hookName, currentFiberRerenderState); // console.log( // "dispatch", // hookOwnerFiberId, // currentFiber && getOrGenerateFiberId(currentFiber), // window.event?.type // ); // console.dir(new Error()); // if ( // !currentFiber && // !currentEffectFiber && // window.event?.type === "message" // ) { // debugger; // } dispatchCalls.push({ dispatch, dispatchName: hookName === "useState" ? "setState" : "dispatch", root: hookOwnerFiberRoot, fiber: hookOwnerFiber, renderFiber: currentFiber, effectFiber: currentEffectFiber, effectName: currentEffectName, event: (!currentFiber && !currentEffectFiber && window.event?.type) || null, loc: extractCallLoc(0), // stack: String(new Error().stack), }); // console.log("dispatch", new Error().stack, ...args); return dispatch(value); }, }; patchedHookFn.set(dispatch, dispatchWrapper); } return [state, dispatchWrapper.fn]; }; } function patchContextHook(dispatcher: Dispatcher) { const orig = dispatcher.useContext; const hookName = "useContext"; dispatcher[hookName] = (context: ReactContext<any>, ...args: any[]) => { trackUseHook(hookName, null, context); const value = orig(context, ...args); return value; }; } function patchDispatcher(dispatcher: Dispatcher | null) { if (dispatcher && !knownDispatcher.has(dispatcher)) { knownDispatcher.add(dispatcher); // ContextOnlyDispatcher has a single guard function for each hook, // detecting it by comparing two random hooks for equality if (dispatcher.useReducer === dispatcher.useState) { ignoreDispatcherTransition.add(dispatcher); } // In dev mode InvalidNestedHooksDispatcher* are used, that's the only // dispatchers which is changing current dispatcher for another InvalidNestedHooksDispatcher. // Detecting such dispatchers by testing a source of the readContext() method // which has just a single additional call for warnInvalidContextAccess(). // We can't rely on a function name since it can be mangled. else if ( /warnInvalidContextAccess\(\)/.test(dispatcher.readContext.toString()) ) { ignoreDispatcherTransition.add(dispatcher); } patchStateHook("useState", dispatcher); patchStateHook("useReducer", dispatcher); patchMemoHook("useMemo", dispatcher); patchMemoHook("useCallback", dispatcher); patchEffectHook("useEffect", dispatcher); patchEffectHook("useLayoutEffect", dispatcher); patchContextHook(dispatcher); } return dispatcher; } Object.defineProperty(renderer.currentDispatcherRef, "current", { get() { return currentDispatcher; }, set(nextDispatcher: Dispatcher | null) { const nextCurrentFiber = renderer.getCurrentFiber(); const prevDispatcher = currentDispatcher; currentDispatcher = patchDispatcher(nextDispatcher); // render if (nextCurrentFiber !== currentFiber) { currentFiber = nextCurrentFiber; currentFiberCollectInfo = null; currentFiberHookIndex = 0; if (currentFiber !== null) { const alternate = currentFiber.alternate; // collect info on mount only if (alternate === null) { const fiberTypeId = getFiberTypeId(currentFiber.type); if (!fiberTypeInfo.has(fiberTypeId)) { fiberTypeInfo.set( fiberTypeId, (currentFiberCollectInfo = { hooks: [], }) ); } } else { // reset stat on update fiberComputedMemo.delete(currentFiber); } let nextCurrentRoot = fiberRoot.get(currentFiber) || (alternate !== null && fiberRoot.get(alternate)) || null; if (nextCurrentRoot === null) { let cursor = currentFiber.return; while (cursor !== null) { const root = fiberRoot.get(currentFiber); if (root !== undefined) { nextCurrentRoot = root; break; } if (isFiberRoot(cursor)) { nextCurrentRoot = cursor.stateNode as FiberRoot; break; } cursor = cursor.return; } if (nextCurrentRoot !== null) { fiberRoot.set(currentFiber, nextCurrentRoot); } } currentRoot = nextCurrentRoot; } // currentFiberRerenderState = null; // rerenderStates.delete(currentFiber as Fiber); } // re-render else if ( currentFiber !== null && prevDispatcher !== null && nextDispatcher !== null && !ignoreDispatcherTransition.has(prevDispatcher) && !ignoreDispatcherTransition.has(nextDispatcher) ) { // if (currentFiberRerenderState) { // if (rerenderStates.has(currentFiber)) { // rerenderStates.get(currentFiber)?.push(currentFiberRerenderState); // } else { // rerenderStates.set(currentFiber, [currentFiberRerenderState]); // } // } // avoid collecting info on re-renders currentFiberCollectInfo = null; currentFiberHookIndex = 0; } }, }); return { getDispatchHookIndex(dispatch: DispatchFn) { const dispatchWrapper = patchedHookFn.get(dispatch); return dispatchWrapper !== undefined ? dispatchWrapper.hook : null; }, getFiberTypeHookInfo(fiberTypeId: number) { return fiberTypeInfo.get(fiberTypeId)?.hooks || []; }, getFiberComputes(fiber: Fiber) { return fiberComputedMemo.get(fiber) || []; }, getFiberRerenders(fiber: Fiber) { return rerenderStates.get(fiber); }, flushDispatchCalls(root: FiberRoot) { const accepted = []; const rejected = []; for (const dispatchCall of dispatchCalls) { if (dispatchCall.root === root) { accepted.push(dispatchCall); } else { rejected.push(dispatchCall); } } dispatchCalls = rejected; return accepted; }, }; }
the_stack
import { Module } from '@nestjs/common'; import { MulterModule } from '@nestjs/platform-express'; import { SentryModule } from '@ntegral/nestjs-sentry'; import { ServeStaticModule, ServeStaticModuleOptions } from '@nestjs/serve-static'; import { HeaderResolver, I18nJsonParser, I18nModule } from 'nestjs-i18n'; import { LogLevel } from '@sentry/types'; import { Integrations as SentryIntegrations } from '@sentry/node'; import { Integrations as TrackingIntegrations } from '@sentry/tracing'; import { initialize as initializeUnleash } from 'unleash-client'; import { LanguagesEnum } from '@gauzy/contracts'; import { ConfigService, environment } from '@gauzy/config'; import * as path from 'path'; import * as moment from 'moment'; import { CandidateInterviewersModule } from './candidate-interviewers/candidate-interviewers.module'; import { CandidateSkillModule } from './candidate-skill/candidate-skill.module'; import { InvoiceModule } from './invoice/invoice.module'; import { InvoiceItemModule } from './invoice-item/invoice-item.module'; import { TagModule } from './tags/tag.module'; import { SkillModule } from './skills/skill.module'; import { LanguageModule } from './language/language.module'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { UserModule } from './user/user.module'; import { HomeModule } from './home/home.module'; import { EmployeeModule } from './employee/employee.module'; import { RoleModule } from './role/role.module'; import { OrganizationModule } from './organization/organization.module'; import { IncomeModule } from './income/income.module'; import { ExpenseModule } from './expense/expense.module'; import { EmployeeSettingModule } from './employee-setting'; import { EmployeeJobPostModule } from './employee-job'; import { EmployeeAppointmentModule } from './employee-appointment'; import { CoreModule } from './core'; import { AuthModule } from './auth/auth.module'; import { UserOrganizationModule } from './user-organization/user-organization.module'; import { EmployeeStatisticsModule } from './employee-statistics/employee-statistics.module'; import { OrganizationDepartmentModule } from './organization-department/organization-department.module'; import { OrganizationRecurringExpenseModule } from './organization-recurring-expense/organization-recurring-expense.module'; import { EmployeeRecurringExpenseModule } from './employee-recurring-expense/employee-recurring-expense.module'; import { OrganizationContactModule } from './organization-contact/organization-contact.module'; import { OrganizationPositionModule } from './organization-position/organization-position.module'; import { OrganizationProjectModule } from './organization-project/organization-project.module'; import { OrganizationVendorModule } from './organization-vendor/organization-vendor.module'; import { OrganizationTeamModule } from './organization-team/organization-team.module'; import { OrganizationTeamEmployeeModule } from './organization-team-employee/organization-team-employee.module'; import { OrganizationAwardModule } from './organization-award/organization-award.module'; import { OrganizationLanguageModule } from './organization-language/organization-language.module'; import { OrganizationDocumentModule } from './organization-document/organization-document.module'; import { ProposalModule } from './proposal/proposal.module'; import { CountryModule } from './country'; import { CurrencyModule } from './currency'; import { InviteModule } from './invite/invite.module'; import { EmailModule } from './email/email.module'; import { TimeOffPolicyModule } from './time-off-policy/time-off-policy.module'; import { RolePermissionModule } from './role-permission/role-permission.module'; import { TenantModule } from './tenant/tenant.module'; import { EmailTemplateModule } from './email-template/email-template.module'; import { EquipmentModule } from './equipment/equipment.module'; import { EmployeeLevelModule } from './employee-level/employee-level.module'; import { ExportAllModule } from './export-import/export/export-all.module'; import { ImportAllModule } from './export-import/import/import-all.module'; import { TaskModule } from './tasks/task.module'; import { EquipmentSharingModule } from './equipment-sharing/equipment-sharing.module'; import { OrganizationEmploymentTypeModule } from './organization-employment-type/organization-employment-type.module'; import { TimeTrackingModule } from './time-tracking/time-tracking.module'; import { ExpenseCategoriesModule } from './expense-categories/expense-categories.module'; import { UpworkModule } from './upwork/upwork.module'; import { HubstaffModule } from './hubstaff/hubstaff.module'; import { CandidateModule } from './candidate/candidate.module'; import { ProductCategoryModule } from './product-category/product-category.module'; import { ProductTypeModule } from './product-type/product-type.module'; import { ProductModule } from './product/product.module'; import { IntegrationSettingModule } from './integration-setting/integration-setting.module'; import { IntegrationMapModule } from './integration-map/integration-map.module'; import { ProductVariantPriceModule } from './product-variant-price/product-variant-price-module'; import { ProductVariantModule } from './product-variant/product-variant.module'; import { IntegrationEntitySettingModule } from './integration-entity-setting/integration-entity-setting.module'; import { IntegrationEntitySettingTiedModule } from './integration-entity-setting-tied/integration-entity-setting-tied.module'; import { CandidateEducationModule } from './candidate-education/candidate-education.module'; import { CandidateSourceModule } from './candidate-source/candidate-source.module'; import { CandidateDocumentsModule } from './candidate-documents/candidate-documents.module'; import { CandidateExperienceModule } from './candidate-experience/candidate-experience.module'; import { CandidateFeedbacksModule } from './candidate-feedbacks/candidate-feedbacks.module'; import { ProductVariantSettingModule } from './product-setting/product-setting.module'; import { IntegrationModule } from './integration/integration.module'; import { IntegrationTenantModule } from './integration-tenant/integration-tenant.module'; import { CandidateInterviewModule } from './candidate-interview/candidate-interview.module'; import { AppointmentEmployeesModule } from './appointment-employees/appointment-employees.module'; import { ApprovalPolicyModule } from './approval-policy/approval-policy.module'; import { RequestApprovalEmployeeModule } from './request-approval-employee/request-approval-employee.module'; import { RequestApprovalModule } from './request-approval/request-approval.module'; import { EventTypeModule } from './event-types/event-type.module'; import { AvailabilitySlotsModule } from './availability-slots/availability-slots.module'; import { PipelineModule } from './pipeline/pipeline.module'; import { PaymentModule } from './payment/payment.module'; import { CandidatePersonalQualitiesModule } from './candidate-personal-qualities/candidate-personal-qualities.module'; import { StageModule } from './pipeline-stage/pipeline-stage.module'; import { CandidateTechnologiesModule } from './candidate-technologies/candidate-technologies.module'; import { GoalModule } from './goal/goal.module'; import { KeyResultModule } from './keyresult/keyresult.module'; import { RequestApprovalTeamModule } from './request-approval-team/request-approval-team.module'; import { KeyResultUpdateModule } from './keyresult-update/keyresult-update.module'; import { CandidateCriterionsRatingModule } from './candidate-criterions-rating/candidate-criterion-rating.module'; import { GoalTimeFrameModule } from './goal-time-frame/goal-time-frame.module'; import { EstimateEmailModule } from './estimate-email/estimate-email.module'; import { TimeOffRequestModule } from './time-off-request/time-off-request.module'; import { DealModule } from './deal/deal.module'; import { OrganizationSprintModule } from './organization-sprint/organization-sprint.module'; import { GoalKpiModule } from './goal-kpi/goal-kpi.module'; import { GoalGeneralSettingModule } from './goal-general-setting/goal-general-setting.module'; import { EquipmentSharingPolicyModule } from './equipment-sharing-policy/equipment-sharing-policy.module'; import { GoalTemplateModule } from './goal-template/goal-template.module'; import { KeyresultTemplateModule } from './keyresult-template/keyresult-template.module'; import { EmployeeAwardModule } from './employee-award/employee-award.module'; import { InvoiceEstimateHistoryModule } from './invoice-estimate-history/invoice-estimate-history.module'; import { GoalKpiTemplateModule } from './goal-kpi-template/goal-kpi-template.module'; import { TenantSettingModule } from './tenant/tenant-setting/tenant-setting.module'; import { EmployeeJobPresetModule } from './employee-job-preset/employee-job-preset.module'; import { ReportModule } from './reports/report.module'; import { EmployeeProposalTemplateModule } from './employee-proposal-template/employee-proposal-template.module'; import { CustomSmtpModule } from './custom-smtp/custom-smtp.module'; import { FeatureModule } from './feature/feature.module'; import { ImageAssetModule } from './image-asset/image-asset.module'; import { resolveServeStaticPath } from './helper'; import { AccountingTemplateModule } from './accounting-template/accounting-template.module'; import { SeederModule } from './core/seeds/seeder.module'; import { WarehouseModule } from './warehouse/warehouse.module'; import { MerchantModule } from './merchant/merchant.module'; import { GauzyCloudModule } from './gauzy-cloud/gauzy-cloud.module'; const { unleashConfig } = environment; if (unleashConfig.url) { const unleashInstanceConfig = { appName: unleashConfig.appName, url: unleashConfig.url, instanceId: unleashConfig.instanceId, refreshInterval: unleashConfig.refreshInterval, metricsInterval: unleashConfig.metricsInterval }; console.log(`Using Unleash Config: ${JSON.stringify(unleashInstanceConfig)}`); const instance = initializeUnleash(unleashInstanceConfig); // metrics hooks instance.on('registered', (client) => { console.log('Unleash Client Registered'); }); } const sentryIntegrations = []; sentryIntegrations.push( // enable HTTP calls tracing new SentryIntegrations.Http({ tracing: true }) ); if (process.env.DB_TYPE === 'postgres') { sentryIntegrations.push(new TrackingIntegrations.Postgres()); } @Module({ imports: [ ServeStaticModule.forRootAsync({ useFactory: async ( configService: ConfigService ): Promise<ServeStaticModuleOptions[]> => { return await resolveServeStaticPath(configService); }, inject: [ConfigService], imports: [] }), MulterModule.register(), I18nModule.forRoot({ fallbackLanguage: LanguagesEnum.ENGLISH, parser: I18nJsonParser, parserOptions: { path: path.resolve(__dirname, 'i18n/'), watch: !environment.production }, resolvers: [new HeaderResolver(['language'])] }), ...(environment.sentry ? [ SentryModule.forRoot({ dsn: environment.sentry.dns, debug: !environment.production, environment: environment.production ? 'production' : 'development', // TODO: we should use some internal function which returns version of Gauzy release: 'gauzy@' + process.env.npm_package_version, logLevel: LogLevel.Error, integrations: sentryIntegrations, tracesSampleRate: 1.0 }) ] : []), CoreModule, AuthModule, UserModule, HomeModule, EmployeeModule, EmployeeRecurringExpenseModule, EmployeeAwardModule, CandidateModule, CandidateDocumentsModule, CandidateSourceModule, CandidateEducationModule, CandidateExperienceModule, CandidateSkillModule, CandidateFeedbacksModule, CandidateInterviewModule, CandidateInterviewersModule, CandidatePersonalQualitiesModule, CandidateTechnologiesModule, CandidateCriterionsRatingModule, CustomSmtpModule, ExportAllModule, ImportAllModule, EmployeeSettingModule, EmployeeJobPresetModule, EmployeeJobPostModule, EmployeeProposalTemplateModule, EmployeeStatisticsModule, EmployeeAppointmentModule, AppointmentEmployeesModule, RoleModule, OrganizationModule, IncomeModule, ExpenseModule, UserOrganizationModule, OrganizationDepartmentModule, OrganizationRecurringExpenseModule, OrganizationContactModule, OrganizationPositionModule, OrganizationProjectModule, OrganizationVendorModule, OrganizationAwardModule, OrganizationLanguageModule, OrganizationSprintModule, OrganizationTeamModule, OrganizationTeamEmployeeModule, OrganizationDocumentModule, RequestApprovalEmployeeModule, RequestApprovalTeamModule, ProposalModule, EmailModule, EmailTemplateModule, CountryModule, CurrencyModule, InviteModule, TimeOffPolicyModule, TimeOffRequestModule, ApprovalPolicyModule, EquipmentSharingPolicyModule, RequestApprovalModule, RolePermissionModule, TenantModule, TenantSettingModule, TagModule, SkillModule, LanguageModule, InvoiceModule, InvoiceItemModule, PaymentModule, EstimateEmailModule, GoalModule, GoalTimeFrameModule, GoalGeneralSettingModule, KeyResultModule, KeyResultUpdateModule, EmployeeLevelModule, EventTypeModule, AvailabilitySlotsModule, PipelineModule, StageModule, DealModule, InvoiceEstimateHistoryModule, EquipmentModule, EquipmentSharingModule, TaskModule, OrganizationEmploymentTypeModule, TimeTrackingModule, FeatureModule, ReportModule, UpworkModule, HubstaffModule, ExpenseCategoriesModule, ProductCategoryModule, ProductTypeModule, ProductModule, ImageAssetModule, IntegrationModule, IntegrationSettingModule, IntegrationTenantModule, IntegrationMapModule, ProductVariantPriceModule, ProductVariantModule, ProductVariantSettingModule, IntegrationEntitySettingModule, IntegrationEntitySettingTiedModule, GoalKpiModule, GoalTemplateModule, KeyresultTemplateModule, GoalKpiTemplateModule, AccountingTemplateModule, SeederModule, WarehouseModule, MerchantModule, GauzyCloudModule ], controllers: [AppController], providers: [AppService], exports: [] }) export class AppModule { constructor() { // Set Monday as start of the week moment.locale(LanguagesEnum.ENGLISH, { week: { dow: 1 } }); moment.locale(LanguagesEnum.ENGLISH); } }
the_stack
import {Element,Drawing} from "./drawing" import {score_from_midi,score_to_midi} from "./midicompile" import { NOTE_LENGTH,ACCIDENTAL, ORDER_OF_ACCIDENTALS, CLEF,ARTICULATION,CUE,BARLINE,BRACKET, Time_signature,Key_signature, Note_itf, Staff_itf, Rest_itf, Slur_itf, Measure_itf, Score_itf,Cresc_itf,Tempo_itf,Instrument_group_itf, Tuplet_itf, note_name_to_staff_pos, get_note_name_accidental, get_existing_voices, short_id, get_median_staff_pos, } from "./common" import { cue_evade_slur,slur_evade_note,round_polylines, export_mock_svg, hf_drawing_polylines, export_animated_svg, export_svg, export_pdf, export_gif } from "./drawing"; import {export_sketch_svg} from "./fx"; import {Midi_file,Midi_track,Midi_event,parse_midi,export_midi} from "./midifmt" import {parse_txt,export_txt} from "./txtfmt"; import {FONT, get_text_width, register_font} from "./hershey"; export { NOTE_LENGTH,ACCIDENTAL,CLEF,ARTICULATION,CUE,BARLINE,BRACKET, Time_signature,Key_signature, Midi_file,Midi_track,Midi_event,Drawing,Element, Note_itf, Staff_itf, Rest_itf, Slur_itf, Measure_itf, Score_itf, Instrument_group_itf, Tempo_itf, Cresc_itf, Tuplet_itf, parse_midi, score_from_midi, score_to_midi, export_midi, export_animated_svg, export_svg, export_mock_svg, export_pdf,export_gif, export_sketch_svg, round_polylines, parse_txt, export_txt, register_font, }; export const CONFIG : Record<string,any> = { PAGE_WIDTH : 1200, LINE_HEIGHT : 9, NOTE_WIDTH : 12, REST_WIDTH_MUL : 1, CLEF_WIDTH_MUL : 2, TIMESIG_WIDTH_MUL : 2, KEYSIG_WIDTH_MUL : 0.8, ACCIDENTAL_WIDTH_MUL: 1.2, LEDGER_WIDTH_MUL: 0.75, INTER_NOTE_WIDTH : 4, DURATION_BASED_SPACING:0.05, FLAG_SPACING: 0.72, MEASURE_PAD_FRONT : 12, MEASURE_PAD_BACK : 12, INTER_STAFF_HEIGHT : 70, INTER_ROW_HEIGHT : 100, STEM_LENGTH : 2.5, PAGE_MARGIN_X : 100, PAGE_MARGIN_Y : 50, TITLE_TEXT_SIZE : 34, SUBTITLE_TEXT_SIZE : 20, TITLE_LINE_SPACING: 12, TEMPO_COMPOSER_TEXT_SIZE: 14, INSTRUMENT_TEXT_SIZE: 16, MEASURE_NUMBER_TEXT_SIZE: 12, INSTRUMENT_PAD_RIGHT: 20, BEAM_MAX_SLOPE: 0.4, LINES_PER_STAFF : 5, GRACE_WIDTH_MUL: 0.4, LYRIC_SCALE: 0.6, LYRIC_SPACING: 12, CUE_TEXT_SIZE: 22, CUE_HEIGHT: 22, SQUIGGLE_WIDTH_MUL: 1.5, JUSTIFY_ALIGN_MIN: 0.75, SLUR_ARC_MUL:1, SHOW_SOLO_INSTRUMENT: 0, SHOW_MEASURE_NUMBER: 1, HEADBUTT_RESOLVE:1, HEADBUTT_MERGE: 1, CUE_EVADE: 1, SLUR_EVADE: 1, JOIN_STAFF_LINES: 1, TUPLET_LABEL_SPACING: 1.1, WHOLE_HALF_REST_LEDGERS:0, TIMESIG_COMMON_TIME_C: 0, BEAM_POLICY: 3, DEBUG_BLOCKS: 0, }; const NOTE_LENGTH_MODIFIER = 1.5; const FONT_INHERENT_HEIGHT = 24; function CONTENT_WIDTH(){ return CONFIG.PAGE_WIDTH-CONFIG.PAGE_MARGIN_X*2; } interface Note extends Note_itf{ stem_len: number; flag_count: number; twisted : boolean; beamed : boolean; articulation_pos? : [number,number]; slot_shift: number; modifier_shift: number; }; interface Beam extends Array<number>{ m: number; b: number; } interface Staff extends Staff_itf{ notes: Note[]; rests: Rest[]; grace: Measure[]; beams: Beam[]; coords:{x:number,y:number,w:number,local_y_min:number,local_y_max:number,col:number,row:number}, flags: { need_keysig:{accidental:number,count:number}|null,need_timesig:boolean,need_clef:boolean need_lyric:boolean,need_cue:boolean, } } interface Measure extends Measure_itf{ staves: Staff[]; slots: Slot[]; is_first_col:boolean; is_last_col:boolean; pad: {left:number,right:number,inter:number}; } interface Rest extends Rest_itf{ staff_pos: number; } interface Score extends Score_itf{ indent:number; first_col_measure_indices:number[]; measures: Measure[]; slurred_ids:Record<string,boolean>; } interface Note_register{ note: Note; staff_idx: number; measure: Measure; row: number; col: number; chord_head_x:number; chord_head_y:number; head_x:number; head_y:number; tail_x:number; tail_y:number; } let id_registry : Record<string,Note_register> = {}; function staff_has_cue_lyric(staff:Staff,crescs:Cresc_itf[]=null):void{ let has_cue = false; for (let i = 0; i < staff.notes.length; i++){ if (staff.notes[i].cue){ has_cue = true; break; } } if (!has_cue){ for (let i = 0; i < staff.rests.length; i++){ if (staff.rests[i].cue){ has_cue = true; break; } } } if (!has_cue && crescs && crescs.length){ for (let i = 0; i < staff.notes.length; i++){ if (staff.notes[i].id){ for (let j = 0; j < crescs.length; j++){ if (crescs[j].left == staff.notes[i].id || crescs[j].right == staff.notes[i].id){ has_cue = true; break; } } if (has_cue){ break; } } } } let has_lyric = false; for (let i = 0; i < staff.notes.length; i++){ if (staff.notes[i].lyric){ has_lyric = true; break; } } staff.flags.need_cue = has_cue; staff.flags.need_lyric = has_lyric; } function calc_staff_flags(score:Score,measure_idx:number,staff_idx:number){ let measures = score.measures; if (measure_idx != 0){ let ks0 = measures[measure_idx-1].staves[staff_idx].key_signature; let ks1 = measures[measure_idx].staves[staff_idx].key_signature; if (ks0[0] != ks1[0] || ks0[1] != ks1[1]){ let [acc0, num_acc0] = ks0; let [acc1, num_acc1] = ks1; if (num_acc0 > 0 && num_acc1 == 0){ measures[measure_idx].staves[staff_idx].flags.need_keysig = { accidental:~acc0, count:num_acc0 }; }else{ measures[measure_idx].staves[staff_idx].flags.need_keysig = { accidental:acc1, count:num_acc1 }; } } let ts0 = measures[measure_idx-1].staves[staff_idx].time_signature; let ts1 = measures[measure_idx].staves[staff_idx].time_signature; if (ts0[0] != ts1[0] || ts0[1] != ts1[1]){ measures[measure_idx].staves[staff_idx].flags.need_timesig = true; } if (measures[measure_idx-1].staves[staff_idx].clef != measures[measure_idx].staves[staff_idx].clef){ measures[measure_idx].staves[staff_idx].flags.need_clef= true; } }else{ let [acc, num_acc] = measures[measure_idx].staves[staff_idx].key_signature; measures[measure_idx].staves[staff_idx].flags.need_keysig = { accidental:acc, count:num_acc }; measures[measure_idx].staves[staff_idx].flags.need_timesig = true; measures[measure_idx].staves[staff_idx].flags.need_clef = true; } staff_has_cue_lyric(measures[measure_idx].staves[staff_idx],score.crescs); } function has_twisted_sibling(notes:Note[],idx:number) : boolean{ let note = notes[idx]; let does = note.twisted; if (does) return does; let head_note : Note = note; let tail_note : Note = note; while (head_note.prev_in_chord != null){ head_note = notes[head_note.prev_in_chord]; if (head_note.twisted) does = true; } if (does) return does; while (tail_note.next_in_chord != null){ tail_note = notes[tail_note.next_in_chord]; if (tail_note.twisted) does = true; } return does; } function compile_measure(measure:Measure){ function get_index_in_chord(notes:Note_itf[],note:Note_itf){ let i = 0; while (note.prev_in_chord !== null){ note = notes[note.prev_in_chord]; i++; } return i; } for (let j = 0; j < measure.staves.length; j++){ let staff = measure.staves[j] as Staff; if (!staff.coords){ staff.coords = {x:0,y:0,w:0,local_y_min:0,local_y_max:0,col:0,row:0}; } if (!staff.flags){ staff.flags = {need_keysig:null,need_timesig:false,need_clef:false,need_cue:false,need_lyric:false}; } // calc_staff_flags(score.measures as Measure[],i,j); for (let b of staff.beams){ for (let k of b){ (staff.notes[k] as Note).beamed = true; } } for (let k = 0; k < staff.notes.length; k++){ let note = staff.notes[k] as Note; let twisted : boolean = false; let stem_len : number = CONFIG.STEM_LENGTH; let stem_dir : number = note.stem_dir; // if (stem_dir == -1){ // stem_len = Math.max( // stem_len, // ~~((note.staff_pos-3)/2) // ); // }else{ // stem_len = Math.max( // stem_len, // ~~((7-note.staff_pos)/2) // ); // } let flag_count = 0; if (note.prev_in_chord !== null){ let pd = note.staff_pos-staff.notes[note.prev_in_chord].staff_pos; if (Math.abs(pd) <= 1){ if (get_index_in_chord(staff.notes,note) % 2){ twisted = true; } } } if (note.next_in_chord !== null){ let pd = note.staff_pos-staff.notes[note.next_in_chord].staff_pos; if (!twisted && Math.abs(pd) <= 1){ if (get_index_in_chord(staff.notes,note) % 2){ twisted = true; } } stem_len = Math.abs(pd)/2; }else{ if (note.tuplet){ flag_count = calc_num_flags(note.tuplet.display_duration,note.modifier); }else{ flag_count = calc_num_flags(note.duration,note.modifier); } } stem_len += flag_count*CONFIG.FLAG_SPACING/2; note.stem_len = stem_len; note.flag_count = flag_count; note.twisted = twisted; note.slot_shift = 0; note.modifier_shift = 0; } let beams = staff.beams; for (let b of beams){ let notes_spanned = []; for (let i = 0; i < b.length; i++){ notes_spanned.push(staff.notes[b[i]]) } if (!notes_spanned.length){ continue; } let flagcnts = []; for (let i = 0; i < notes_spanned.length; i++){ flagcnts.push(notes_spanned[i].flag_count); } let extra_len = Math.max(0,Math.max(...flagcnts)-1)*CONFIG.FLAG_SPACING; for (let i = 0; i < notes_spanned.length; i++){ notes_spanned[i].stem_len += extra_len - notes_spanned[i].flag_count*CONFIG.FLAG_SPACING/6; } } compile_rests(staff); } for (let j = 0; j < measure.staves.length; j++){ let staff = measure.staves[j] as Staff; for (let i = 0; i < staff.grace.length; i++){ if (staff.grace[i]){ compile_measure(staff.grace[i]); let st = staff.grace[i].staves[0]; for (let j = 0; j < st.notes.length; j++){ if (st.notes[j].next_in_chord == null){ st.notes[j].stem_len*=0.6; } } // staff.grace[i].pad={left:CONFIG.INTER_NOTE_WIDTH,inter:0,right:CONFIG.INTER_NOTE_WIDTH} staff.grace[i].pad = {left:0,inter:CONFIG.INTER_NOTE_WIDTH/2,right:0}; } } } measure.pad = {left:CONFIG.MEASURE_PAD_FRONT,inter:CONFIG.INTER_NOTE_WIDTH,right:CONFIG.MEASURE_PAD_BACK}; make_measure_slots(measure); if (CONFIG.HEADBUTT_RESOLVE){ for (let j = 0; j < measure.staves.length; j++){ let staff = measure.staves[j]; for (let k = 0; k < staff.notes.length; k++){ let staff_idx =j; let note_idx = k; let note = staff.notes[k]; let slot = measure.slots[note.begin]; function try_opt_headbutt(){ if (staff.voices <= 1 || slot.mid_note <= 1 || has_twisted_sibling(staff.notes,k)){ return; } let track = slot.mid_pack.intervals[staff_idx]; let entry = track.find(a=>a.idx==note_idx); if (entry.x > 0){ return; } let collider : Note = null; for (let j = 0; j < track.length; j++){ if (track[j].idx == entry.idx) continue; if (interval_overlap(track[j].top,track[j].bottom,entry.top,entry.bottom)){ if (collider){ return; //giveup }else{ collider = staff.notes[track[j].idx]; } } } if (collider){ return; } if (note.stem_dir < 0){ note.slot_shift = -CONFIG.NOTE_WIDTH; note.modifier_shift = -CONFIG.NOTE_WIDTH; }else{ note.modifier_shift = -CONFIG.NOTE_WIDTH; } } try_opt_headbutt(); } } } } function make_space_for_barlines(measures:Measure[]){ for (let i = 0; i < measures.length; i++){ let measure = measures[i]; if (measure.barline == BARLINE.DOUBLE){ measure.pad.right += 4; }else if (measure.barline == BARLINE.END){ measure.pad.right += 8; }else if (measure.barline == BARLINE.REPEAT_END){ measure.pad.right += 12; }else if (measure.barline == BARLINE.REPEAT_BEGIN){ measures[i+1].pad.left += 12; }else if (measure.barline == BARLINE.REPEAT_END_BEGIN){ measure.pad.right += 12; measures[i+1].pad.left += 12; } } } function plan_beams(measure:Measure,staff_idx:number){ let staff = measure.staves[staff_idx]; let beams = staff.beams; let notes = staff.notes; let slots = measure.slots; for (let beam of beams){ let notes_spanned = []; for (let i = 0; i < beam.length; i++){ notes_spanned.push(notes[beam[i]]) } if (!notes_spanned.length){ continue; } let stem_dir = notes_spanned[0].stem_dir; let pts : {x:number,y:number}[] = notes_spanned.map(n=>{ let stem_length = n.stem_len; let x = slot_pos(measure,n.begin)+CONFIG.NOTE_WIDTH*(Number(n.stem_dir<0)*slots[n.begin].mid_note); return {x,y:on_staff(2*stem_dir*stem_length+n.staff_pos)}; }); let [m,b]:[number,number] = least_sq_regress(pts); if (Math.abs(m) > CONFIG.BEAM_MAX_SLOPE){ m = Math.sign(m)*CONFIG.BEAM_MAX_SLOPE; let anchor : {x:number,y:number}; if (stem_dir < 0){ anchor = pts.reduce((acc:{x:number,y:number},a:{x:number,y:number}):{x:number,y:number}=>(a.y<=acc.y?a:acc),{x:0,y:Infinity}); }else{ anchor = pts.reduce((acc:{x:number,y:number},a:{x:number,y:number}):{x:number,y:number}=>(a.y>=acc.y?a:acc),{x:0,y:-Infinity}); } // m*x+b=y b=y-m*x b = anchor.y-m*anchor.x; } for (let i = 0; i < notes_spanned.length; i++){ let d = (pts[i].x*m+b) - on_staff(notes_spanned[i].staff_pos); if (Math.sign(d) != notes_spanned[i].stem_dir){ b -= d; d = (pts[i].x*m+b) - on_staff(notes_spanned[i].staff_pos); } if (Math.abs(d) < CONFIG.LINE_HEIGHT*1.5){ b += notes_spanned[i].stem_dir * CONFIG.LINE_HEIGHT*1.5; } } for (let i = 0; i < notes_spanned.length; i++){ let d = (pts[i].x*m+b) - on_staff(notes_spanned[i].staff_pos); notes_spanned[i].stem_len = Math.abs(d)/CONFIG.LINE_HEIGHT; } beam.m = m; beam.b = b; } } function plan_articulations(measure:Measure,staff_idx:number){ let staff = measure.staves[staff_idx]; for (let k = 0; k < staff.notes.length; k++){ let note = staff.notes[k] as Note; if (note.articulation && note.articulation != ARTICULATION.ARPEGGIATED){ let head_note : Note = note; let tail_note : Note = note; while (head_note.prev_in_chord != null){ head_note = staff.notes[head_note.prev_in_chord]; } while (tail_note.next_in_chord != null){ tail_note = staff.notes[tail_note.next_in_chord]; } let lh = head_note.staff_pos; let lt = tail_note.staff_pos; let ya = ((lh % 2 ? lh : lh-note.stem_dir)-note.stem_dir*2); let line_b = Math.round(lt+(note.stem_len*note.stem_dir)*2); let yb = ((line_b % 2 ? line_b : line_b+note.stem_dir)+note.stem_dir*2); let xa = 0; let xb = 1; let x:number, y:number; if (staff.voices <= 1){ if (note.articulation == ARTICULATION.TRILL){ [x,y] = note.stem_dir < 0 ? [xb,yb] : [xa,ya]; }else{ [x,y] = [xa,ya]; } }else if (note.voice % 2){ if (note.stem_dir < 0){ [x,y] = [xa,ya]; }else{ [x,y] = [xb,yb]; } }else{ if (note.stem_dir < 0){ [x,y] = [xb,yb]; }else{ [x,y] = [xa,ya]; } } note.articulation_pos = [x,y]; } } } export function compile_score(score:Score_itf):Score{ let score_ : Score = score as Score; score_.indent = 0; let instr_set : Set<string> = new Set(); for (let i = 0; i < score.instruments.length; i++){ for (let j = 0; j < score.instruments[i].names.length; j++){ instr_set.add(score.instruments[i].names[j]); } } let instrs : string[] = Array.from(instr_set); if (instrs.length > 1 || CONFIG.SHOW_SOLO_INSTRUMENT){ let w = 0; for (let i = 0; i < instrs.length; i++){ w = Math.max(w,get_text_width(instrs[i],FONT.DUPLEX,-2)); } w *= CONFIG.INSTRUMENT_TEXT_SIZE/FONT_INHERENT_HEIGHT; score_.indent = w+CONFIG.INSTRUMENT_PAD_RIGHT; } score_.first_col_measure_indices = []; score_.slurred_ids = {}; for (let i = 0; i < score_.slurs.length; i++){ score_.slurred_ids[score_.slurs[i].left] = true; score_.slurred_ids[score_.slurs[i].right] = true; } for (let i = 0; i < score_.measures.length; i++){ let measure = score_.measures[i] as Measure; for (let j = 0; j < measure.staves.length; j++){ let staff = measure.staves[j] as Staff; staff.flags = {need_keysig:null,need_timesig:false,need_clef:false,need_cue:false,need_lyric:false}; calc_staff_flags(score_,i,j); } compile_measure(measure); } make_space_for_barlines(score_.measures); plan_measures(score_); return score_; } function least_sq_regress(pts:{x:number,y:number}[]):[number,number]{ let sum_x = 0 let sum_y = 0 let sum_xsq = 0 let sum_xy = 0 let n = pts.length; for (let p of pts){ sum_x += p.x; sum_y += p.y; sum_xsq += p.x**2; sum_xy += p.x * p.y; } let denom = (n * sum_xsq - sum_x**2); if (denom == 0){ denom = 0.0001; } let m = (n * sum_xy - sum_x * sum_y)/denom; let b = (sum_y - m * sum_x)/n; return [m,b]; } interface Slot{ acc_pack: Pack; mid_pack: Pack; mid_note: number; left_grace: number; left_squiggle: number; left_deco: number; left_note: number; right_note: number; right_deco: number; right_spacing: number; } interface Pack_interval{ x:number; top: number; bottom: number; idx: number; } interface Pack{ intervals: Pack_interval[][]; } function interval_overlap(x1:number,x2:number,y1:number,y2:number):boolean{ return x1 < y2 && y1 < x2; } function pack_add(pack:Pack,idx:number,layer:number,top:number,bottom:number,exemption?:Function){ if (!exemption){ exemption = (_a:number,_b:number)=>false; } if (!pack.intervals[layer]){ pack.intervals[layer] = []; } let track = pack.intervals[layer]; for (let i = 0; i < 99; i++){ let ok = true; for (let j = 0; j < track.length; j++){ if (track[j].x != i){ continue; } if (interval_overlap(track[j].top,track[j].bottom,top,bottom) && !(track[j].top==top && track[j].bottom==bottom && exemption(idx,j))){ ok = false; break; } } if (ok){ track.push({top,bottom,x:i,idx}); return; } } } function pack_width(pack:Pack):number{ let x = 0; for (let i = 0; i < pack.intervals.length; i++){ if (!pack.intervals[i]) continue; for (let j = 0; j < pack.intervals[i].length; j++){ x = Math.max(pack.intervals[i][j].x+1,x); } } return x; } function make_measure_slots(measure:Measure):void{ let slots : Slot[] = new Array(Math.max(1,measure.duration)).fill(null).map(x=>({ mid_note:0, left_grace:0, left_squiggle:0, left_deco: 0, right_deco: 0, left_note: 0, right_note: 0, right_spacing:0, acc_pack:{intervals:new Array(measure.staves.length).fill(null).map(_=>[])}, mid_pack:{intervals:new Array(measure.staves.length).fill(null).map(_=>[])} })); for (let k = 0; k < measure.staves.length; k++){ let notes : Note[] = measure.staves[k].notes; let rests = measure.staves[k].rests; function merger(a:number,b:number) : boolean{return ( (notes[a].duration < NOTE_LENGTH.HALF && notes[b].duration < NOTE_LENGTH.HALF) || (NOTE_LENGTH.HALF <= notes[a].duration && notes[a].duration < NOTE_LENGTH.WHOLE && NOTE_LENGTH.HALF <= notes[b].duration && notes[b].duration < NOTE_LENGTH.WHOLE) )} for (let i = 0; i < notes.length; i++){ let slot = slots[notes[i].begin]; // console.dir(measure,{depth:null}); if (notes[i].stem_dir < 0){ if (notes[i].twisted){ slot.right_note = 1; }else{ // slot.mid_note = Math.max(slot.mid_note,1); slot.mid_note=1; pack_add(slot.mid_pack,i,k,notes[i].staff_pos-1,notes[i].staff_pos+1,CONFIG.HEADBUTT_MERGE&&merger); } }else{ if (notes[i].twisted){ slot.left_note = 1; }else{ // slot.mid_note = Math.max(slot.mid_note,1); slot.mid_note=1; pack_add(slot.mid_pack,i,k,notes[i].staff_pos-1,notes[i].staff_pos+1,CONFIG.HEADBUTT_MERGE&&merger); } } if (notes[i].modifier){ slot.right_deco = Math.max(1,slot.right_deco); } if (notes.length > 1){ let v = CONFIG.DURATION_BASED_SPACING*notes[i].duration; if (!slot.right_spacing){ slot.right_spacing = v; }else{ slot.right_spacing = Math.min(v,slot.right_spacing); } } if ( (notes[i].flag_count) && (!notes[i].beamed) && notes[i].stem_dir < 0 && !notes[i].twisted){ slot.right_deco = Math.max(1,slot.right_deco); } if (notes[i].articulation == ARTICULATION.ARPEGGIATED){ slot.left_squiggle = CONFIG.SQUIGGLE_WIDTH_MUL; } if (notes[i].accidental !== null){ pack_add(slot.acc_pack,i,k,notes[i].staff_pos-3,notes[i].staff_pos+2); // slot.left_deco = Math.max(CONFIG.ACCIDENTAL_WIDTH_MUL,slot.left_deco); } } for (let i = 0; i < rests.length; i++){ let slot = slots[rests[i].begin]; slot.mid_note = Math.max(slot.mid_note,CONFIG.REST_WIDTH_MUL); } for (let i = 0; i < measure.staves[k].grace.length; i++){ if (measure.staves[k].grace[i]){ let slot = slots[i]; let d : [number,number,number] = [0,0,0]; slot_pos(measure.staves[k].grace[i],measure.staves[k].grace[i].duration,d); slot.left_grace = d[0]*CONFIG.GRACE_WIDTH_MUL+d[1]*measure.staves[k].grace[i].pad.inter/CONFIG.NOTE_WIDTH; } } if (!notes.length){ slots[0].mid_note = Math.max(slots[0].mid_note,CONFIG.REST_WIDTH_MUL); } } for (let i = 0; i < slots.length; i++){ // console.log(JSON.stringify(slots[i].acc_pack)); slots[i].left_deco = (pack_width(slots[i].acc_pack))*CONFIG.ACCIDENTAL_WIDTH_MUL; } for (let i = 0; i < slots.length; i++){ // console.log(JSON.stringify(slots[i].mid_pack)); slots[i].mid_note = Math.max(slots[i].mid_note, (pack_width(slots[i].mid_pack))*1 ); } let lyric_slots : boolean[] = new Array(slots.length).fill(false); for (let k = 0; k < measure.staves.length; k++){ let notes : Note[] = measure.staves[k].notes; for (let i = 0; i < notes.length; i++){ if (notes[i].lyric){ lyric_slots[notes[i].begin] = true; } } } for (let k = 0; k < measure.staves.length; k++){ let notes : Note[] = measure.staves[k].notes; for (let i = 0; i < notes.length; i++){ if (notes[i].lyric){ let slot = slots[notes[i].begin]; let w = get_text_width(notes[i].lyric)*CONFIG.LYRIC_SCALE; let w0 = (slot.mid_note + slot.right_note + slot.right_deco + slot.right_spacing)*CONFIG.NOTE_WIDTH; let n = notes[i].begin+1; while (!lyric_slots[n] && n < lyric_slots.length){ let ww = slots[n].left_deco + slots[n].left_grace + slots[n].left_note + slots[n].left_squiggle + slots[n].mid_note + slots[n].right_deco + slots[n].right_note + slots[n].right_spacing; if (ww){ w0 += CONFIG.INTER_NOTE_WIDTH; } w0 += ww * CONFIG.NOTE_WIDTH; n++; } if (w0 < w){ let due = (w-w0)/CONFIG.NOTE_WIDTH; let spread = due / (n - notes[i].begin); for (let m = notes[i].begin; m < n; m++){ slots[m].right_spacing += spread; } } // console.log(w,slot); } } } measure.slots = slots; } function slot_pos(measure:Measure,begin:number,out?:[number,number,number]):number{ let slots = measure.slots; let r : number = 0; let s : number = measure.pad.left; let t : number = 0; if (measure.staves.some(x=>x.flags.need_clef)){ s += CONFIG.CLEF_WIDTH_MUL * CONFIG.NOTE_WIDTH; t++; s += measure.pad.inter; } if (measure.staves.some(x=>x.flags.need_timesig)){ s += CONFIG.TIMESIG_WIDTH_MUL * CONFIG.NOTE_WIDTH; t++; s += measure.pad.inter; } if (measure.staves.some(x=>x.flags.need_keysig)){ let num_acc = 0; for (let i = 0; i < measure.staves.length; i++){ num_acc = Math.max(num_acc,measure.staves[i].key_signature[1]); } s += num_acc * CONFIG.KEYSIG_WIDTH_MUL * CONFIG.NOTE_WIDTH; t++; s += measure.pad.inter; } for (let i = 0; i < begin; i++){ if (slots[i].left_grace){ s += measure.pad.inter*2 ; r += slots[i].left_grace; t+=2; } let w_real = slots[i].left_note+slots[i].right_note+slots[i].mid_note+slots[i].left_deco+slots[i].right_deco+slots[i].left_squiggle; let w = w_real + slots[i].right_spacing; r += w; if (w_real){ s += measure.pad.inter; t++; } } if (slots[begin]){ if (slots[begin].left_grace){ s += measure.pad.inter*2 ; r += slots[begin].left_grace; t+=2; } r += slots[begin].left_note + slots[begin].left_deco + slots[begin].left_squiggle; }else if (begin>=slots.length){ s += measure.pad.right-measure.pad.inter; t--; }else if (begin<0){ s -= measure.pad.left; } if (out){ out[0] = r; out[1] = t; out[2] = s; } return r * CONFIG.NOTE_WIDTH + s; } function on_staff(line:number):number{ return line*CONFIG.LINE_HEIGHT/2; } function estimate_staff_ybound(staff:Staff,slurred_ids:Record<string,boolean>):[number,number]{ let ymin = 0; let ymax = (CONFIG.LINES_PER_STAFF-1)*2; for (let i = 0; i < staff.notes.length; i++){ let note = staff.notes[i]; let line = note.staff_pos; let y0 = line; let y1 = y0; if (note.stem_dir<0){ y0 -= note.stem_len*2; }else{ y1 += note.stem_len*2; } if (note.tuplet){ if (note.stem_dir<0){ y0 -= 3; }else{ y1 += 3; } } if (note.articulation_pos){ y0=Math.min(y0,note.articulation_pos[1]-2); y1=Math.max(y1,note.articulation_pos[1]+2); } if (note.id && slurred_ids[note.id]){ y0-=2; y1+=2; } y0 -= 1; y1 += 1; ymin = Math.min(ymin,y0); ymax = Math.max(ymax,y1); } for (let i = 0; i < staff.rests.length; i++){ let rest = staff.rests[i]; ymin = Math.min(ymin,rest.staff_pos-2); ymax = Math.max(ymax,rest.staff_pos+2); } let ya = on_staff(ymin); let yb = on_staff(ymax); let {need_cue,need_lyric} = staff.flags; let yc = (need_cue?CONFIG.CUE_HEIGHT:0); let yd = (need_lyric?(FONT_INHERENT_HEIGHT * CONFIG.LYRIC_SCALE + CONFIG.LYRIC_SPACING*2):0); return [ya,yb+yc+yd]; } function calc_num_flags(length:number, has_modifier:boolean):number{ return Math.max(0,~~(4 - Math.log2((!has_modifier) ? length : length/NOTE_LENGTH_MODIFIER))); } function compile_rests(staff:Staff){ let voice_median_staff_pos = get_median_staff_pos(staff.notes); let notes = staff.notes; let rests = staff.rests; function rest_staff_pos(rest:Rest) : number{ let y : number; if (staff.voices <= 1){ y = 4; }else if (staff.voices == 2){ if (voice_median_staff_pos[rest.voice] == undefined){ if (rest.voice){ y = 8; }else{ y = 0; } }else{ let other_voice = (rest.voice+1)%staff.voices; if ( // (voice_median_staff_pos[other_voice] < voice_median_staff_pos[rest.voice]) || // ( // voice_median_staff_pos[other_voice] == voice_median_staff_pos[rest.voice] && other_voice < rest.voice // ) ){ y = voice_median_staff_pos[rest.voice]+4; for (let i = 0; i < notes.length;i++){ if (notes[i].voice != other_voice){ continue; } if (notes[i].begin == rest.begin){ y = Math.max(y,5+notes[i].staff_pos); } } y = (~~(y/2))*2; }else { y = voice_median_staff_pos[rest.voice]-4; for (let i = 0; i < notes.length;i++){ if (notes[i].voice != other_voice){ continue; } if (notes[i].begin == rest.begin){ y = Math.min(y,-5+notes[i].staff_pos); } } y = (~~(y/2))*2; } // console.log(rest.channel,other_channel,channel_average_staff,y); } }else{ y = voice_median_staff_pos[rest.voice]; } return y; } for (let i = 0; i < rests.length; i++){ rests[i].staff_pos = rest_staff_pos(rests[i]); } } function draw_staff(measure:Measure, staff_idx:number,no_staff_lines:boolean=false) : Element[] { let staff = measure.staves[staff_idx]; let notes = staff.notes; let rests = staff.rests; let result : Element[] = []; let slots : Slot[] = measure.slots; let ledgers : Set<number>[] = new Array(measure.duration).fill(null).map(_=>new Set()); function put_ledgers_as_necessary(begin:number,line:number){ if (line < 0){ for (let i = Math.floor((line+1)/2)*2; i < 0; i += 2){ ledgers[begin].add(i); } }else if (line > 9){ for (let i = 10; i < ~~(line/2)*2+1; i+=2){ ledgers[begin].add(i); } } } function draw_ledgers(){ for (let i = 0; i < ledgers.length; i++){ let slot = slots[i]; let slot_x = slot_pos(measure,i); for (let line of ledgers[i]){ result.push({ tag:'line', type:'ledger', x:slot_x-slot.left_note*CONFIG.NOTE_WIDTH-(CONFIG.LEDGER_WIDTH_MUL/2)*CONFIG.NOTE_WIDTH, y:on_staff(line), w:CONFIG.NOTE_WIDTH*(CONFIG.LEDGER_WIDTH_MUL+slot.left_note+slot.mid_note+slot.right_note), h:0, }) } }; } function note_head_center_x(note:Note,slot_x:number){ let slot = slots[note.begin]; let x : number = slot_x+CONFIG.NOTE_WIDTH*(Number(note.stem_dir<0)*slot.mid_note); if (note.stem_dir < 0){ if (note.twisted){ x += CONFIG.NOTE_WIDTH/2; }else{ x -= CONFIG.NOTE_WIDTH/2; } }else{ if (note.twisted){ x -= CONFIG.NOTE_WIDTH/2; }else{ x += CONFIG.NOTE_WIDTH/2; } } return x; } function draw_note(note:Note,slot_x:number,line:number){ let slot = slots[note.begin]; let head_note : Note = note; let tail_note : Note = note; let modifier_x = slot_x+CONFIG.NOTE_WIDTH*(slot.mid_note+slot.right_note+0.5); slot_x += note.slot_shift; modifier_x += note.modifier_shift; while (head_note.prev_in_chord != null){ head_note = notes[head_note.prev_in_chord]; } while (tail_note.next_in_chord != null){ tail_note = notes[tail_note.next_in_chord]; } if (note.id){ let x : number = slot_x+CONFIG.NOTE_WIDTH*(Number(note.stem_dir<0)*slot.mid_note); let reg : Note_register = { note, staff_idx, measure, row: null, col: null, chord_head_x:note_head_center_x(head_note,slot_x), chord_head_y:on_staff(head_note.staff_pos), head_x:note_head_center_x(note,slot_x), tail_x:x, head_y:on_staff(note.staff_pos), tail_y:null, }; let n = note; while (n.next_in_chord !== null){ n = staff.notes[n.next_in_chord]; } let y1 = on_staff(n.staff_pos); y1 += n.stem_len*n.stem_dir*CONFIG.LINE_HEIGHT; reg.tail_y = y1; reg.chord_head_x += staff.coords.x; reg.chord_head_y += staff.coords.y; reg.head_x += staff.coords.x; reg.head_y += staff.coords.y; reg.tail_x += staff.coords.x; reg.tail_y += staff.coords.y; reg.row = staff.coords.row; reg.col = staff.coords.col; id_registry[note.id] = reg; } if (note.modifier){ result.push({ tag:'dot', type:'modifier', x:modifier_x, y:on_staff(line % 2 ? line : (line+ ((note.voice % 2)?1:-1))), w:0, h:0, }) } if (note.articulation){ if (note.articulation != ARTICULATION.ARPEGGIATED){ let [xx,yy] = note.articulation_pos; let x = xx ? (slot_x+CONFIG.NOTE_WIDTH*(Number(note.stem_dir<0)*slot.mid_note)) : note_head_center_x(note,slot_x); let y = on_staff(yy); result.push({ tag:'articulation', type:note.articulation, dir:(xx?-1:1)*note.stem_dir, x:x, y:y, w:CONFIG.NOTE_WIDTH, h:CONFIG.LINE_HEIGHT, }); }else{ let lh = head_note.staff_pos; let lt = tail_note.staff_pos; let ya = on_staff(lh-note.stem_dir); // let line_b = Math.round(lt+(note.stem_len*note.stem_dir)*2); let line_b = Math.round(lt+note.stem_dir); let yb = on_staff(line_b); let y0 = Math.min(ya,yb); let y1 = Math.max(ya,yb); result.push({ tag:'squiggle', type:'arpeggiated_chord', x:slot_x-(slot.left_deco+slot.left_note+slot.left_squiggle/2)*CONFIG.NOTE_WIDTH, y:y0, w:0, h:y1-y0, }); } } result.push({ tag:'note_head', x:slot_x+CONFIG.NOTE_WIDTH*(Number(note.stem_dir<0)*slot.mid_note), y:on_staff(line), w:CONFIG.NOTE_WIDTH, h:CONFIG.LINE_HEIGHT, twisted:note.twisted, stem_dir:note.stem_dir, duration:note.duration, }) if (!note.beamed && note.stem_len != 0 && note.duration < NOTE_LENGTH.WHOLE){ let y0 = note.stem_len*note.stem_dir; let y1 = 0; let y = y0; let h = y1-y; result.push({ tag:'line', type:'note_stem', x:slot_x+CONFIG.NOTE_WIDTH*(Number(note.stem_dir<0)*slot.mid_note), y:on_staff(line+y*2), w:0, h:CONFIG.LINE_HEIGHT*h, }) } if (!note.beamed && note.flag_count){ let flagcnt = note.flag_count; for (let i = 0; i < flagcnt; i++){ let y = (note.stem_len-i* CONFIG.FLAG_SPACING) * note.stem_dir * 2 ; result.push({ tag:'flag', x:slot_x+CONFIG.NOTE_WIDTH*(Number(note.stem_dir<0)*slot.mid_note), y:on_staff(line+y), w:CONFIG.NOTE_WIDTH, h:CONFIG.LINE_HEIGHT, stem_dir:note.stem_dir, is_last: i == flagcnt-1, }) } } } function draw_accidental(acc:number,slot_x:number,line:number){ result.push({ tag:'accidental', type:acc, x:slot_x, y:on_staff(line), w:CONFIG.NOTE_WIDTH, h:CONFIG.LINE_HEIGHT, }) } function draw_rest(rest:Rest,slot_x:number){ let dur = rest.duration; if (rest.tuplet){ dur = rest.tuplet.display_duration; } let y : number = rest.staff_pos; if (CONFIG.WHOLE_HALF_REST_LEDGERS){ if (dur == NOTE_LENGTH.WHOLE){ // put_ledgers_as_necessary(rest.begin,y-2); let slot = slots[rest.begin]; let line = y-2; result.push({ tag:'line', type:'ledger', x:slot_x-slot.left_note*CONFIG.NOTE_WIDTH-0.5*CONFIG.NOTE_WIDTH, y:on_staff(line), w:CONFIG.NOTE_WIDTH*(1+slot.left_note+slot.mid_note+slot.right_note), h:0, }) }else if (dur == NOTE_LENGTH.HALF){ // put_ledgers_as_necessary(rest.begin,y); let slot = slots[rest.begin]; let line = y; result.push({ tag:'line', type:'ledger', x:slot_x-slot.left_note*CONFIG.NOTE_WIDTH-0.5*CONFIG.NOTE_WIDTH, y:on_staff(line), w:CONFIG.NOTE_WIDTH*(1+slot.left_note+slot.mid_note+slot.right_note), h:0, }) } }else if (dur == NOTE_LENGTH.WHOLE || dur == NOTE_LENGTH.HALF){ y = Math.min(Math.max(y,2),8); } let line = on_staff(y); result.push({ tag:'rest', x:slot_x+CONFIG.NOTE_WIDTH/2, y:line, w:CONFIG.NOTE_WIDTH, h:CONFIG.LINE_HEIGHT*(CONFIG.LINES_PER_STAFF-1), duration:dur, }) } function draw_beam(notes_spanned:Note[]){ if (!notes_spanned.length){ return; } let beat_length = ~~(NOTE_LENGTH.WHOLE/staff.time_signature[1]); // let stem_length : number = notes_spanned.reduce((acc:number,x:Note)=>(acc+x.info.stem_len),0)/notes_spanned.length; let stem_dir = notes_spanned[0].stem_dir; let flagcnts = []; for (let i = 0; i < notes_spanned.length; i++){ flagcnts.push(notes_spanned[i].flag_count); } // let extra_len = Math.max(0,Math.max(...flagcnts)-1)*CONFIG.FLAG_SPACING; let pts : {x:number,y:number}[] = notes_spanned.map(n=>{ let stem_length = n.stem_len;//+extra_len; let x = slot_pos(measure,n.begin)+CONFIG.NOTE_WIDTH*(Number(n.stem_dir<0)*slots[n.begin].mid_note) + n.slot_shift; return {x,y:on_staff(2*stem_dir*stem_length+n.staff_pos)}; }); let lengths = notes_spanned.map(x=>x.flag_count); let bins : number[] = new Array(pts.length*2-2).fill(0); // let [m,b]:[number,number] = least_sq_regress(pts); // if (Math.abs(m) > CONFIG.BEAM_MAX_SLOPE){ // m = Math.sign(m)*CONFIG.BEAM_MAX_SLOPE; // let anchor : {x:number,y:number}; // if (stem_dir < 0){ // anchor = pts.reduce((acc:{x:number,y:number},a:{x:number,y:number}):{x:number,y:number}=>(a.y<=acc.y?a:acc),{x:0,y:Infinity}); // }else{ // anchor = pts.reduce((acc:{x:number,y:number},a:{x:number,y:number}):{x:number,y:number}=>(a.y>=acc.y?a:acc),{x:0,y:-Infinity}); // } // // m*x+b=y b=y-m*x // b = anchor.y-m*anchor.x; // } for (let i = 0; i < pts.length; i++){ let flagcnt = flagcnts[i]; let last_len : number|undefined = lengths[i-1]; let next_len : number|undefined = lengths[i+1]; if (i == 0){ bins[i*2] = flagcnt; }else if (i == pts.length-1){ bins[i*2-1] = flagcnt; }else{ if (Math.abs(lengths[i]-last_len) <= Math.abs(lengths[i]-next_len)){ bins[i*2-1] = flagcnt; }else{ bins[i*2] = flagcnt; } if (CONFIG.BEAM_POLICY == 3){ let same_beat_l = ~~(notes_spanned[i-1].begin / beat_length) == ~~(notes_spanned[i].begin / beat_length); let same_beat_r = ~~(notes_spanned[i].begin / beat_length) == ~~(notes_spanned[i+1].begin / beat_length); if (!same_beat_l && i != 1){ bins[i*2-1] = 1; } if (!same_beat_r && i != pts.length-2){ bins[i*2] = 1; } } } } for (let i = 0; i < bins.length; i++){ if (bins[i] == 0){ let [i0,i1] = [~~(i/2),~~(i/2)+1]; bins[i] = Math.min(lengths[i0],lengths[i1]); } } let runs : [number,number,number][] = [[1,0,bins.length]]; let on : number = -1; for (let i = 2; i <= 4; i++){ for (let j = 0; j < bins.length; j++){ if (bins[j] >= i && on < 0){ on = j; } if (bins[j] < i && on >= 0){ runs.push([i,on,j]); on = -1; } } if (on >= 0){ runs.push([i,on,bins.length]); on = -1; } } // console.log(bins,runs); for (let i = 0; i < runs.length; i++){ let [t0,t1] = [(runs[i][1]/2),(runs[i][2]/2)]; let [i0,i1] = [~~(t0),~~(t1)]; let [f0,f1] = [t0-i0,t1-i1]; if (f0 > 0){ f0 += 0.2; } if (f1 > 0){ f1 -= 0.2; } let [j0,j1] = [ Math.min(i0+1,pts.length-1), Math.min(i1+1,pts.length-1) ]; let p0 = [pts[i0].x,pts[i0].y]; let p1 = [pts[j0].x,pts[j0].y]; let q0 = [pts[i1].x,pts[i1].y]; let q1 = [pts[j1].x,pts[j1].y]; let p = [p0[0]*(1-f0)+p1[0]*f0, p0[1]*(1-f0)+p1[1]*f0]; let q = [q0[0]*(1-f1)+q1[0]*f1, q0[1]*(1-f1)+q1[1]*f1]; result.push({ tag:'beam', x:p[0],y:p[1]-(runs[i][0]-1)*stem_dir*CONFIG.LINE_HEIGHT*CONFIG.FLAG_SPACING, w:q[0]-p[0],h:q[1]-p[1], stem_dir }); } for (let i = 0; i < bins.length; i++){ let [i0,i1] = [~~(i/2), ~~(i/2)+1]; let [x0,v0,y0] = [pts[i0].x, pts[i0].y, pts[i0].y]; let [x1,v1,y1] = [pts[i1].x, pts[i1].y, pts[i1].y]; if (i % 2 == 0){ let u0 = v0-((notes_spanned[i0].stem_len)*notes_spanned[i0].stem_dir)*CONFIG.LINE_HEIGHT; result.push({ tag:'line', type:'note_stem', x:x0,y:y0,w:0, h:u0-y0, }) }else if (i == bins.length-1){ let u1 = v1-((notes_spanned[i1].stem_len)*notes_spanned[i1].stem_dir)*CONFIG.LINE_HEIGHT; result.push({ tag:'line', type:'note_stem', x:x1,y:y1,w:0, h:u1-y1, }) } } } function draw_clef(){ result.push({ tag:'clef', type:staff.clef, x:measure.pad.inter+CONFIG.NOTE_WIDTH*CONFIG.CLEF_WIDTH_MUL/2, y:on_staff({ [CLEF.TREBLE]:6, [CLEF.BASS]:2, [CLEF.ALTO]:4, [CLEF.BARITONE]:0, [CLEF.SOPRANO]:8, [CLEF.TENOR]:2, [CLEF.MEZZO_SOPRANO]:6, }[staff.clef]), w:CONFIG.CLEF_WIDTH_MUL*CONFIG.NOTE_WIDTH, h:CONFIG.LINE_HEIGHT*(CONFIG.LINES_PER_STAFF-1), }); } function draw_key_signature(){ let {accidental,count} = staff.flags.need_keysig; let is_cancel : boolean = false; if ((accidental == ~ACCIDENTAL.SHARP) || (accidental == ~ACCIDENTAL.FLAT)){ is_cancel = true; accidental = ~accidental; } let targ_notes : string[] = Array.from(ORDER_OF_ACCIDENTALS[accidental].slice(0,count)); let octs : number[] = (accidental == ACCIDENTAL.SHARP)?( [6,6,6,6,5,6,5] ):( [5,6,5,6,5,6,5] ); let x = measure.pad.inter+Number(staff.flags.need_clef)*(CONFIG.NOTE_WIDTH*CONFIG.CLEF_WIDTH_MUL+measure.pad.inter); for (let i = 0; i < targ_notes.length; i++){ let n : string; if (staff.clef == CLEF.TREBLE){ n = targ_notes[i]+'_'+octs[i]; }else if (staff.clef == CLEF.BASS){ n = targ_notes[i]+'_'+(octs[i]-2); }else if (staff.clef == CLEF.SOPRANO){ n = targ_notes[i]+'_'+(octs[i]-1); }else if (staff.clef == CLEF.ALTO){ n = targ_notes[i]+'_'+(octs[i]-1); }else if (staff.clef == CLEF.TENOR){ n = targ_notes[i]+'_'+(octs[i]-1); }else if (staff.clef == CLEF.BARITONE){ n = targ_notes[i]+'_'+(octs[i]-1); }else if (staff.clef == CLEF.MEZZO_SOPRANO){ n = targ_notes[i]+'_'+(octs[i]-1); }else{ n = targ_notes[i]+'_'+octs[i]; } let line = note_name_to_staff_pos(n,staff.clef); result.push({ tag:'accidental', type:is_cancel?ACCIDENTAL.NATURAL:accidental, x:x+(i)*CONFIG.NOTE_WIDTH*CONFIG.KEYSIG_WIDTH_MUL+3, y:on_staff(line), w:CONFIG.NOTE_WIDTH, h:CONFIG.LINE_HEIGHT, }); } } function draw_time_signature(){ let x = measure.pad.inter+Number(staff.flags.need_clef)*(CONFIG.NOTE_WIDTH*CONFIG.CLEF_WIDTH_MUL+measure.pad.inter); if (staff.flags.need_keysig){ x += staff.flags.need_keysig.count*CONFIG.NOTE_WIDTH*CONFIG.KEYSIG_WIDTH_MUL+measure.pad.inter; } x += CONFIG.TIMESIG_WIDTH_MUL * CONFIG.NOTE_WIDTH/2; function draw_digit(d:number,x:number,line:number){ result.push({ tag:'timesig_digit', value:d, x:x, y:on_staff(line), w:CONFIG.TIMESIG_WIDTH_MUL*CONFIG.NOTE_WIDTH, h:CONFIG.LINE_HEIGHT*(CONFIG.LINES_PER_STAFF-1)/2, }) } function draw_num(n:number,x:number,line:number){ let digits : number[] = Array.from(n.toString()).map(Number); let u = CONFIG.TIMESIG_WIDTH_MUL * CONFIG.NOTE_WIDTH*0.5; for (let i = 0; i < digits.length; i++){ draw_digit(digits[i],x-(digits.length*u)/2+i*u+u/2,line); } } if (CONFIG.TIMESIG_COMMON_TIME_C && ( (staff.time_signature[0] == 2 && staff.time_signature[1] == 2) || (staff.time_signature[0] == 4 && staff.time_signature[1] == 4) )){ result.push({ tag:'timesig_c', type:(staff.time_signature[0]-2)?'common':'cut', x:x, y:on_staff(4), w:CONFIG.TIMESIG_WIDTH_MUL*CONFIG.NOTE_WIDTH, h:CONFIG.LINE_HEIGHT*(CONFIG.LINES_PER_STAFF-1)/2, }) }else{draw_num(staff.time_signature[0],x,2); draw_num(staff.time_signature[1],x,6); } } function draw_tuplets(){ let tuplets : Record<string,{ label:number,stem_dir:number,xmin:number,xmax:number,ymin:number,ymax:number }> = {}; function register_note_or_rest(n:Note|Rest,is_rest:boolean){ if (!n.tuplet){ return; } let r = tuplets[n.tuplet.id] if (!r){ r = tuplets[n.tuplet.id] = {label:n.tuplet.label,stem_dir:-1,xmin:Infinity,xmax:-Infinity,ymin:Infinity,ymax:-Infinity}; } let slot = slots[n.begin]; let slot_x = slot_pos(measure,n.begin); if (is_rest){ let rest : Rest = (n as Rest); let y0 = on_staff(rest.staff_pos); r.xmin = Math.min(r.xmin, slot_x); r.xmax = Math.max(r.xmax, slot_x + slot.mid_note*CONFIG.NOTE_WIDTH); r.ymin = Math.min(r.ymin,y0-CONFIG.LINE_HEIGHT*2); r.ymax = Math.max(r.ymax,y0+CONFIG.LINE_HEIGHT*2); }else{ let note : Note = (n as Note); r.stem_dir = note.stem_dir; let y = on_staff(note.staff_pos); let y0 = y+CONFIG.LINE_HEIGHT/2; let y1 = y + note.stem_len*note.stem_dir*CONFIG.LINE_HEIGHT + Math.max(0,note.flag_count-1) * CONFIG.FLAG_SPACING * note.stem_dir * CONFIG.LINE_HEIGHT; if (note.stem_dir < 0){ r.xmin = Math.min(r.xmin, slot_x - (slot.left_note-0.5)*CONFIG.NOTE_WIDTH); r.xmax = Math.max(r.xmax, slot_x + slot.mid_note*CONFIG.NOTE_WIDTH); }else{ r.xmin = Math.min(r.xmin, slot_x); r.xmax = Math.max(r.xmax, slot_x + (slot.mid_note+slot.right_note-0.5)*CONFIG.NOTE_WIDTH); } r.ymin = Math.min(r.ymin,y0,y1); r.ymax = Math.max(r.ymax,y0,y1); } } for (let i = 0; i < staff.notes.length; i++){ register_note_or_rest(staff.notes[i],false); } for (let i = 0; i < staff.rests.length; i++){ register_note_or_rest(staff.rests[i],true); } for (let k in tuplets){ let {label,stem_dir,ymin,ymax,xmin,xmax} = tuplets[k]; let y = stem_dir < 0 ? ymin : ymax; result.push({ tag:'tuplet_label', label, x:xmin, y:y+stem_dir*CONFIG.LINE_HEIGHT*CONFIG.TUPLET_LABEL_SPACING, w:xmax-xmin, h:stem_dir*CONFIG.LINE_HEIGHT/2, }) } } function draw_lyric(note:Note,slot_x:number){ let ymax_sans_lyric : number; ymax_sans_lyric = staff.coords.local_y_max-CONFIG.LYRIC_SPACING-CONFIG.LYRIC_SCALE*FONT_INHERENT_HEIGHT; // console.log(y_bound,ymax_sans_lyric); result.push({ tag:'lyric', text:note.lyric, x:slot_x, y:ymax_sans_lyric, w:get_text_width(note.lyric)*CONFIG.LYRIC_SCALE, h:FONT_INHERENT_HEIGHT*CONFIG.LYRIC_SCALE, }) } function draw_cue(nr:Note|Rest,slot_x:number){ let slot = slots[nr.begin]; let ymax_sans_cue : number; ymax_sans_cue = staff.coords.local_y_max-(staff.flags.need_lyric? (CONFIG.LYRIC_SPACING*2+CONFIG.LYRIC_SCALE*FONT_INHERENT_HEIGHT) : 0 )-CONFIG.CUE_HEIGHT; let x = slot_x; if (nr.cue.position == 0){ x+=CONFIG.NOTE_WIDTH*slot.mid_note/2; }else if (nr.cue.position == -1){ x-=CONFIG.NOTE_WIDTH*(slot.left_note+slot.left_deco+slot.left_squiggle+slot.left_grace)+measure.pad.inter/2; }else if (nr.cue.position == 1){ x+=CONFIG.NOTE_WIDTH*(slot.mid_note+slot.right_deco+slot.right_note)+measure.pad.inter/2; } // console.log(y_bound,ymax_sans_cue); result.push({ tag:'cue', text:nr.cue.data, x:x, y:ymax_sans_cue-(CONFIG.CUE_TEXT_SIZE-CONFIG.CUE_HEIGHT)/2, w:CONFIG.NOTE_WIDTH, h:CONFIG.CUE_TEXT_SIZE, }) } if (CONFIG.DEBUG_BLOCKS){ ;(function draw_dbg(){ // for (let i = 0; i < slots.length; i++){ // let slot_x = slot_pos(measure,i); // result.push({ // tag:'dbg', color:'red', // x:slot_x, // y:on_staff(0), // w: slots[i].mid_note*CONFIG.NOTE_WIDTH, // h: CONFIG.LINE_HEIGHT*(CONFIG.LINES_PER_STAFF-1), // }) // } for (let i = 0; i < slots.length; i++){ let slot_x = slot_pos(measure,i); result.push({ tag:'dbg', color:['red','blue','green'][~~(Math.random()*3)], x:slot_x, y:staff.coords.local_y_min, w: slots[i].mid_note*CONFIG.NOTE_WIDTH, h:staff.coords.local_y_max-staff.coords.local_y_min, }) } })(); } if (!no_staff_lines){ let measure_render_width : number = slot_pos(measure,measure.duration); for (let i = 0; i < CONFIG.LINES_PER_STAFF; i++){ result.push({ tag:'line', type:'staff_line', x:0, y:i*CONFIG.LINE_HEIGHT, w:measure_render_width, h:0, }) } } if (staff.flags.need_clef){ draw_clef(); } if (staff.flags.need_keysig){ draw_key_signature(); } if (staff.flags.need_timesig){ draw_time_signature(); } for (let i = 0; i < notes.length; i++){ let note = notes[i]; let line = note.staff_pos; let slot_x = slot_pos(measure,note.begin); let slot = slots[note.begin]; put_ledgers_as_necessary(note.begin,line); draw_note(note,slot_x,line); if (note.lyric){ draw_lyric(note,slot_x); } if (note.cue){ draw_cue(note,slot_x); } if (note.accidental !== null){ let x = slot.acc_pack.intervals[staff_idx].find(a=>a.idx==i).x; draw_accidental( note.accidental, slot_x-CONFIG.NOTE_WIDTH*slot.left_note-CONFIG.NOTE_WIDTH*CONFIG.ACCIDENTAL_WIDTH_MUL*0.6-(CONFIG.NOTE_WIDTH*CONFIG.ACCIDENTAL_WIDTH_MUL)*x*0.8, line ); } } let beams = staff.beams; for (let b of beams){ let notes_spanned = []; for (let i = 0; i < b.length; i++){ notes_spanned.push(notes[b[i]]) } if (!notes_spanned.length){ continue; } draw_beam(notes_spanned); } for (let i = 0; i < rests.length; i++){ let rest = rests[i]; let slot_x = slot_pos(measure,rest.begin); draw_rest(rest,slot_x); if (rest.cue){ draw_cue(rest,slot_x); } } draw_tuplets(); draw_ledgers(); translate_elements(result,staff.coords.x,staff.coords.y); for (let i = 0; i < staff.grace.length; i++){ if (!staff.grace[i]){ continue; } let nw0 = CONFIG.NOTE_WIDTH; CONFIG.NOTE_WIDTH*=CONFIG.GRACE_WIDTH_MUL; let ret = draw_staff(staff.grace[i],0,true); CONFIG.NOTE_WIDTH=nw0; ret.forEach((x)=>{ x.mini=true; result.push(x) }); } return result; } function translate_elements(elts:Element[],x:number,y:number){ for (let i = 0; i < elts.length; i++){ elts[i].x += x; elts[i].y += y; if (elts[i].x1){ elts[i].x1 += x; } if (elts[i].y1){ elts[i].y1 += y; } } } function plan_measures(score:Score){ let measures:Measure[] = score.measures; let measure_widths : [number,number,number][] = []; for (let i = 0; i < measures.length; i++){ let w : [number,number,number] = [0,0,0]; slot_pos(measures[i],measures[i].duration,w); w[0] += w[2]/CONFIG.NOTE_WIDTH; measure_widths.push(w); } let rows : { num_inter:number,count:number,width:number }[] = [{count:0,width:0,num_inter:0}]; for (let i = 0; i < measures.length; i++){ if (!i) {measures[i].is_first_col = true; score.first_col_measure_indices.push(i);} let row = rows[rows.length-1]; if (row.width + measure_widths[i][0] <= (CONTENT_WIDTH()-((rows.length==1)?score.indent:0))/CONFIG.NOTE_WIDTH){ row.count ++; row.width += measure_widths[i][0]; row.num_inter += measure_widths[i][1]; }else{ if (i) measures[i-1].is_last_col = true; measures[i].is_first_col = true; score.first_col_measure_indices.push(i); for (let j = 0; j < measures[i].staves.length; j++){ measures[i].staves[j].flags.need_clef = true; let [acc, num_acc] = measures[i].staves[j].key_signature; measures[i].staves[j].flags.need_keysig = { accidental:acc, count: num_acc }; } let w : [number,number,number] = [0,0,0]; slot_pos(measures[i],measures[i].duration,w); w[0] += w[2]/CONFIG.NOTE_WIDTH; measure_widths[i] = w; row = {count:1,width:measure_widths[i][0],num_inter:measure_widths[i][1]}; rows.push(row); } } // console.log(measures); let j0 : number = 0; let row_ybounds : [number,number][][] = []; let num_staves= measures.map(x=>x.staves.length).reduce((acc,x)=>Math.max(acc,x),0); for (let i = 0; i < rows.length; i++){ for (let k = 0; k < num_staves; k++){ let [has_cue,has_lyric] = [false,false]; for (let j = j0; j < j0+rows[i].count; j++){ if (!measures[j].staves[k]){ continue; } has_cue = has_cue || measures[j].staves[k].flags.need_cue; has_lyric = has_lyric || measures[j].staves[k].flags.need_lyric; } for (let j = j0; j < j0+rows[i].count; j++){ if (!measures[j].staves[k]){ continue; } measures[j].staves[k].flags.need_cue = has_cue; measures[j].staves[k].flags.need_lyric = has_lyric; } } j0 += rows[i].count; } j0 = 0; for (let i = 0; i < rows.length; i++){ let extra = ((CONTENT_WIDTH()-((i==0)?score.indent:0))-(rows[i].width*CONFIG.NOTE_WIDTH)); let nw = extra/rows[i].num_inter; for (let j = j0; j < j0+rows[i].count; j++){ measures[j].pad.inter += (i == rows.length-1 && extra/CONTENT_WIDTH() > (1-CONFIG.JUSTIFY_ALIGN_MIN))? 0 : nw; } j0 += rows[i].count; } for (let i = 0; i < measures.length; i++){ let measure = measures[i] as Measure; for (let j = 0; j < measure.staves.length; j++){ plan_beams(measure,j); plan_articulations(measure,j); } } j0 = 0; for (let i = 0; i < rows.length; i++){ row_ybounds[i] = []; for (let k = 0; k < num_staves; k++){ let [ya,yb] = [0,0,0,0]; for (let j = j0; j < j0+rows[i].count; j++){ if (!measures[j].staves[k]){ continue; } let [y0,y1] = estimate_staff_ybound(measures[j].staves[k],score.slurred_ids); ya = Math.min(y0,ya); yb = Math.max(y1,yb); // console.log(y0,y1,ya,yb) } let ymin = ya; let ymax = yb; row_ybounds[i][k] = [ymin,ymax]; } j0 += rows[i].count; } let xoff = score.indent; // let yoff = Math.max(CONFIG.INTER_ROW_HEIGHT,-row_ybounds[0][0][0]); let yoff = -row_ybounds[0][0][0]; let row_num = 0; let col_num = 0; if (rows[0] && rows[1] && rows[0].count == 0){ xoff = 0; yoff = -row_ybounds[1][0][0]; row_num++; } for (let i = 0; i < measures.length; i++){ let yo = 0; let staves = measures[i].staves; let w = slot_pos(measures[i],measures[i].duration); for (let j = 0; j < staves.length; j++){ let sp = (CONFIG.LINE_HEIGHT*(CONFIG.LINES_PER_STAFF-1)+CONFIG.INTER_STAFF_HEIGHT); let r = row_ybounds[row_num][j][1]; let staff_xoff = xoff; let staff_yoff = yoff+yo; if (j != staves.length-1){ r -= row_ybounds[row_num][j+1][0]; } sp = Math.max(sp,r); if (j != staves.length-1){ yo += sp; }else{ yo += (CONFIG.LINE_HEIGHT*(CONFIG.LINES_PER_STAFF-1)) } staves[j].coords.x = staff_xoff; staves[j].coords.y = staff_yoff; staves[j].coords.row = row_num; staves[j].coords.col = col_num; staves[j].coords.w = w; staves[j].coords.local_y_min = row_ybounds[row_num][j][0]; staves[j].coords.local_y_max = row_ybounds[row_num][j][1]; for (let k = 0; k < staves[j].grace.length; k++){ if (!staves[j].grace[k]){ continue; } let slot_x = slot_pos(measures[i],k); let slot = measures[i].slots[k]; slot_x -= (slot.left_note+slot.left_deco+slot.left_squiggle+slot.left_grace)*CONFIG.NOTE_WIDTH+measures[i].pad.inter; staves[j].grace[k].staves[0].coords.x = staff_xoff + slot_x; staves[j].grace[k].staves[0].coords.y = staff_yoff; staves[j].grace[k].staves[0].coords.row = row_num; staves[j].grace[k].staves[0].coords.col = col_num; staves[j].grace[k].staves[0].coords.w = slot_pos(staves[j].grace[k],staves[j].grace[k].duration)*CONFIG.GRACE_WIDTH_MUL; staves[j].grace[k].staves[0].coords.local_y_min = row_ybounds[row_num][j][0]; staves[j].grace[k].staves[0].coords.local_y_max = row_ybounds[row_num][j][1]; } } xoff += w; col_num++; if (measures[i].is_last_col || i == measures.length-1){ xoff = 0; let sp = row_ybounds[row_num][row_ybounds[row_num].length-1][1]; sp -= (CONFIG.LINE_HEIGHT*(CONFIG.LINES_PER_STAFF-1)); row_num++; col_num = 0; if (row_ybounds[row_num]){ sp -= row_ybounds[row_num][0][0]; } sp = Math.max(sp+30,CONFIG.INTER_ROW_HEIGHT); yo += sp yoff += yo; } } } function draw_measures(score:Score):Element[]{ let measures:Measure[] = score.measures; let result : Element[] = []; let human_measure_count = 0; for (let i = 0; i < measures.length; i++){ let staves = measures[i].staves; if (CONFIG.SHOW_MEASURE_NUMBER){ // console.log(measures[i].duration , staves[0].time_signature[0] * (64/staves[0].time_signature[1])) if (staves[0] && measures[i].duration >= staves[0].time_signature[0] * (64/staves[0].time_signature[1]) ){ human_measure_count ++; }else if (staves[0] && measures[i+1] && measures[i+1].staves[0] && measures[i+1].staves[0].key_signature[0] == staves[0].key_signature[0] && measures[i+1].staves[0].key_signature[1] == staves[0].key_signature[1] && measures[i].duration + measures[i+1].duration == staves[0].time_signature[0] * (64/staves[0].time_signature[1]) ){ human_measure_count ++; } } if (measures[i].is_first_col){ let staff_count = 0; for (let j = 0; j < score.instruments.length; j++){ if (!staves[staff_count]){ break; } let y0 = staves[staff_count].coords.y; let y1 = staves[staff_count+score.instruments[j].names.length-1].coords.y+(CONFIG.LINE_HEIGHT*(CONFIG.LINES_PER_STAFF-1)); if (!j && i && CONFIG.SHOW_MEASURE_NUMBER){ let t = human_measure_count.toString(); let w = get_text_width(t,FONT.DUPLEX,-2)*CONFIG.MEASURE_NUMBER_TEXT_SIZE/FONT_INHERENT_HEIGHT; result.push({ tag:"regular_text", type:"measure_number", text:t, x:staves[0].coords.x-w/2, y:y0-CONFIG.MEASURE_NUMBER_TEXT_SIZE-14, w, h:CONFIG.MEASURE_NUMBER_TEXT_SIZE, }); } if (!i && score.indent){ if (new Set(score.instruments[j].names).size == 1){ let w = get_text_width(score.instruments[j].names[0],FONT.DUPLEX,-2)*CONFIG.INSTRUMENT_TEXT_SIZE/FONT_INHERENT_HEIGHT; result.push({ tag:"regular_text", type:"instrument", text:score.instruments[j].names[0], x:staves[0].coords.x-w-CONFIG.INSTRUMENT_PAD_RIGHT, y:(y0+y1)/2-CONFIG.INSTRUMENT_TEXT_SIZE/2, w:w, h:CONFIG.INSTRUMENT_TEXT_SIZE, }); }else{ for (let k = 0; k < score.instruments[j].names.length; k++){ let z0 = staves[staff_count+k].coords.y; let z1 = staves[staff_count+k].coords.y+(CONFIG.LINE_HEIGHT*(CONFIG.LINES_PER_STAFF-1)); let w = get_text_width(score.instruments[j].names[k],FONT.DUPLEX,-2)*CONFIG.INSTRUMENT_TEXT_SIZE/FONT_INHERENT_HEIGHT; result.push({ tag:"regular_text", type:"instrument", text:score.instruments[j].names[k], x:staves[0].coords.x-w-CONFIG.INSTRUMENT_PAD_RIGHT, y:(z0+z1)/2-CONFIG.INSTRUMENT_TEXT_SIZE/2, w:w, h:CONFIG.INSTRUMENT_TEXT_SIZE, }); } } } if (score.instruments[j].bracket != BRACKET.NONE){ result.push({ tag:"bracket", type:score.instruments[j].bracket, x:staves[0].coords.x, y:y0, w:0, h:y1-y0, }); } staff_count += score.instruments[j].names.length; } if (staves.length > 1){ result.push({ tag:"line", type:'barline', x:staves[0].coords.x, y:staves[0].coords.y, w:0, h:staves[staves.length-1].coords.y+(CONFIG.LINE_HEIGHT*(CONFIG.LINES_PER_STAFF-1))-staves[0].coords.y, }) } if (CONFIG.JOIN_STAFF_LINES){ let last_measure_of_row = (score.first_col_measure_indices[staves[0].coords.row+1] ?? measures.length)-1; let x1 = measures[last_measure_of_row].staves[0].coords.x + measures[last_measure_of_row].staves[0].coords.w; for (let j = 0; j < staves.length; j++){ let y0 = staves[j].coords.y; for (let k = 0; k < CONFIG.LINES_PER_STAFF; k++){ result.push({ tag:'line', type:'staff_line', x:staves[0].coords.x, y:y0+k*CONFIG.LINE_HEIGHT, w:x1-staves[0].coords.x, h:0, }) } } } } for (let j = 0; j < staves.length; j++){ let ret = draw_staff(measures[i],j,CONFIG.JOIN_STAFF_LINES); ret.forEach(x=>result.push(x)); } if (!score.instruments.length){ result.push({ tag:"line", type:'barline', x:staves[0].coords.x+staves[0].coords.w, y:staves[0].coords.y, w:0, h:staves[staves.length-1].coords.y+(CONFIG.LINE_HEIGHT*(CONFIG.LINES_PER_STAFF-1))-staves[0].coords.y, }) } let staff_count = 0; for (let j = 0; j < score.instruments.length; j++){ for (let k = 0; k < score.instruments[j].names.length; k++){ let z0 = staves[staff_count+k].coords.y; let z1 = staves[staff_count+k].coords.y+(CONFIG.LINE_HEIGHT*(CONFIG.LINES_PER_STAFF-1)); let z2 = staves[staff_count+k+1]?staves[staff_count+k+1].coords.y:z1; if (measures[i].barline == BARLINE.SINGLE || measures[i].barline == BARLINE.REPEAT_BEGIN){ result.push({ tag:"line", type:'barline', x:staves[staff_count+k].coords.x+staves[staff_count+k].coords.w, y:z0, w:0, h:(score.instruments[j].connect_barlines[k]?z2:z1)-z0, }); } if (measures[i].barline == BARLINE.DOUBLE){ result.push({ tag:"line", type:'barline', x:staves[staff_count+k].coords.x+staves[staff_count+k].coords.w, y:z0, w:0, h:(score.instruments[j].connect_barlines[k]?z2:z1)-z0, }); result.push({ tag:"line", type:'barline', x:staves[staff_count+k].coords.x+staves[staff_count+k].coords.w-4, y:z0, w:0, h:(score.instruments[j].connect_barlines[k]?z2:z1)-z0, }); } if (measures[i].barline == BARLINE.END || measures[i].barline == BARLINE.REPEAT_END || measures[i].barline == BARLINE.REPEAT_END_BEGIN){ for (let l = 0; l < 4; l++){ result.push({ tag:"line", type:'barline', x:staves[staff_count+k].coords.x+staves[staff_count+k].coords.w-l, y:z0, w:0, h:(score.instruments[j].connect_barlines[k]?z2:z1)-z0, }); } result.push({ tag:"line", type:'barline', x:staves[staff_count+k].coords.x+staves[staff_count+k].coords.w-8, y:z0, w:0, h:(score.instruments[j].connect_barlines[k]?z2:z1)-z0, }); if (measures[i].barline != BARLINE.END){ result.push({ tag:"dot", type:'barline_repeat', x:staves[staff_count+k].coords.x+staves[staff_count+k].coords.w-12, y:z0+CONFIG.LINE_HEIGHT*1.5, w:0, h:0, }); result.push({ tag:"dot", type:'barline_repeat', x:staves[staff_count+k].coords.x+staves[staff_count+k].coords.w-12, y:z0+CONFIG.LINE_HEIGHT*2.5, w:0, h:0, }); } } if (measures[i].barline == BARLINE.REPEAT_BEGIN || measures[i].barline == BARLINE.REPEAT_END_BEGIN){ // console.log('!'); let x0 = measures[i+1].staves[staff_count+k].coords.x+slot_pos(measures[i+1],-1); let y0 = measures[i+1].staves[staff_count+k].coords.y; let xl = staves[staff_count+k].coords.x+staves[staff_count+k].coords.w; let adj = measures[i].barline == BARLINE.REPEAT_END_BEGIN && Math.abs(x0-xl) < 0.01; if (!adj){ for (let l = 1; l < 4; l++){ result.push({ tag:"line", type:'barline', x:x0+l, y:y0, w:0, h:(score.instruments[j].connect_barlines[k]?z2:z1)-z0, }); } } result.push({ tag:"line", type:'barline', x:x0+8-3*Number(adj), y:y0, w:0, h:(score.instruments[j].connect_barlines[k]?z2:z1)-z0, }); result.push({ tag:"dot", type:'barline_repeat', x:x0+12-3*Number(adj), y:y0+CONFIG.LINE_HEIGHT*1.5, w:0, h:0, }); result.push({ tag:"dot", type:'barline_repeat', x:x0+12-3*Number(adj), y:y0+CONFIG.LINE_HEIGHT*2.5, w:0, h:0, }); } } staff_count += score.instruments[j].names.length; } } return result; } function draw_slurs(score:Score):Element[]{ // console.log(id_registry); let result : Element[] = []; let row_yoffsets = score.measures.filter(x=>x.is_first_col).map(x=>x.staves[0].coords.y); // let been_left : Record<string,number> = {}; for (let i = 0; i < score.slurs.length; i++){ let {left,right,is_tie} = score.slurs[i]; // console.log(score.slurs[i]); let lreg = id_registry[left]; let rreg = id_registry[right]; let x0:number,y0:number,x1:number,y1:number,dir:number; let sh_lh = lreg.note.articulation?4:7; let sh_lt = lreg.note.articulation?2:5; let sh_rh = rreg.note.articulation?4:7; let sh_rt = rreg.note.articulation?2:5; let l_is_grace = score.measures[score.first_col_measure_indices[lreg.row]+lreg.col] != lreg.measure; if (is_tie){ if ( lreg.note.voice == 0 && rreg.note.voice == 0 && lreg.measure.staves[lreg.staff_idx].voices == 1 && rreg.measure.staves[rreg.staff_idx].voices == 1 && lreg.note.stem_dir == rreg.note.stem_dir ){ if (lreg.note.next_in_chord == null && lreg.note.prev_in_chord != null && rreg.note.next_in_chord == null && rreg.note.prev_in_chord != null){ dir = lreg.note.stem_dir; }else{ dir = -lreg.note.stem_dir; } [x0,y0] = [lreg.head_x,lreg.head_y+sh_lh*dir]; [x1,y1] = [rreg.head_x,rreg.head_y+sh_rh*dir]; }else{ if (Math.max(lreg.note.voice,rreg.note.voice) % 2){ dir = 1; [x0,y0] = [lreg.head_x,lreg.head_y+sh_lh]; [x1,y1] = [rreg.head_x,rreg.head_y+sh_rh]; }else{ dir = -1; [x0,y0] = [lreg.head_x,lreg.head_y-sh_lh]; [x1,y1] = [rreg.head_x,rreg.head_y-sh_rh]; } } }else{ sh_lh = lreg.note.articulation? ( lreg.note.articulation==ARTICULATION.STACCATO ? (Math.abs(lreg.note.articulation_pos[1]*CONFIG.LINE_HEIGHT/2-(lreg.chord_head_y-lreg.measure.staves[lreg.staff_idx].coords.y) )+5) : 4 ) :7 ; sh_rh = rreg.note.articulation? ( rreg.note.articulation==ARTICULATION.STACCATO ? (Math.abs(rreg.note.articulation_pos[1]*CONFIG.LINE_HEIGHT/2-(rreg.chord_head_y-rreg.measure.staves[rreg.staff_idx].coords.y) )+5) : 4 ) :7 ; if ( (lreg.measure.staves[lreg.staff_idx].voices > 1 || rreg.measure.staves[rreg.staff_idx].voices > 1) && lreg.note.stem_dir == rreg.note.stem_dir ){ if (lreg.note.stem_dir == 1){ dir = 1; [x0,y0] = [lreg.tail_x,lreg.tail_y+sh_lt]; [x1,y1] = [rreg.tail_x,rreg.tail_y+sh_rt]; }else{ dir = -1; [x0,y0] = [lreg.tail_x,lreg.tail_y-sh_lt]; [x1,y1] = [rreg.tail_x,rreg.tail_y-sh_rt]; } }else{ let head_to_tail_better = (Math.abs(lreg.chord_head_y-rreg.tail_y) < Math.abs(lreg.tail_y-rreg.chord_head_y)+5); let tail_to_tail_better = (Math.abs(lreg.tail_y-rreg.tail_y) < Math.abs(lreg.chord_head_y-rreg.chord_head_y)-40); if (lreg.note.stem_dir < 0 && rreg.note.stem_dir < 0){ if (tail_to_tail_better){ dir = -1; [x0,y0] = [lreg.tail_x,lreg.tail_y-sh_lt]; [x1,y1] = [rreg.tail_x,rreg.tail_y-sh_rt]; }else{ dir = 1; [x0,y0] = [lreg.chord_head_x,lreg.chord_head_y+sh_lh]; [x1,y1] = [rreg.chord_head_x,rreg.chord_head_y+sh_rh]; } }else if (lreg.note.stem_dir < 0 && rreg.note.stem_dir > 0){ if (head_to_tail_better){ dir = 1; [x0,y0] = [lreg.chord_head_x,lreg.chord_head_y+sh_lh]; [x1,y1] = [rreg.tail_x,rreg.tail_y+sh_rt]; }else{ dir = -1; [x0,y0] = [lreg.tail_x,lreg.tail_y-sh_lt]; [x1,y1] = [rreg.chord_head_x,rreg.chord_head_y-sh_rh]; } }else if (lreg.note.stem_dir > 0 && rreg.note.stem_dir > 0){ if (tail_to_tail_better){ dir = 1; [x0,y0] = [lreg.tail_x,lreg.tail_y+sh_lt]; [x1,y1] = [rreg.tail_x,rreg.tail_y+sh_rt]; }else{ dir = -1; [x0,y0] = [lreg.chord_head_x,lreg.chord_head_y-sh_lh]; [x1,y1] = [rreg.chord_head_x,rreg.chord_head_y-sh_rh]; } }else{ if (head_to_tail_better){ dir = -1; [x0,y0] = [lreg.chord_head_x,lreg.chord_head_y-sh_lh]; [x1,y1] = [rreg.tail_x,rreg.tail_y-sh_rt]; }else{ dir = 1; [x0,y0] = [lreg.tail_x,lreg.tail_y+sh_lt]; [x1,y1] = [rreg.chord_head_x,rreg.chord_head_y+sh_rh]; } } } } // if (been_left[left]){ // dir = - been_left[left]; // y0 += (CONFIG.LINE_HEIGHT+10) * dir; // y1 += (CONFIG.LINE_HEIGHT+10) * dir; // } // been_left[left] = dir; if (is_tie){ x0 +=3; x1 -=3; }else{ x0 +=2; x1 -=2; } function notes_ybounds(notes:Note[]):[number,number]{ if (!notes.length){ return null; } let ymin = Infinity; let ymax = -Infinity; for (let i = 0; i < notes.length; i++){ let y0 = on_staff(notes[i].staff_pos); let y1 = y0 + notes[i].stem_dir*notes[i].stem_len*CONFIG.LINE_HEIGHT; if (notes[i].accidental != null){ y0 -= CONFIG.LINE_HEIGHT; y1 += CONFIG.LINE_HEIGHT; } ymin = Math.min(y0,y1,ymin); ymax = Math.max(y0,y1,ymax); } return [ymin,ymax]; } function share_measure_ybound_in_slur():[number,number]{ let m0 = score.first_col_measure_indices[lreg.row]+lreg.col; let m1 = score.first_col_measure_indices[rreg.row]+rreg.col; if (m0 != m1){ return null; } let b0 = get_begin(lreg); let b1 = get_begin(rreg); let notes = score.measures[m0].staves[lreg.staff_idx].notes.filter(x=>(b0 < x.begin && x.begin < b1)); return notes_ybounds(notes); } function get_begin(reg:Note_register){ let m = score.first_col_measure_indices[reg.row]+reg.col; if (score.measures[m] != reg.measure){ for (let i = 0; i < score.measures[m].staves[reg.staff_idx].grace.length; i++){ if (score.measures[m].staves[reg.staff_idx].grace[i] == reg.measure){ return i; } } } return reg.note.begin; } function self_measure_ybound_in_slur(reg:Note_register,sign:number):[number,number]{ let m = score.first_col_measure_indices[reg.row]+reg.col; let begin = reg.note.begin; if (score.measures[m] != reg.measure){ for (let i = 0; i < score.measures[m].staves[reg.staff_idx].grace.length; i++){ if (score.measures[m].staves[reg.staff_idx].grace[i] == reg.measure){ begin = i; break; } } } let notes = score.measures[m].staves[reg.staff_idx].notes.filter(x=>(Math.sign(x.begin-begin)==sign)); return notes_ybounds(notes); } function inter_ybound_in_slur(situation:number):[number,number]{ let m0 = score.first_col_measure_indices[lreg.row]+lreg.col; let m1 = score.first_col_measure_indices[rreg.row]+rreg.col; if (situation == 1){ if (score.first_col_measure_indices[lreg.row+1] && score.first_col_measure_indices[lreg.row+1] < m1){ m1 = score.first_col_measure_indices[lreg.row+1]; } }else if (situation == 2){ if (score.first_col_measure_indices[rreg.row] && score.first_col_measure_indices[rreg.row] > m0){ m0 = score.first_col_measure_indices[rreg.row]-1; } } // if (situation == 0)console.log(m0,m1); if (m0+1 >= m1){ return null; } let ymin = Infinity; let ymax = -Infinity; for (let i = m0+1; i < m1; i++){ // console.log(score.measures[i].staves[lreg.staff_idx].coords) // let ya = score.measures[i].staves[lreg.staff_idx].coords.local_y_min; // let yb = score.measures[i].staves[rreg.staff_idx].coords.local_y_max; // let [ya,yb] = estimate_staff_ybound(score.measures[i].staves[lreg.staff_idx]); let [ya,yb] = notes_ybounds(score.measures[i].staves[lreg.staff_idx].notes); if (ya == null){ ya = 0; yb = CONFIG.LINE_HEIGHT*4; } ymin = Math.min(ymin,ya); ymax = Math.max(ymax,yb); } return [ymin,ymax]; } let dy : number = null; let ymin : number = null; let ymax : number = null; function compute_slur(situation:number){ dy = null; ymin = ymax = null; if (!is_tie && lreg.staff_idx == rreg.staff_idx){ let m0 = score.first_col_measure_indices[lreg.row]+lreg.col; let m1 = score.first_col_measure_indices[rreg.row]+rreg.col; if (m0 <= m1){ if (m0 == m1){ let ret = share_measure_ybound_in_slur(); if (ret) [ymin,ymax] = ret; }else{ let rets : [number,number][]; if (situation == 0){ rets = [self_measure_ybound_in_slur(lreg,1), inter_ybound_in_slur(0), self_measure_ybound_in_slur(rreg,-1), ]; if (rreg.measure.staves[rreg.staff_idx].flags.need_clef){ rets.push([CONFIG.LINE_HEIGHT,CONFIG.LINE_HEIGHT*(CONFIG.LINES_PER_STAFF-1)]); // console.log(rets); } // console.log(rets); }else if (situation == 1){ rets = [self_measure_ybound_in_slur(lreg,1), inter_ybound_in_slur(1), ]; }else if (situation == 2){ rets = [inter_ybound_in_slur(2), self_measure_ybound_in_slur(rreg,-1), ]; // console.log(rets); } // console.log(m0,m1,lreg.staff_idx,rets); for (let i = 0; i < rets.length; i++){ if (rets[i] == null){ continue; } if (ymin === null){ [ymin,ymax] = rets[i] }else{ ymin = Math.min(rets[i][0],ymin); ymax = Math.max(rets[i][1],ymax); } } } if (ymin !== null){ let yl = y0-lreg.measure.staves[lreg.staff_idx].coords.y; let yr = y1-rreg.measure.staves[rreg.staff_idx].coords.y; let ya : number; let yb : number; if (situation == 0){ ya = yl; yb = yr; }else if (situation == 1){ ya = yb = yl; }else if (situation == 2){ ya = yb = yr; } if (dir == -1){ // dy = Math.min(ya,yb)-ymin+CONFIG.LINE_HEIGHT/2; dy = (Math.max(ya,yb) + (ya+yb)/2)/2-ymin // if (situation == 1){ // console.log(ya,yb,ymin,dy) // } }else{ // dy = ymax-Math.max(ya,yb)+CONFIG.LINE_HEIGHT/2; dy = ymax-(Math.min(ya,yb)+(ya+yb)/2)/2 } dy *= 1.2; dy = Math.max(dy,0); // if (dy){ dy += CONFIG.LINE_HEIGHT*2; // } } } } } if (lreg.row == rreg.row){ compute_slur(0); let h = Math.min(CONFIG.LINE_HEIGHT*(lreg.measure==rreg.measure?4.5:6.5),Math.max(CONFIG.LINE_HEIGHT*1.5, dy!=null?0:(Math.abs(x1-x0)*0.05), dy!=null?0:(Math.abs(y1-y0)*0.5),dy==null?0:dy)); if (is_tie){ h *= 0.6; } result.push({ tag:"slur", x:x0, y:y0, w:x1-x0, h:h*CONFIG.SLUR_ARC_MUL, y1, dir, adjacent:dy==null, }) }else{ compute_slur(1); // let h = Math.min(CONFIG.LINE_HEIGHT*4.5,Math.max(CONFIG.LINE_HEIGHT*1.5,Math.abs(CONTENT_WIDTH()-x0)*0.16)); let h = Math.min(CONFIG.LINE_HEIGHT*6.5,Math.max(CONFIG.LINE_HEIGHT*1.5, dy!=null?0:(Math.abs(CONTENT_WIDTH()-x0)*0.16),dy==null?0:dy)); if (is_tie){ h *= 0.6; } let y_1 = y0+dir*h/4; if (ymin != null){ y_1 = y_1 * 0.5 + ( lreg.measure.staves[lreg.staff_idx].coords.y+ (dir<0?(ymin-CONFIG.LINE_HEIGHT/2):(ymax+CONFIG.LINE_HEIGHT/2)) )*0.5; } result.push({ tag:"slur", x:x0, y:y0, w:CONTENT_WIDTH()-x0, h:h*CONFIG.SLUR_ARC_MUL, y1:y_1, dir, }) function get_row_left(row:number):number{ let k = score.first_col_measure_indices[row]; let slot = score.measures[k].slots[0]; // let xz = slot_pos(score.measures[k],0)-(slot.left_deco+slot.left_grace+slot.left_note+slot.left_squiggle)*CONFIG.NOTE_WIDTH-score.measures[k].pad.inter; let xz = slot_pos(score.measures[k],-1);; return Math.max(xz,0); } for (let j = lreg.row+1; j < rreg.row; j++){ let h = Math.min(CONFIG.LINE_HEIGHT*7,Math.max(CONFIG.LINE_HEIGHT*1.5,CONTENT_WIDTH()*0.16)); let xz = get_row_left(j); // let dy = y0-row_yoffsets[lreg.row]; let notes = score.measures.slice(score.first_col_measure_indices[j],score.first_col_measure_indices[j+1]||Infinity).map(x=>x.staves[lreg.staff_idx]).map(x=>x.notes).flat(); let bd = notes_ybounds(notes); result.push({ tag:"slur", x:xz, y:row_yoffsets[j]+(dir<0?bd[0]:bd[1]), w:CONTENT_WIDTH()-xz, h:h*CONFIG.SLUR_ARC_MUL*3/4, y1:row_yoffsets[j]+(dir<0?bd[0]:bd[1]), dir, }) } let xz = get_row_left(rreg.row); compute_slur(2); // h = Math.min(CONFIG.LINE_HEIGHT*4.5,Math.max(CONFIG.LINE_HEIGHT*1.5,Math.abs(x1)*0.16)); h = Math.min(CONFIG.LINE_HEIGHT*6.5,Math.max(CONFIG.LINE_HEIGHT*1.5, dy!=null?0:(x1*0.16),dy==null?0:dy)); y_1 = y1+dir*h/4; if (ymin != null){ y_1 = y_1 * 0.5 + ( rreg.measure.staves[rreg.staff_idx].coords.y + (dir<0?(ymin-CONFIG.LINE_HEIGHT/2):(ymax+CONFIG.LINE_HEIGHT/2)) )*0.5; } result.push({ tag:"slur", x:xz, y:y_1 , w:x1-xz, h:h*CONFIG.SLUR_ARC_MUL, y1:y1, dir, }) } } return result; } function draw_crescs(score:Score):Element[]{ let result : Element[] = []; for (let i = 0; i < score.crescs.length; i++){ let {left,right,val_left,val_right} = score.crescs[i]; let lreg = id_registry[left]; let rreg = id_registry[right]; let x0 = lreg.head_x+3; let x1 = rreg.head_x-3; let staff0 = lreg.measure.staves[lreg.staff_idx]; let staff1 = rreg.measure.staves[rreg.staff_idx]; let ch = CONFIG.CUE_TEXT_SIZE; let y0 = staff0.coords.y + staff0.coords.local_y_max -(staff0.flags.need_lyric? (2*CONFIG.LYRIC_SPACING+CONFIG.LYRIC_SCALE*FONT_INHERENT_HEIGHT) : 0 )-CONFIG.CUE_HEIGHT/2; let y1 = staff1.coords.y + staff1.coords.local_y_max -(staff1.flags.need_lyric? (2*CONFIG.LYRIC_SPACING+CONFIG.LYRIC_SCALE*FONT_INHERENT_HEIGHT) : 0 )-CONFIG.CUE_HEIGHT/2; if (lreg.row == rreg.row){ let u0 = y0-ch/2*val_left; let u1 = y0+ch/2*val_left; let v0 = y1-ch/2*val_right; let v1 = y1+ch/2*val_right; result.push({ tag:'cresc', x:x0, y:u0, w:x1-x0, h:v0-u0, x1:x0, y1:u1, w1:x1-x0, h1:v1-u1, }) }else{ let wa = CONTENT_WIDTH()-x0; let ws:number[] = [0,wa]; for (let j = lreg.row+1; j < rreg.row; j++){ ws.push(wa+=CONTENT_WIDTH()); } ws.push(wa+=x1); for (let j = 0; j < rreg.row-lreg.row+1; j++){ let is_first = j==0; let is_last = j==rreg.row-lreg.row; let t0 = ws[j]/wa; let t1 = ws[j+1]/wa; let xl = is_first?x0:0; let xr = is_last?x1:CONTENT_WIDTH(); let y : number; if (is_first){ y = y0; }else if (is_last){ y = y1; }else{ for (let k = 0; k < score.measures.length; k++){ if (score.measures[k].staves[lreg.staff_idx].coords.row == lreg.row+j){ let staff = score.measures[k].staves[lreg.staff_idx]; y = staff.coords.y + staff.coords.local_y_max -(staff.flags.need_lyric? (2*CONFIG.LYRIC_SPACING+CONFIG.LYRIC_SCALE*FONT_INHERENT_HEIGHT) : 0 )-CONFIG.CUE_HEIGHT/2; break; } } } let l = val_left * (1-t0) + val_right * t0; let r = val_left * (1-t1) + val_right * t1; let u0 = y-ch/2*l; let u1 = y+ch/2*l; let v0 = y-ch/2*r; let v1 = y+ch/2*r; result.push({ tag:'line', type:'cresc_top', x:xl, y:u0, w:xr-xl, h:v0-u0, }) result.push({ tag:'line', type:'cresc_bottom', x:xl, y:u1, w:xr-xl, h:v1-u1, }) } } } return result; } function draw_tempo(tempo:Tempo_itf) : Element[]{ let result : Element[] = []; let dx = 0; if (tempo.duration!=null && tempo.bpm!=null){ if (tempo.duration<NOTE_LENGTH.WHOLE){ let num_flags = calc_num_flags(tempo.duration,tempo.modifier); result.push({ tag:'note_head', x:CONFIG.NOTE_WIDTH, y:CONFIG.TEMPO_COMPOSER_TEXT_SIZE, w:CONFIG.NOTE_WIDTH, h:CONFIG.LINE_HEIGHT, twisted:false, stem_dir:-1, duration:tempo.duration, }); dx += CONFIG.NOTE_WIDTH; let eh = (num_flags+1)*CONFIG.FLAG_SPACING*CONFIG.LINE_HEIGHT; result.push({ tag:'line', type:'note_stem', x:CONFIG.NOTE_WIDTH, y:-eh, w:0, h:CONFIG.TEMPO_COMPOSER_TEXT_SIZE+eh, }); if (tempo.modifier){ result.push({ tag:'dot', type:'modifier', x:CONFIG.NOTE_WIDTH*1.5, y:CONFIG.TEMPO_COMPOSER_TEXT_SIZE-CONFIG.LINE_HEIGHT/2, w:0, h:0, }) } if (tempo.modifier || num_flags){ dx += CONFIG.NOTE_WIDTH; } for (let i = 0; i < num_flags; i++){ result.push({ tag:'flag', x:CONFIG.NOTE_WIDTH, y:-eh+i*CONFIG.FLAG_SPACING*CONFIG.LINE_HEIGHT, w:CONFIG.NOTE_WIDTH, h:CONFIG.LINE_HEIGHT, stem_dir:-1, is_last: i == num_flags-1, }) } }else{ result.push({ tag:'note_head', x:CONFIG.NOTE_WIDTH, y:CONFIG.TEMPO_COMPOSER_TEXT_SIZE/2, w:CONFIG.NOTE_WIDTH, h:CONFIG.LINE_HEIGHT, twisted:false, stem_dir:-1, duration:tempo.duration, }); dx += CONFIG.NOTE_WIDTH; } let t = ' = '+tempo.bpm; let tw = get_text_width(t,FONT.DUPLEX,-2)*CONFIG.TEMPO_COMPOSER_TEXT_SIZE/FONT_INHERENT_HEIGHT; result.push({ tag:'regular_text', type:'tempo', text:t, x:dx, y:0, w:tw, h:CONFIG.TEMPO_COMPOSER_TEXT_SIZE, }); dx += tw + CONFIG.TEMPO_COMPOSER_TEXT_SIZE; } if (tempo.text != null){ let tw = get_text_width(tempo.text,FONT.TRIPLEX,-2)*CONFIG.TEMPO_COMPOSER_TEXT_SIZE/FONT_INHERENT_HEIGHT; result.push({ tag:'bold_text', type:'tempo', text:tempo.text, x:dx, y:0, w:tw, h:CONFIG.TEMPO_COMPOSER_TEXT_SIZE, }); } return result; } function get_content_yoffset(score:Score){ let dy = CONFIG.PAGE_MARGIN_Y; for (let i = 0; i < score.title.length; i++){ let h = i?CONFIG.SUBTITLE_TEXT_SIZE:CONFIG.TITLE_TEXT_SIZE; dy += h+CONFIG.TITLE_LINE_SPACING; } if (score.tempo || score.composer.length){ dy += CONFIG.TITLE_LINE_SPACING; if (score.composer.length){ let h = CONFIG.TEMPO_COMPOSER_TEXT_SIZE; for (let i = 0; i < score.composer.length; i++){ dy += CONFIG.TEMPO_COMPOSER_TEXT_SIZE+4; } dy -= CONFIG.TEMPO_COMPOSER_TEXT_SIZE+4; } dy += CONFIG.TEMPO_COMPOSER_TEXT_SIZE; } dy += CONFIG.TITLE_LINE_SPACING*1.2; return dy; } function draw_score(score:Score):[Element[],number]{ id_registry = {}; let ret = draw_measures(score); ret.push(...draw_slurs(score)); ret.push(...draw_crescs(score)); let last_staff = score.measures[score.measures.length-1].staves[score.measures[score.measures.length-1].staves.length-1]; let H = last_staff.coords.y+Math.max(last_staff.coords.local_y_max, (CONFIG.LINE_HEIGHT*(CONFIG.LINES_PER_STAFF+1))); let result : Element[] = []; let dy = CONFIG.PAGE_MARGIN_Y; for (let i = 0; i < score.title.length; i++){ let h = i?CONFIG.SUBTITLE_TEXT_SIZE:CONFIG.TITLE_TEXT_SIZE; let w = get_text_width(score.title[i],i?FONT.DUPLEX:FONT.TRIPLEX,-2)*h/FONT_INHERENT_HEIGHT; result.push({ ...(i?{tag:'regular_text',type:'subtitle'}:{tag:'bold_text',type:'title'}), text:score.title[i], x:CONFIG.PAGE_WIDTH/2-w/2, y:dy, w:w, h:h, }); dy += h+CONFIG.TITLE_LINE_SPACING; } if (score.tempo || score.composer.length){ dy += CONFIG.TITLE_LINE_SPACING; if (score.composer.length){ let h = CONFIG.TEMPO_COMPOSER_TEXT_SIZE; for (let i = 0; i < score.composer.length; i++){ let w = get_text_width(score.composer[i],FONT.DUPLEX,-2)*h/FONT_INHERENT_HEIGHT; result.push({ tag:'regular_text', type:'composer', text:score.composer[i], x:CONFIG.PAGE_WIDTH-CONFIG.PAGE_MARGIN_X-w, y:dy, w:w, h:h, }); dy += CONFIG.TEMPO_COMPOSER_TEXT_SIZE+4; } dy -= CONFIG.TEMPO_COMPOSER_TEXT_SIZE+4; } if (score.tempo){ let r = draw_tempo(score.tempo); translate_elements(r,CONFIG.PAGE_MARGIN_X+score.indent,dy); r.forEach(x=>result.push(x)); } dy += CONFIG.TEMPO_COMPOSER_TEXT_SIZE; } dy += CONFIG.TITLE_LINE_SPACING*1.2; translate_elements(ret,CONFIG.PAGE_MARGIN_X,dy); ret.forEach(x=>result.push(x)); return [result,H+CONFIG.PAGE_MARGIN_Y+dy]; } export function render_score(score:Score, {compute_polylines=true} : {compute_polylines?:boolean}={}):Drawing{ let [elements,h] = draw_score(score); let ret = { w:CONFIG.PAGE_WIDTH, h, elements:elements, polylines:null, }; if (CONFIG.SLUR_EVADE){ slur_evade_note(elements); } if (CONFIG.CUE_EVADE){ cue_evade_slur(elements); } if (compute_polylines){ ret.polylines = hf_drawing_polylines(elements,ret.w,ret.h); } return ret; } export function playhead_coords(score: Score, time_in_64th: number):[number,number,number,number]{ let time = Math.max(0,time_in_64th); let T = 0; let i:number; for (i = 0; i < score.measures.length; i++){ if (time < T+score.measures[i].duration){ break; } T += score.measures[i].duration; } if (i >= score.measures.length){ return playhead_coords(score,T-0.01); } let measure = score.measures[i]; let t = time-T; let it = ~~t; let ft = t-it; let x0 = slot_pos(measure,it); let x1 : number; if (measure.slots[it+1]){ x1 = slot_pos(measure,it+1); }else if (score.measures[i+1] && !score.measures[i+1].is_first_col){ x1 = measure.staves[0].coords.w+slot_pos(score.measures[i+1],0); }else{ x1 = measure.staves[0].coords.w; } let xf = x0 * (1-ft) + x1 * ft; let x = measure.staves[0].coords.x + xf + CONFIG.PAGE_MARGIN_X; let dy = get_content_yoffset(score); let y0 = dy + measure.staves[0].coords.y; let y1 = dy + measure.staves[measure.staves.length-1].coords.y + CONFIG.LINE_HEIGHT * (CONFIG.LINES_PER_STAFF-1); return [x,y0,x,y1]; }
the_stack
import {TestBed, inject} from '@angular/core/testing'; import {NgxApiUtilsModule, AuthTokenService, ApiHttpService, TokenPayload} from '../public-api'; import {Polly} from '@pollyjs/core'; import * as XHRAdapter from '@pollyjs/adapter-xhr'; import * as FetchAdapter from '@pollyjs/adapter-fetch'; import {TokenDecoder, AUTH_TOKEN_NAME} from './auth-token/public-api'; import {ApiErrorsInterceptor} from './api-http/interceptors/api-errors/api-errors.interceptor'; import { API_HTTP_INTERCEPTORS, API_HTTP_BASE_URL, API_HTTP_DEFAULT_HEADERS, API_HTTP_AUTHORIZATION_HEADER_NAME } from './api-http/public-api'; import {HttpErrorResponse} from '@angular/common/http'; /* Register the adapters and persisters we want to use. This way all future polly instances can access them by name. */ Polly.register(XHRAdapter); Polly.register(FetchAdapter); describe('ngx-api-utils package', () => { const apiUtilsConfig = { baseUrl: 'http://example.com/api', authTokenName: 'id_token', defaultHeaders: { accept: 'application/json, */*', 'X-Client': 'Ngx Api Utils Client' }, authorizationHeaderName: 'Authorization' }; let polly: any; beforeEach(() => { TestBed.configureTestingModule({ imports: [NgxApiUtilsModule], providers: [ { provide: API_HTTP_BASE_URL, useValue: apiUtilsConfig.baseUrl }, { provide: AUTH_TOKEN_NAME, useValue: apiUtilsConfig.authTokenName }, { provide: API_HTTP_DEFAULT_HEADERS, useValue: apiUtilsConfig.defaultHeaders }, { provide: API_HTTP_AUTHORIZATION_HEADER_NAME, useValue: apiUtilsConfig.authorizationHeaderName } ] }); polly = new Polly('ngx-api-utils', { adapters: ['xhr', 'fetch'] }); localStorage.removeItem(apiUtilsConfig.authTokenName); }); afterEach(async () => { await polly.stop(); }); describe('an AuthTokenService', () => { const fakeTokenValue = 'fake token value'; beforeEach(() => { // ensure the localStorage is clear localStorage.removeItem(apiUtilsConfig.authTokenName); }); it('should be provided', inject([AuthTokenService], (service: AuthTokenService) => { expect(service).toBeTruthy(); })); it('should have no token initially and should not be valid', inject([AuthTokenService], (service: AuthTokenService) => { expect(service.value).toEqual(undefined); expect(service.payload).toEqual(undefined); expect(service.isValid()).toBeFalsy(); expect(localStorage.getItem(apiUtilsConfig.authTokenName)).toEqual(null); })); it('should store whatever value is provided as token and should be valid', inject([AuthTokenService], (service: AuthTokenService) => { service.value$.next(fakeTokenValue); expect(service.value).toEqual(fakeTokenValue); expect(service.payload).toBeTruthy(); expect(service.isValid()).toBeTruthy(); expect(localStorage.getItem(apiUtilsConfig.authTokenName)).toEqual(fakeTokenValue); })); it('should load the stored value of the token and should be valid', () => { localStorage.setItem(apiUtilsConfig.authTokenName, fakeTokenValue); return inject([AuthTokenService], (service: AuthTokenService) => { expect(service.value).toEqual(fakeTokenValue); expect(service.payload).toBeTruthy(); expect(service.isValid()).toBeTruthy(); expect(localStorage.getItem(apiUtilsConfig.authTokenName)).toEqual(fakeTokenValue); })(); }); it('should clear the stored value of the token and should not be valid', inject([AuthTokenService], (service: AuthTokenService) => { localStorage.setItem(apiUtilsConfig.authTokenName, fakeTokenValue); service.value$.next(undefined); expect(service.value).toEqual(undefined); expect(service.payload).toEqual(undefined); expect(service.isValid()).toBeFalsy(); expect(localStorage.getItem(apiUtilsConfig.authTokenName)).toEqual(null); })); it('should update the value of the token when changed and should be valid', () => { class FakeTokenPayload extends TokenPayload { constructor(public token: string) { super(); } } class FakeTokenDecoder extends TokenDecoder<FakeTokenPayload> { decode(token: string): FakeTokenPayload { return new FakeTokenPayload(token); } } TestBed.overrideProvider(TokenDecoder, { useValue: new FakeTokenDecoder() }); return inject([AuthTokenService], (service: AuthTokenService<FakeTokenPayload>) => { const subscriberSpy = jasmine.createSpy('subscriberSpy'); service.value$.subscribe((token) => subscriberSpy(token)); // no stored token yet expect(subscriberSpy.calls.mostRecent().args[0]).toBeUndefined(); // fist token const tokenValueFirst = 'fake token first'; service.value$.next(tokenValueFirst); expect(service.value).toEqual(tokenValueFirst); expect(service.payload).toBeTruthy(); expect(service.payload.token).toEqual(tokenValueFirst); expect(service.isValid()).toBeTruthy(); expect(subscriberSpy.calls.mostRecent().args[0]).toEqual(tokenValueFirst); expect(localStorage.getItem(apiUtilsConfig.authTokenName)).toEqual(tokenValueFirst); // second token const tokenValueSecond = 'fake token second'; service.value$.next(tokenValueSecond); expect(service.value).toEqual(tokenValueSecond); expect(service.payload).toBeTruthy(); expect(service.payload.token).toEqual(tokenValueSecond); expect(service.isValid()).toBeTruthy(); expect(subscriberSpy.calls.mostRecent().args[0]).toEqual(tokenValueSecond); expect(localStorage.getItem(apiUtilsConfig.authTokenName)).toEqual(tokenValueSecond); // third token const tokenValueThird = 'fake token third'; service.value$.next(tokenValueThird); expect(service.value).toEqual(tokenValueThird); expect(service.payload).toBeTruthy(); expect(service.payload.token).toEqual(tokenValueThird); expect(service.isValid()).toBeTruthy(); expect(subscriberSpy.calls.mostRecent().args[0]).toEqual(tokenValueThird); expect(localStorage.getItem(apiUtilsConfig.authTokenName)).toEqual(tokenValueThird); })(); }); }); describe('an ApiHttpService', () => { const fakeTokenValue = 'fake token value'; it('should be provided', inject([ApiHttpService], (service: ApiHttpService) => { expect(service).toBeTruthy(); })); it('should prefix the requests with the `baseUrl` configured', async () => { // ensure a token localStorage.setItem(apiUtilsConfig.authTokenName, fakeTokenValue); return inject([ApiHttpService], async (service: ApiHttpService) => { const {server} = polly; const endpoint = '/products'; server.get(`${apiUtilsConfig.baseUrl}/*`).intercept((req: any, res: any) => { res.sendStatus(404); }); server.get(`${apiUtilsConfig.baseUrl}${endpoint}`).intercept((req: any, res: any) => { res.status(200).json({success: true}); }); const {success} = await service.get<{success: boolean}>(endpoint).toPromise(); expect(success).toBeTruthy('response should be success'); })(); }); it('should add default configured headers to the requests', async () => { // ensure a token localStorage.setItem(apiUtilsConfig.authTokenName, fakeTokenValue); return inject([ApiHttpService], async (service: ApiHttpService) => { const {server} = polly; const endpoint = '/products'; server.get(`${apiUtilsConfig.baseUrl}/*`).intercept((req: any, res: any) => { res.sendStatus(404); }); server.get(`${apiUtilsConfig.baseUrl}${endpoint}`).intercept((req: any, res: any) => { res.status(200).json({success: true, receivedHeaders: req.headers}); }); const {success, receivedHeaders} = await service.get<{success: boolean; receivedHeaders: object}>(endpoint).toPromise(); expect(success).toBeTruthy('response should be success'); const normalizedReceivedHeaders = Object.keys(receivedHeaders).reduce((prev, headerName) => { (prev as any)[headerName.toLowerCase()] = (receivedHeaders as any)[headerName]; return prev; }, {}); Object.keys(apiUtilsConfig.defaultHeaders).forEach((headerName) => { const headerValue = (apiUtilsConfig.defaultHeaders as any)[headerName]; headerName = headerName.toLowerCase(); expect((normalizedReceivedHeaders as any)[headerName]).toEqual(headerValue); }); })(); }); it('should add the authentication token as header', async () => { return inject([ApiHttpService, AuthTokenService], async (service: ApiHttpService, authTokenService: AuthTokenService) => { authTokenService.value$.next(fakeTokenValue); const {server} = polly; const endpoint = '/products'; server.get(`${apiUtilsConfig.baseUrl}/*`).intercept((req: any, res: any) => { res.sendStatus(404); }); server.get(`${apiUtilsConfig.baseUrl}${endpoint}`).intercept((req: any, res: any) => { res.status(200).json({success: true, authToken: req.headers[apiUtilsConfig.authorizationHeaderName]}); }); const {success, authToken} = await service.get<{success: boolean; authToken: string}>(endpoint).toPromise(); expect(success).toBeTruthy('response should be success'); expect(authToken).toEqual(`Bearer ${fakeTokenValue}`); })(); }); it('should allow requests without authentication token as header', async () => { return inject([ApiHttpService, AuthTokenService], async (service: ApiHttpService, authTokenService: AuthTokenService) => { authTokenService.value$.next(fakeTokenValue); const {server} = polly; const endpoint = '/products'; server.get(`${apiUtilsConfig.baseUrl}/*`).intercept((req: any, res: any) => { res.sendStatus(404); }); server.get(`${apiUtilsConfig.baseUrl}${endpoint}`).intercept((req: any, res: any) => { res.status(200).json({success: true, authToken: req.headers[apiUtilsConfig.authorizationHeaderName]}); }); const {success, authToken} = await service .get<{success: boolean; authToken: string}>(endpoint, { headers: service.headersWithNoAuthorization() }) .toPromise(); expect(success).toBeTruthy('response should be success'); expect(authToken).toBeUndefined(); })(); }); it('should leave preset authorization token header in the request as is', async () => { return inject([ApiHttpService, AuthTokenService], async (service: ApiHttpService, authTokenService: AuthTokenService) => { const presetFakeTokenValue = 'preset fake token value'; authTokenService.value$.next(fakeTokenValue); const {server} = polly; const endpoint = '/products'; server.get(`${apiUtilsConfig.baseUrl}/*`).intercept((req: any, res: any) => { res.sendStatus(404); }); server.get(`${apiUtilsConfig.baseUrl}${endpoint}`).intercept((req: any, res: any) => { res.status(200).json({success: true, authToken: req.headers[apiUtilsConfig.authorizationHeaderName]}); }); const {success, authToken} = await service .get<{success: boolean; authToken: string}>(endpoint, { headers: {[apiUtilsConfig.authorizationHeaderName]: `Bearer ${presetFakeTokenValue}`} }) .toPromise(); expect(success).toBeTruthy('response should be success'); expect(authToken).toEqual(`Bearer ${presetFakeTokenValue}`); })(); }); it('should throw in case the token is not valid any more', async () => { return inject([ApiHttpService, AuthTokenService], async (service: ApiHttpService, authTokenService: AuthTokenService) => { authTokenService.value$.next(undefined); const {server} = polly; const endpoint = '/products'; server.get(`${apiUtilsConfig.baseUrl}/*`).intercept((req: any, res: any) => { res.sendStatus(404); }); server.get(`${apiUtilsConfig.baseUrl}${endpoint}`).intercept((req: any, res: any) => { res.status(200).json({success: true, authToken: req.headers[apiUtilsConfig.authorizationHeaderName]}); }); let caught = false; try { await service.get<{success: boolean; authToken: string}>(endpoint).toPromise(); } catch { caught = true; } expect(caught).toEqual(true, 'error was thrown when a request was performed'); })(); }); it('should intercept errors in case the errors interceptor is used at all', async () => { TestBed.configureTestingModule({ providers: [ ApiErrorsInterceptor, { provide: API_HTTP_INTERCEPTORS, useExisting: ApiErrorsInterceptor, multi: true } ] }); return inject( [ApiHttpService, AuthTokenService, ApiErrorsInterceptor], async (service: ApiHttpService, authTokenService: AuthTokenService, apiErrors: ApiErrorsInterceptor) => { const presetFakeTokenValue = 'preset fake token value'; authTokenService.value$.next(fakeTokenValue); const {server} = polly; const endpoint = '/products'; server.get(`${apiUtilsConfig.baseUrl}/*`).intercept((req: any, res: any) => { res.sendStatus(404); }); let caught = false; try { await service .get<{success: boolean}>(endpoint, {headers: {[apiUtilsConfig.authorizationHeaderName]: `Bearer ${presetFakeTokenValue}`}}) .toPromise(); } catch { caught = true; } expect(caught).toEqual(true, 'error was thrown when a request was performed'); expect(apiErrors.lastApiError instanceof HttpErrorResponse).toBeTruthy(); expect(apiErrors.lastApiError.status).toEqual(404); } )(); }); }); xdescribe('an ApiAuthGuard', () => { // TODO: Complete these integration tests }); });
the_stack
import * as Clutter from 'clutter'; import * as Gio from 'gio'; import * as GnomeDesktop from 'gnomedesktop'; import * as GObject from 'gobject'; import { VerticalPanelPositionEnum } from 'src/manager/msThemeManager'; import { assert, assertNotNull } from 'src/utils/assert'; import { registerGObjectClass } from 'src/utils/gjs'; import { reparentActor } from 'src/utils/index'; import { gnomeVersionGreaterOrEqualTo } from 'src/utils/shellVersionMatch'; import * as St from 'st'; import { dateMenu, main as Main, panel } from 'ui'; /** Extension imports */ const Me = imports.misc.extensionUtils.getCurrentExtension(); @registerGObjectClass export class MsStatusArea extends Clutter.Actor { static metaInfo: GObject.MetaInfo = { GTypeName: 'MsStatusArea', }; gnomeShellPanel: panel.Panel; leftBoxActors: Clutter.Actor[]; rightBoxActors: Clutter.Actor[]; dateMenu: dateMenu.DateMenuButton; originalDateMenuBox: any; msDateMenuBox?: MsDateMenuBox; signalIds: { leftBoxActor: number; centerBoxActor: number; rightBoxActor: number; } | null = null; centerBoxActors: Clutter.Actor[]; constructor() { super({ layout_manager: new Clutter.BoxLayout({ orientation: Clutter.Orientation.VERTICAL, pack_start: false, }), }); this.gnomeShellPanel = Main.panel; this.leftBoxActors = []; this.centerBoxActors = []; this.rightBoxActors = []; this.dateMenu = this.gnomeShellPanel.statusArea.dateMenu; this.enable(); } enable() { this.verticaliseDateMenuButton(); this.stealPanelActors(); this.overridePanelMenuSide(); } verticaliseDateMenuButton() { assert( this.msDateMenuBox === undefined, 'date menu button has alreayd been verticalized' ); this.originalDateMenuBox = this.dateMenu._clockDisplay.get_parent(); this.dateMenu.remove_child(this.originalDateMenuBox); this.msDateMenuBox = new MsDateMenuBox(this.dateMenu); this.dateMenu.add_child(this.msDateMenuBox); } unVerticaliseDateMenuButton() { assert( this.msDateMenuBox !== undefined, "date menu button hasn't been verticalized" ); this.msDateMenuBox.destroy(); delete this.msDateMenuBox; this.dateMenu.add_child(this.originalDateMenuBox); } stealPanelActors() { this.gnomeShellPanel._leftBox .get_children() .filter((actor) => { return ( actor != this.gnomeShellPanel.statusArea.activities.container && actor != this.gnomeShellPanel.statusArea.appMenu.container ); }) .forEach((actor) => { this.stealActor(actor, this.leftBoxActors); }); const leftBoxActorAddedSignal = this.gnomeShellPanel._leftBox.connect( 'actor-added', (_, actor) => { this.stealActor(actor, this.leftBoxActors); } ); this.gnomeShellPanel._centerBox.get_children().forEach((actor) => { this.stealActor(actor, this.centerBoxActors); }); const centerBoxActorAddedSignal = this.gnomeShellPanel._centerBox.connect( 'actor-added', (_, actor) => { this.stealActor(actor, this.centerBoxActors); } ); this.gnomeShellPanel._rightBox .get_children() .reverse() .forEach((actor) => { this.stealActor(actor, this.rightBoxActors); }); const rightBoxActorAddedSignal = this.gnomeShellPanel._rightBox.connect( 'actor-added', (_, actor) => { this.stealActor(actor, this.rightBoxActors); } ); this.signalIds = { rightBoxActor: rightBoxActorAddedSignal, leftBoxActor: leftBoxActorAddedSignal, centerBoxActor: centerBoxActorAddedSignal, }; } stealActor(actor: Clutter.Actor, container: Clutter.Actor[]) { container.push(actor); actor.connect('destroy', () => { container.splice(container.indexOf(actor), 1); }); actor.y_expand = false; actor.x_expand = true; this.recursivelySetVertical(actor, true); reparentActor(actor, this, true); } restorePanelActors() { const signalIds = assertNotNull(this.signalIds); this.gnomeShellPanel._leftBox.disconnect(signalIds.leftBoxActor); this.gnomeShellPanel._centerBox.disconnect(signalIds.centerBoxActor); this.gnomeShellPanel._rightBox.disconnect(signalIds.rightBoxActor); this.leftBoxActors.forEach((actor) => { if (!actor) return; this.recursivelySetVertical(actor, false); reparentActor(actor, this.gnomeShellPanel._leftBox); }); this.centerBoxActors.forEach((actor) => { if (!actor) return; this.recursivelySetVertical(actor, false); reparentActor(actor, this.gnomeShellPanel._centerBox); }); this.rightBoxActors.reverse().forEach((actor) => { if (!actor) return; this.recursivelySetVertical(actor, false); reparentActor(actor, this.gnomeShellPanel._rightBox); }); } recursivelySetVertical( actor: Clutter.Actor & { has_style_class_name?: (name: string) => boolean; }, value: boolean ) { if (actor instanceof St.BoxLayout) { actor.vertical = value; actor.set_x_align(Clutter.ActorAlign.CENTER); } if ( actor instanceof St.Icon && actor.has_style_class_name('popup-menu-arrow') ) { actor.visible = !value; } // TODO: Is `actor instanceof St.Button` enough? if ( actor.has_style_class_name && actor.has_style_class_name('panel-button') ) { actor.y_expand = !value; } actor.get_children().forEach((child) => { this.recursivelySetVertical(child, value); }); } overridePanelMenuSide() { // For each menu override the opening side to match the vertical panel for (const menuData of this.gnomeShellPanel.menuManager._menus) { const menu = gnomeVersionGreaterOrEqualTo(menuData, '42.0') ? menuData : menuData.menu; if (menu._boxPointer) { (menu._boxPointer as any).oldArrowSideFunction = menu._boxPointer._calculateArrowSide; menu._boxPointer._calculateArrowSide = function () { return Me.msThemeManager.verticalPanelPosition === VerticalPanelPositionEnum.LEFT ? St.Side.LEFT : St.Side.RIGHT; }; } } } restorePanelMenuSide() { for (const menuData of this.gnomeShellPanel.menuManager._menus) { const menu = gnomeVersionGreaterOrEqualTo(menuData, '42.0') ? menuData : menuData.menu; if (menu._boxPointer) { menu._boxPointer._calculateArrowSide = ( menu._boxPointer as any ).oldArrowSideFunction; delete (menu._boxPointer as any).oldArrowSideFunction; } } } disable() { Me.logFocus('disable statusArea'); this.unVerticaliseDateMenuButton(); this.restorePanelMenuSide(); this.restorePanelActors(); this.gnomeShellPanel.statusArea.aggregateMenu.set_y_expand(true); } } @registerGObjectClass export class MsDateMenuBox extends St.Widget { static metaInfo: GObject.MetaInfo = { GTypeName: 'MsDateMenuBox', }; dateMenu: dateMenu.DateMenuButton; indicatorActor: dateMenu.MessagesIndicator; private _wallClock: any; clockLabel: St.Label< Clutter.Actor<Clutter.LayoutManager, Clutter.ContentPrototype> >; notificationIcon: St.Icon< Clutter.Actor<Clutter.LayoutManager, Clutter.ContentPrototype> >; notificationIconRing: St.Icon< Clutter.Actor<Clutter.LayoutManager, Clutter.ContentPrototype> >; dndIcon: St.Icon< Clutter.Actor<Clutter.LayoutManager, Clutter.ContentPrototype> >; private _settings: Gio.Settings; iconDisplay: Clutter.Actor<Clutter.LayoutManager, Clutter.ContentPrototype>; dateMenuSignal: number; indicatorSignal: number; constructor(dateMenu: dateMenu.DateMenuButton) { super({ x_align: Clutter.ActorAlign.CENTER, layout_manager: new Clutter.BinLayout(), }); this.dateMenu = dateMenu; this.indicatorActor = this.dateMenu._indicator; this._wallClock = new GnomeDesktop.WallClock({ time_only: true }); this.clockLabel = new St.Label({}); this.notificationIcon = new St.Icon({ gicon: Gio.icon_new_for_string( `${Me.path}/assets/icons/bell-symbolic.svg` ), }); this.notificationIconRing = new St.Icon({ style_class: 'primary', gicon: Gio.icon_new_for_string( `${Me.path}/assets/icons/bell-ring-symbolic.svg` ), }); this.dndIcon = new St.Icon({ gicon: Gio.icon_new_for_string( `${Me.path}/assets/icons/bell-off-symbolic.svg` ), }); this._settings = new Gio.Settings({ schema_id: 'org.gnome.desktop.notifications', }); this.iconDisplay = new Clutter.Actor(); this.iconDisplay.add_child(this.notificationIcon); this.iconDisplay.add_child(this.notificationIconRing); this.iconDisplay.add_child(this.dndIcon); if (Me.msThemeManager.clockHorizontal) { this.add_child(this.iconDisplay); } else { this.add_child(this.clockLabel); } Me.msThemeManager.connect('clock-horizontal-changed', () => { if (Me.msThemeManager.clockHorizontal) { this.remove_child(this.clockLabel); this.add_child(this.iconDisplay); } else { this.remove_child(this.iconDisplay); this.add_child(this.clockLabel); } this.updateVisibility(); }); this.updateVisibility(); this.updateClock(); this.dateMenuSignal = this._wallClock.connect( 'notify::clock', this.updateClock.bind(this) ); this.indicatorSignal = this.indicatorActor.connect( 'notify::visible', this.updateVisibility.bind(this) ); this.connect('destroy', () => { this.indicatorActor.disconnect(this.indicatorSignal); this._wallClock.disconnect(this.dateMenuSignal); delete this._wallClock; }); } updateClock() { /** * Format clock display to fit into the vertical panel * Place each section of the clock (HH, MM, AM/PM) onto its own line * * Deliberately separates HH:MM into distinct sections */ const clockSections: string[] = this._wallClock.clock .replace(/∶/g, ' ') .split(' '); if (!clockSections[0]) clockSections.shift(); const markup = clockSections .map((section) => `<span>${section}</span>`) .join('\n'); this.clockLabel.clutter_text.set_markup(markup); this.updateVisibility(); } updateVisibility() { const doNotDisturb = !this._settings.get_boolean('show-banners'); if (this.indicatorActor.visible) { if (Me.msThemeManager.clockHorizontal) { if (doNotDisturb) { this.dndIcon.show(); this.notificationIconRing.hide(); } else { this.dndIcon.hide(); this.notificationIconRing.show(); } this.notificationIcon.hide(); } else { if (doNotDisturb) { if (this.clockLabel.has_style_class_name('primary')) { this.clockLabel.remove_style_class_name('primary'); } return; } if (this.clockLabel.has_style_class_name('primary')) return; this.clockLabel.add_style_class_name('primary'); } } else { if (Me.msThemeManager.clockHorizontal) { this.notificationIcon.show(); this.notificationIconRing.hide(); this.dndIcon.hide(); } else { if (!this.clockLabel.has_style_class_name('primary')) return; this.clockLabel.remove_style_class_name('primary'); } } } }
the_stack
module Fayde.Controls { export class ItemsControlNode extends ControlNode { XObject: ItemsControl; constructor(xobj: ItemsControl) { super(xobj); } ItemsPresenter: ItemsPresenter = null; GetDefaultVisualTree(): UIElement { var presenter = this.ItemsPresenter; if (!presenter) (presenter = new ItemsPresenter()).TemplateOwner = this.XObject; return presenter; } } export class ItemsControl extends Control { XamlNode: ItemsControlNode; CreateNode(): ItemsControlNode { return new ItemsControlNode(this); } get IsItemsControl(): boolean { return true; } static DisplayMemberPathProperty = DependencyProperty.Register("DisplayMemberPath", () => String, ItemsControl, null, (d, args) => (<ItemsControl>d).OnDisplayMemberPathChanged(args)); static ItemsPanelProperty = DependencyProperty.Register("ItemsPanel", () => ItemsPanelTemplate, ItemsControl); static ItemsSourceProperty = DependencyProperty.RegisterFull("ItemsSource", () => nullstone.IEnumerable_, ItemsControl, null, (d, args) => (<ItemsControl>d).OnItemsSourceChanged(args)); static ItemsProperty = DependencyProperty.RegisterImmutable<ItemCollection>("Items", () => ItemCollection, ItemsControl); static ItemTemplateProperty = DependencyProperty.Register("ItemTemplate", () => DataTemplate, ItemsControl, undefined, (d, args) => (<ItemsControl>d).OnItemTemplateChanged(args)); static IsItemsHostProperty = DependencyProperty.RegisterAttached("IsItemsHost", () => Boolean, ItemsControl, false); static GetIsItemsHost(d: DependencyObject): boolean { return d.GetValue(ItemsControl.IsItemsHostProperty) === true; } static SetIsItemsHost(d: DependencyObject, value: boolean) { d.SetValue(ItemsControl.IsItemsHostProperty, value === true); } DisplayMemberPath: string; ItemsPanel: ItemsPanelTemplate; ItemsSource: nullstone.IEnumerable<any>; Items: ItemCollection; ItemTemplate: DataTemplate; OnDisplayMemberPathChanged(e: IDependencyPropertyChangedEventArgs) { for (var en = this.ItemContainersManager.GetEnumerator(); en.moveNext();) { this.UpdateContainerTemplate(en.current, en.CurrentItem); } } OnItemsSourceChanged(e: IDependencyPropertyChangedEventArgs) { //Unsubscribe from old var nc = Collections.INotifyCollectionChanged_.as(e.OldValue); if (nc) nc.CollectionChanged.off(this._OnItemsSourceUpdated, this); var items = this.Items; var resetargs = Collections.CollectionChangedEventArgs.Reset(items.ToArray()); //Reset old try { this._SuspendItemsChanged = true; items.Clear(); } finally { this._SuspendItemsChanged = false; } this.OnItemsChanged(resetargs); //Notify new this._IsDataBound = !!e.NewValue; var arr = toArray(e.NewValue); try { this._SuspendItemsChanged = true; if (arr) items.AddRange(arr); } finally { this._SuspendItemsChanged = false; } if (arr) this.OnItemsChanged(Collections.CollectionChangedEventArgs.AddRange(arr, 0)); //Subscribe to new var nc = Collections.INotifyCollectionChanged_.as(e.NewValue); if (nc) nc.CollectionChanged.on(this._OnItemsSourceUpdated, this); } OnItemTemplateChanged (e: IDependencyPropertyChangedEventArgs) { for (var en = this.ItemContainersManager.GetEnumerator(); en.moveNext();) { this.UpdateContainerTemplate(en.current, en.CurrentItem); } } private _ItemContainersManager: Internal.IItemContainersManager; get ItemContainersManager(): Internal.IItemContainersManager { return this._ItemContainersManager; } constructor() { super(); this.DefaultStyleKey = ItemsControl; var coll = <ItemCollection>ItemsControl.ItemsProperty.Initialize(this); coll.ItemsChanged.on(this._OnItemsUpdated, this); this._ItemContainersManager = new Internal.ItemContainersManager(this); } PrepareContainerForItem(container: UIElement, item: any) { if (this.DisplayMemberPath != null && this.ItemTemplate != null) throw new InvalidOperationException("Cannot set 'DisplayMemberPath' and 'ItemTemplate' simultaneously"); this.UpdateContainerTemplate(container, item); } ClearContainerForItem(container: UIElement, item: any) { if (container instanceof ContentPresenter) { var cp = <ContentPresenter>container; if (cp.Content === item) cp.Content = null; } else if (container instanceof ContentControl) { var cc = <ContentControl>container; if (cc.Content === item) cc.Content = null; } } GetContainerForItem(): UIElement { return new ContentPresenter(); } IsItemItsOwnContainer(item: any): boolean { return item instanceof UIElement; } private _IsDataBound = false; private _SuspendItemsChanged = false; private _OnItemsUpdated(sender: any, e: Collections.CollectionChangedEventArgs) { if (this._SuspendItemsChanged) //Ignore OnItemsSourceChanged operations return; if (this._IsDataBound) throw new InvalidOperationException("Cannot modify Items while bound to ItemsSource."); this.OnItemsChanged(e); } private _OnItemsSourceUpdated(sender: any, e: Collections.CollectionChangedEventArgs) { var items = this.Items; try { this._SuspendItemsChanged = true; switch (e.Action) { case Collections.CollectionChangedAction.Add: for (var i = 0, len = e.NewItems.length; i < len; i++) { items.Insert(e.NewStartingIndex + i, e.NewItems[i]); } break; case Collections.CollectionChangedAction.Remove: for (var i = 0, len = e.OldItems.length; i < len; i++) { items.RemoveAt(e.OldStartingIndex); } break; case Collections.CollectionChangedAction.Replace: items.SetValueAt(e.NewStartingIndex, e.NewItems[0]); break; case Collections.CollectionChangedAction.Reset: items.Clear(); break; } } finally { this._SuspendItemsChanged = false; } this.OnItemsChanged(e); } OnItemsChanged(e: Collections.CollectionChangedEventArgs) { switch (e.Action) { case Collections.CollectionChangedAction.Add: this.OnItemsAdded(e.NewStartingIndex, e.NewItems); break; case Collections.CollectionChangedAction.Remove: this.OnItemsRemoved(e.OldStartingIndex, e.OldItems); break; case Collections.CollectionChangedAction.Replace: this.OnItemsRemoved(e.NewStartingIndex, e.OldItems); this.OnItemsAdded(e.NewStartingIndex, e.NewItems); break; case Collections.CollectionChangedAction.Reset: this.OnItemsRemoved(0, e.OldItems); break; } } OnItemsAdded(index: number, newItems: any[]) { this._ItemContainersManager.OnItemsAdded(index, newItems); var presenter = this.XamlNode.ItemsPresenter; if (presenter) presenter.OnItemsAdded(index, newItems); } OnItemsRemoved(index: number, oldItems: any[]) { var presenter = this.XamlNode.ItemsPresenter; if (presenter) presenter.OnItemsRemoved(index, oldItems); this._ItemContainersManager.OnItemsRemoved(index, oldItems); } private UpdateContainerTemplate(container: UIElement, item: any) { if (!container || container === item) return; var template: DataTemplate; if (!(item instanceof UIElement)) template = this.ItemTemplate || this._GetDisplayMemberTemplate(); if (container instanceof ContentPresenter) { var cp = <ContentPresenter>container; cp.ContentTemplate = template; cp.Content = item; } else if (container instanceof ContentControl) { var cc = <ContentControl>container; cc.ContentTemplate = template; cc.Content = item; } } private _DisplayMemberTemplate: DataTemplate = null; private _GetDisplayMemberTemplate(): DataTemplate { if (!this._DisplayMemberTemplate) { var xm = DisplayTemplate.create(this.DisplayMemberPath || ""); this._DisplayMemberTemplate = Markup.Load<DataTemplate>(this.App, xm); } return this._DisplayMemberTemplate; } } Fayde.CoreLibrary.add(ItemsControl); Markup.Content(ItemsControl, ItemsControl.ItemsProperty); function toArray(value: any): any[] { if (value instanceof Array) return <any[]>value; var enu = nullstone.IEnumerable_.as(value); if (enu) { var arr = []; for (var en = enu.getEnumerator(); en.moveNext();) { arr.push(en.current); } return arr; } return null; } module DisplayTemplate { export function create (dmp: string) { return Fayde.Markup.CreateXaml("<DataTemplate xmlns=\"" + Fayde.XMLNS + "\"><Grid><TextBlock Text=\"{Binding " + dmp + "}\" /></Grid></DataTemplate>" , Fayde.XMLNS + "/itemscontrol/displaymember/" + dmp); } } }
the_stack
* @fileoverview Tools for manipulating text in SVG. */ export enum HorizontalAlign { Left, Right, Center, } export enum VerticalAlign { Top, Bottom, Middle, } /** * Definition of the options object which the fitTextInBox() function may take. */ export interface FitTextInBoxOptions { /** * Width of the box. */ width: number; /** * Height of the box. */ height: number; /** * Width of a monospace font glyph relative to its height. */ glyphAspectRatio?: number; /** * X offset of the box to fill. */ x?: number; /** * Y offset of the box to fill. */ y?: number; /** * Height of lines as a proportion of font size. Same semantic meaning as CSS * line-height attribute when used without any units. * See: https://developer.mozilla.org/en-US/docs/Web/CSS/line-height */ lineHeight?: number; /** * How to align text horizontally (left, right, center). */ horizontalAlign?: HorizontalAlign; /** * How to align text vertically within the box (top, bottom, middle). */ verticalAlign?: VerticalAlign; } /** * Default values used by fitTextInBox() in the absence of a specified option. */ const FIT_TEXT_IN_BOX_DEFAULT_OPTIONS = { x: 0, y: 0, glyphAspectRatio: 0.6, // 0.6em wide. lineHeight: 1.1, // 10% margin between lines. horizontalAlign: HorizontalAlign.Center, verticalAlign: VerticalAlign.Middle, }; /** * The fitTextInBox() function performs a binary search when looking for the * best combination of wrapping and size to fit the text. It will never make * more than MAX_ATTEMPTS during the search. */ const MAX_ATTEMPTS = 20; /** * The fitTextInBox() uses the relative aspect ratio of a candidate wrapping and * size combination to determine whether the candidate is best. If at any time * the ratio between candidate aspect ratio and box aspect ratio is less than * EPSILON, the algorithim will short circuit rather than continuing to look. */ const EPSILON = 0.01; /** * When asked to fit() text, the TextFitter returns a tuple of lines, each with * x and y coordinates for its upper left hand corner, as well as an overall * font size in the same units as the containing box. * * So for example, if the containing box was 32x32 pixels, then semantically the * fontSize suggested would be in pixels. This will usually be the case, * although the algorithim is implementation agnostic. */ export interface TextSpecs { fontSize: number; // Same units as bounding box, typically pixels. lines: {text: string; x: number; y: number;}[]; } /** * A Segment consists of text and may be marked as containing only whitespace. * If a segment consists of only whitespace, it is considered not to add to * horizontal space when at the beginning or end of a line, and may be omitted * between lines. */ export interface Segment { text: string; whitespace: boolean; } /** * The TextFitter class exists to efficiently fit text into a bounding box. It * is meant to be called many times for different input text, given the same * options. */ export class TextFitter { /** * Text fitting settings for this instance. */ settings: FitTextInBoxOptions; constructor(options: FitTextInBoxOptions) { // Compute settings from options and defaults. this.settings = (Object as any).assign({}, FIT_TEXT_IN_BOX_DEFAULT_OPTIONS, options) as FitTextInBoxOptions; } /** * Given a text string, fit it into the box defined by this object's settings. * Return a specification detailing how the text should be laid out on a * per-line basis. * * Each line consists of text and pair of x/y coordinates. The x and y are * measured from the top left hand corner of the containing box and represent * the top left hand corner of the beginning of the line. */ fit(text: string): TextSpecs { // Split text into segments. text = text.trim(); const {max, segments} = this.split(text); // Compute best cutoff width in glyphs to approach target aspect ratio. const {cutoff, width, height} = this.computeCutoff(segments, text.length, max); // The best found width and height will almost certainly be a little too // tall or too wide to exactly fit within the target aspect ratio. The size // factor is how much bigger (or smaller) the bounding box is relative to // the glyph-based units of width and height. // If you are certain the expression is always non-null/undefined, remove // this comment. const textWidth = width * this.settings.glyphAspectRatio!; const boxAspectRatio = this.settings.width / this.settings.height; const textAspectRatio = textWidth / height; const sizeFactor = textAspectRatio > boxAspectRatio ? this.settings.width / textWidth : this.settings.height / height; // The horizontal multiplication factor (xMult) determines how much of the // horizontal space left on the line should be padded to the left. const xMult = (this.settings.horizontalAlign === HorizontalAlign.Left ? 0 : this.settings.horizontalAlign === HorizontalAlign.Right ? 1 : 0.5); // The vertical offset specifies how far from the top the first line should // appear, based on vertical alignment settings. const yOffset = Math.max(0, this.settings.height - height * sizeFactor) * (this.settings.verticalAlign === VerticalAlign.Top ? 0 : this.settings.verticalAlign === VerticalAlign.Bottom ? 1 : 0.5); const wrappedLines = this.wrapLines(segments, cutoff); // Construct final lines from wrapped lines based on settings. const lines: {text: string; x: number; y: number;}[] = []; for (let i = 0; i < wrappedLines.length; i++) { const {startPos, endPos, textLength} = wrappedLines[i]; let lineText = ''; for (let j = startPos; j < endPos; j++) { const segment = segments[j]; lineText += segment.text; } // If you are certain the expression is always non-null/undefined, remove // this comment. const xdiff = this.settings.width - lineText.length * this.settings.glyphAspectRatio! * sizeFactor; // If you are certain the expression is always non-null/undefined, remove // this comment. lines.push({ text: lineText, x: this.settings.x! + xMult * Math.max(0, xdiff), y: this.settings.y! + yOffset + i * this.settings.lineHeight! * sizeFactor, }); } return {lines, fontSize: sizeFactor}; } /** * Given a text string, break it up into a sequence of strings, some of which * may consist of only whitespace. */ split(text: string) { const segments: Segment[] = []; let pos = 1; let prev = text.charAt(0); let prevW = /\s/.test(prev); let start = 0; let max = 0; while (pos <= text.length) { const ch = text.charAt(pos); const chW = /\s/.test(ch); if (!ch.length || prevW !== chW) { // We've found a word boundary or end of string. max = Math.max(max, pos - start); segments.push({ text: text.substring(start, pos), whitespace: prevW, }); start = pos; } prev = ch; prevW = chW; pos++; } return {max, segments}; } /** * Given a collection of segments and a proposed bounding width (in glyphs), * compute the bounding rectangle that would contain the wrapped text. */ computeTextRect(segments: Segment[], proposedWidth: number) { // Total length of the current row, including trailing whitespace. let rowLength = 0; // Length of current row, ignoring trailing whitespace. let trimmedRowLength = 0; // Longest row length encountered (ignores trailing whitespace). let maxLength = 0; // Total accumulated height of rows. let totalHeight = 1; for (let i = 0; i < segments.length; i++) { const {text, whitespace} = segments[i]; const length = text.length; if (whitespace && !rowLength) { // Short-circuit for whitespace at the beginning of a line. continue; } if (whitespace) { if (rowLength + length <= proposedWidth) { rowLength += length; } else { rowLength = 0; trimmedRowLength = 0; // If you are certain the expression is always non-null/undefined, // remove this comment. totalHeight += this.settings.lineHeight!; } } else { if (rowLength + length <= proposedWidth) { // Still room on this row. rowLength += length; trimmedRowLength = rowLength; } else if (trimmedRowLength) { // Not enough room on this row, start another. rowLength = trimmedRowLength = length; // If you are certain the expression is always non-null/undefined, // remove this comment. totalHeight += this.settings.lineHeight!; } else { // This individual segment is too long for the proposed width, so // it goes on a line by itself. maxLength = Math.max(maxLength, length); rowLength = trimmedRowLength = 0; // If you are certain the expression is always non-null/undefined, // remove this comment. totalHeight += this.settings.lineHeight!; } } maxLength = Math.max(maxLength, trimmedRowLength); } return {width: maxLength, height: totalHeight}; } /** * Perform a binary search to find the optimal width cutoff to achive the * desired aspect ratio for wrapped text. The minumum bound is the width of * the single longest segment. The maximum is the total length of all * segments. */ computeCutoff(segments: Segment[], total: number, max: number) { const targetAspectRatio = this.settings.width / this.settings.height; let low = max; let high = total; let proposedWidth = low + (high - low) / 2; let bestWidth = proposedWidth; let bestTextRect: {width: number; height: number;} = null!; let bestErr = Infinity; // The true best wrapping must be discoverabe in fewer attempts than half // the number of segments. const maxAttempts = Math.min(MAX_ATTEMPTS, (segments.length + 1) / 2); let attempts = 0; while (attempts < maxAttempts) { attempts++; const textRect = this.computeTextRect(segments, proposedWidth); // If you are certain the expression is always non-null/undefined, remove // this comment. const computedAspectRatio = textRect.width / textRect.height * this.settings.glyphAspectRatio!; const err = Math.abs(1 - (computedAspectRatio / targetAspectRatio)); if (err < bestErr) { bestWidth = proposedWidth; bestTextRect = textRect; bestErr = err; } if (err < EPSILON) { break; } if (computedAspectRatio > targetAspectRatio) { // If the computed aspect ratio is too high, then the text should // ideally wrap more, meaning our proposed width is too big and we // should narrow it down. high = proposedWidth; } else { // Otherwise, the text is probably too wrapped and we should ease up by // increasing the proposed width. low = proposedWidth; } proposedWidth = low + (high - low) / 2; } return { cutoff: bestWidth, width: bestTextRect.width, height: bestTextRect.height }; } /** * Wrap segments into lines based on the cutoff. The return value is a list * of line objects, each indicating the start and end offsets into the * segments array along with the total length of segments in than slice. */ wrapLines(segments: Segment[], cutoff: number) { const lines: {startPos: number, endPos: number, textLength: number}[] = []; let startPos = 0; let endPos = 0; let lineLength = 0; let trimmedLineLength = 0; for (let i = 0; i < segments.length; i++) { const {text, whitespace} = segments[i]; const length = text.length; if (whitespace && !lineLength) { // Ignore whitespace at the beginning of a line. startPos = endPos = i + 1; continue; } if (whitespace) { if (lineLength + length <= cutoff) { // There's room to add this segment on the current line. lineLength += length; } else { // This segment pushes us over. lines.push({ startPos, endPos, textLength: trimmedLineLength, }); lineLength = trimmedLineLength = 0; startPos = endPos = i + 1; } } else { if (lineLength + length <= cutoff) { // There's room to add this segment on the current line. lineLength += length; trimmedLineLength = lineLength; endPos = i + 1; } else if (trimmedLineLength) { // The segment pushes us over, and the line has content already. lines.push({ startPos, endPos, textLength: trimmedLineLength, }); lineLength = trimmedLineLength = length; startPos = i; endPos = i + 1; } else { // This single segment exceeds the cutoff. lines.push({ startPos: i, endPos: i + 1, textLength: length, }); lineLength = trimmedLineLength = 0; startPos = endPos = i + 1; } } } if (endPos > startPos) { lines.push({ startPos, endPos, textLength: trimmedLineLength, }); } return lines; } }
the_stack
import type { SuggestionCostMapDef } from '../models/suggestionCostsDef'; import { DEFAULT_COMPOUNDED_WORD_SEPARATOR } from '../suggestions/suggestCollector'; import { addAdjustment, addDefToWeightMap, CostPosition, createWeightMap, lookupReplaceCost, PenaltyAdjustment, prettyPrintWeightMap, __testing__, } from './weightedMaps'; const { splitMapSubstrings, splitMap, findTrieCostPrefixes, normalizeDef } = __testing__; const oc = expect.objectContaining; // const u = undefined; cspell: describe('Validate weightedMaps', () => { test.each` map | expected ${''} | ${[]} ${'abc'} | ${'abc'.split('')} ${'f(ph)(gh)v'} | ${['f', 'ph', 'gh', 'v']} `('splitMapSubstrings "$map"', ({ map, expected }) => { expect(splitMapSubstrings(map)).toEqual(expected); }); test.each` map | expected ${''} | ${[]} ${'||'} | ${[]} ${'abc'} | ${['abc'.split('')]} ${'abc|'} | ${['abc'.split('')]} ${'f(ph)(gh)v|eé'} | ${[['f', 'ph', 'gh', 'v'], ['e', 'é', 'é'.normalize('NFD')]]} ${'f(ph)(😁)🤣|eé'} | ${[['f', 'ph', '😁', '🤣'], ['e', 'é', 'é'.normalize('NFD')]]} `('splitMap "$map"', ({ map, expected }) => { expect(splitMap({ map })).toEqual(expected); }); test.each` defs | expected ${[]} | ${oc({ insDel: {}, replace: {}, swap: {} })} ${[defIns('ab', 3)]} | ${oc({ insDel: { n: { a: { c: 3 }, b: { c: 3 } } }, replace: {}, swap: {} })} ${[defIns('ab', 3), defIns('bc', 2)]} | ${oc({ insDel: { n: { a: { c: 3 }, b: { c: 2 }, c: { c: 2 } } }, replace: {}, swap: {} })} ${[defRep('ab', 3)]} | ${oc({ insDel: {}, replace: { n: { a: { t: { n: { b: { c: 3 } } } }, b: { t: { n: { a: { c: 3 } } } } } }, swap: {} })} ${[defSwap('ab', 3)]} | ${oc({ insDel: {}, replace: {}, swap: { n: { a: { t: { n: { b: { c: 3 } } } }, b: { t: { n: { a: { c: 3 } } } } } } })} `('buildWeightMap $defs', ({ defs, expected }) => { expect(createWeightMap(...defs)).toEqual(expected); }); test.each` def1 | def2 | def3 ${undefined} | ${undefined} | ${undefined} ${defIns('ab', 3)} | ${undefined} | ${undefined} ${defIns('ab', 3)} | ${defIns('bc', 2)} | ${undefined} ${defRep('ab', 3)} | ${undefined} | ${undefined} ${defSwap('ab', 3)} | ${undefined} | ${undefined} ${defRep('(ei)(ie)', 3)} | ${undefined} | ${undefined} ${defRep('(ei)(ie)e', 3, { insDel: 11, swap: 4 })} | ${{ map: 'aeiou', replace: 4, insDel: 7 }} | ${defRep('eio', 1, { swap: 3 })} `('buildWeightMap pp $def1, $def2, $def2', ({ def1, def2, def3 }) => { const defs = [def1, def2, def3].filter((a) => !!a); const pp = prettyPrintWeightMap(createWeightMap(...defs)); expect(pp).toMatchSnapshot(); const map2 = defs.reverse().reduce((map, def) => addDefToWeightMap(map, def), createWeightMap()); expect(prettyPrintWeightMap(map2)).toBe(pp); }); test.each` defs | word | offset | expected ${[]} | ${''} | ${1} | ${[]} ${[defIns('aeiou', 7, penalty(5)), defIns('(ae)(ea)(ou)(ei)(ie)', 11)]} | ${'read'} | ${1} | ${[{ i: 2, c: 7, p: 5 }, { i: 3, c: 11, p: 0 }] /* cspell:disable-line */} ${[defIns('aeiou', 7, penalty(5)), defIns('(ae)(ea)(ou)(ei)(ie)', 11)]} | ${'read'} | ${2} | ${[{ i: 3, c: 7, p: 5 }] /* cspell:disable-line */} `('findTrieCostPrefixes with insDel $defs.0 $defs.1 $word $offset', ({ defs, word, offset, expected }) => { const map = createWeightMap(...defs); expect([...findTrieCostPrefixes(map.insDel, word, offset)]).toEqual(expected); }); // cspell:ignore aeiou test.each` defs | wordA | ai | wordB | bi | expected ${[]} | ${''} | ${1} | ${''} | ${0} | ${[]} ${[defIns('aeiou', 7), defIns('(ae)(ea)(ou)(ei)(ie)', 11)]} | ${'read'} | ${1} | ${''} | ${0} | ${[{ ai: 2, bi: 0, c: 1007, p: 1000 }, { ai: 3, bi: 0, c: 1011, p: 1000 }]} ${[defIns('aeiou', 7), defIns('(ae)(ea)(ou)(ei)(ie)', 11)]} | ${'read'} | ${1} | ${'ride'} | ${1} | ${[{ ai: 2, bi: 1, c: 1007 /* del e */, p: 1000 }, { ai: 3, bi: 1, c: 1011 /* del ea */, p: 1000 }, { ai: 1, bi: 2, c: 1007 /* ins i */, p: 1000 }]} ${[defIns('aeiou', 7), defIns('(ae)(ea)(ou)(ei)(ie)', 11)]} | ${'red'} | ${1} | ${'read'} | ${1} | ${[{ ai: 2, bi: 1, c: 1007 /* del e */, p: 1000 }, { ai: 1, bi: 2, c: 1007 /* ins */, p: 1000 }, { ai: 1, bi: 3, c: 1011 /* ins ea */, p: 1000 }]} ${[defIns('aeiou', 7), defIns('(ae)(ea)(ou)(ei)(ie)', 11)]} | ${'red'} | ${2} | ${'read'} | ${2} | ${[{ ai: 2, bi: 3, c: 1007 /* ins a */, p: 1000 }]} ${[defIns('1234567890', 7, penalty(20))]} | ${'cost'} | ${4} | ${'cost8'} | ${4} | ${[{ ai: 4, bi: 5, c: 1007 /* insert 8 */, p: 1020 }]} `( 'calcInsDelCosts with $defs.0 $defs.1 "$wordA"@$ai, "$wordB"@$bi', ({ defs, wordA, ai, wordB, bi, expected, }: { defs: SuggestionCostMapDef[]; wordA: string; wordB: string; ai: number; bi: number; expected: CostPosition[]; }) => { const map = createWeightMap(...defs); const results = [...map.calcInsDelCosts({ a: wordA, b: wordB, ai, bi, c: 1000, p: 1000 })]; expected.forEach((p) => { (p.a = p.a ?? wordA), (p.b = p.b ?? wordB); }); expect(results).toEqual(expect.arrayContaining(expected)); expect(results).toHaveLength(expected.length); } ); test.each` defs | wordA | ai | wordB | bi | expected ${[]} | ${''} | ${0} | ${''} | ${0} | ${[]} ${[defRep('aeiou', 5), defRep('ae(ae)(ea)', 7)]} | ${'read'} | ${1} | ${'red'} | ${1} | ${[{ ai: 3, bi: 2, c: 1007 /* ea -> a */, p: 1000 }]} ${[defRep('aeiou', 5), defRep('ae(ae)(ea)', 7)]} | ${'read'} | ${1} | ${'road'} | ${1} | ${[{ ai: 2, bi: 2, c: 1005 /* e -> o */, p: 1000 }]} ${[defRep('aeiou', 5), defRep('o(oo)|e(ee)', 7)]} | ${'met'} | ${1} | ${'meet'} | ${1} | ${[{ ai: 2, bi: 3, c: 1007 /* e -> ee */, p: 1000 }]} ${[defRep('aeiou', 5), defRep('o(oo)|e(ee)', 7)]} | ${'meet'} | ${1} | ${'met'} | ${1} | ${[{ ai: 3, bi: 2, c: 1007 /* ee -> e */, p: 1000 }]} ${[defRep('aeiou', 5), defRep('(ei)(ie)', 7)]} | ${'believe'} | ${3} | ${'receive'} | ${3} | ${[{ ai: 4, bi: 4, c: 1005 /* i => e */, p: 1000 }, { ai: 5, bi: 5, c: 1007 /* ie => ei */, p: 1000 }]} ${[defRep('(sk)(sch)', 5), defRep('(sch)(sk)', 7)]} | ${'school'} | ${0} | ${'skull'} | ${0} | ${[{ ai: 3, bi: 2, c: 1005 /* sch => sk */, p: 1000 }]} `( 'calcReplaceCosts with $defs.0 $defs.1 "$wordA"@$ai, "$wordB"@$bi', ({ defs, wordA, ai, wordB, bi, expected, }: { defs: SuggestionCostMapDef[]; wordA: string; wordB: string; ai: number; bi: number; expected: CostPosition[]; }) => { const map = createWeightMap(...defs); const results = [...map.calcReplaceCosts({ a: wordA, b: wordB, ai, bi, c: 1000, p: 1000 })]; expected.forEach((p) => { (p.a = p.a ?? wordA), (p.b = p.b ?? wordB); }); expect(results).toEqual(expect.arrayContaining(expected)); expect(results).toHaveLength(expected.length); } ); test.each` defs | wordA | ai | wordB | bi | expected ${[defSwap('ae', 9), defSwap('ei', 7)]} | ${'believe'} | ${1} | ${'receive'} | ${1} | ${[]} ${[defSwap('ae', 9), defSwap('ei', 7)]} | ${'believe'} | ${3} | ${'receive'} | ${3} | ${[{ ai: 5, bi: 5, c: 1007 /* swap ei -> ie */, p: 1000 }]} ${[defSwap('ei', 7, penalty(20))]} | ${'believe'} | ${3} | ${'receive'} | ${3} | ${[{ ai: 5, bi: 5, c: 1007 /* swap ei -> ie */, p: 1020 }]} `( 'calcSwapCosts with $defs.0 $defs.1 "$wordA"@$ai, "$wordB"@$bi', ({ defs, wordA, ai, wordB, bi, expected, }: { defs: SuggestionCostMapDef[]; wordA: string; wordB: string; ai: number; bi: number; expected: CostPosition[]; }) => { const map = createWeightMap(...defs); const results = [...map.calcSwapCosts({ a: wordA, b: wordB, ai, bi, c: 1000, p: 1000 })]; expected.forEach((p) => { (p.a = p.a ?? wordA), (p.b = p.b ?? wordB); }); expect(results).toEqual(expect.arrayContaining(expected)); expect(results).toHaveLength(expected.length); } ); test.each` defs | wordA | wordB | expected ${[defRep('ae', 9), defRep('ei', 7)]} | ${'a'} | ${'e'} | ${9} ${[defRep('ae', 9), defRep('ei', 7)]} | ${'a'} | ${'i'} | ${undefined} ${[defRep('o(oo)(oh)', 9), defRep('o(oo)(ooo)', 7)]} | ${'oo'} | ${'o'} | ${7} ${[defRep('o(oo)(oh)', 9), defRep('o(oo)(ooo)', 7)]} | ${'oo'} | ${'oh'} | ${9} `('calcSwapCosts with $defs.0 $defs.1 "$wordA", "$wordB"', ({ defs, wordA, wordB, expected }) => { const map = createWeightMap(...defs); const results = lookupReplaceCost(map, wordA, wordB); expect(results).toEqual(expected); }); test.each` def | expected ${defIns('(+A)(+B)', 50, { penalty: 150 })} | ${defIns(sep('(|A)(|B)'), 50, { penalty: 150 })} ${defIns('abc', 95)} | ${defIns('abc', 95)} `('normalizeDef for compound separators $def', ({ def, expected }) => { expect(normalizeDef(def)).toEqual(expected); }); test.each` adjustments | word | expected ${[]} | ${'hello'} | ${0} ${[adj('case-change', /\p{Ll}∙\p{Lu}|\p{Lu}∙\p{Ll}/gu, 500)]} | ${'hello∙There'} | ${500} ${[adj('case-change', /\p{Ll}∙\p{Lu}|\p{Lu}∙\p{Ll}/gu, 500)]} | ${'WORK∙ed'} | ${500} ${[adj('case-change', /\p{Ll}∙\p{Lu}|\p{Lu}∙\p{Ll}/gu, 500)]} | ${'WORK∙ed∙Fine'} | ${1000} ${[adj('case-change', /\p{Ll}∙\p{Lu}|\p{Lu}∙\p{Ll}/u, 500)]} | ${'WORK∙ed∙Fine'} | ${500} `('calcAdjustment $adjustments $word', ({ adjustments, word, expected }) => { const w = createWeightMap(); addAdjustment(w, ...adjustments); expect(w.calcAdjustment(word)).toEqual(expected); }); }); function sep(s: string): string { return s.replace(/[|+]/g, DEFAULT_COMPOUNDED_WORD_SEPARATOR); } // function mo(...opts: Partial<SuggestionCostMapDef>[]): Partial<SuggestionCostMapDef> { // return mergeOps(opts); // } function penalty(penalty: number): Partial<SuggestionCostMapDef> { return { penalty }; } function defIns(map: string, insDel: number, ...opts: Partial<SuggestionCostMapDef>[]): SuggestionCostMapDef { return { ...mergeOps(opts), map, insDel }; } function defRep(map: string, replace: number, ...opts: Partial<SuggestionCostMapDef>[]): SuggestionCostMapDef { return { ...mergeOps(opts), map, replace }; } function defSwap(map: string, swap: number, ...opts: Partial<SuggestionCostMapDef>[]): SuggestionCostMapDef { return { ...mergeOps(opts), map, swap }; } function mergeOps(opts: Partial<SuggestionCostMapDef>[]): Partial<SuggestionCostMapDef> { return opts.reduce((acc, opt) => ({ ...acc, ...opt }), {} as Partial<SuggestionCostMapDef>); } function adj(id: string, regexp: RegExp, penalty: number): PenaltyAdjustment { return { id, regexp, penalty }; }
the_stack