text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { Table } from "./Table"
import { PostgreSqlConnection } from "./connections/PostgreSqlConnection"
import { ConsoleLogNoopQueryRunner } from "./queryRunners/ConsoleLogNoopQueryRunner"
import { View } from "./View"
import { ConsoleLogQueryRunner } from "./queryRunners/ConsoleLogQueryRunner"
import { NoopQueryRunner } from "./queryRunners/NoopQueryRunner"
import { TypeSafeMySqlConnection } from "./connections/TypeSafeMySqlConnection"
import { MockQueryRunner } from "./queryRunners/MockQueryRunner"
import { CustomBooleanTypeAdapter } from "./TypeAdapter"
import { DynamicCondition } from "./expressions/dynamicConditionUsingFilters"
import { dynamicPick } from "./dynamicCondition"
import { extractColumnsFrom, mapForGuidedSplit, mergeType, prefixCapitalized, prefixDotted, prefixMapForGuidedSplitCapitalized, prefixMapForGuidedSplitDotted, prefixMapForSplitCapitalized, prefixMapForSplitDotted } from "./extras/utils"
// import { InterceptorQueryRunner, QueryType } from "./queryRunners/InterceptorQueryRunner"
// import { TypeSafeNoopConnection } from "./clients/TypeSafeNoopConnection"
// import { int } from "ts-extended-types"
class MyConection extends PostgreSqlConnection<'MyConnection'> {
procedure1(p1: number) {
return this.executeProcedure('procedure1', [this.const(p1, 'int')])
}
function1(p1: number) {
return this.executeFunction('function1', [this.const(p1, 'int')], 'int', 'required')
}
now = this.buildFragmentWithArgs().as(() => {
return this.fragmentWithType('localDateTime', 'required').sql`now()`
})
isBigFactorial = this.buildFragmentWithArgs(
this.arg('int', 'required'),
this.arg('int', 'required')
).as((a1, a2) => {
return this.fragmentWithType('boolean', 'required').sql`!!${a1} > ${a2}`
})
transformValueFromDB(value: any, type: any) {
if (type === 'json') {
return JSON.parse(value);
}
return super.transformValueFromDB(value, type);
}
transformValueToDB(value: any, type: any) {
if (type === 'json') {
return JSON.stringify(value);
}
return super.transformValueToDB(value, type);
}
}
class MyTable extends Table<MyConection, 'MyTable'> {
id = this.autogeneratedPrimaryKeyBySequence('id', 'mySeq', 'int')
c = this.column('c', 'int')
d = this.column('d', 'string')
e = this.columnWithDefaultValue('e', 'localDateTime')
oc = this.optionalColumn('oc', 'int')
od = this.optionalColumn('od', 'string')
oe = this.optionalColumn('oe', 'localDateTime')
bool = this.optionalColumn('bool', 'boolean')
customBool = this.column('custom_boolean', 'boolean', new CustomBooleanTypeAdapter('t', 'f'))
optCustomBool = this.optionalColumn('opt_custom_boolean', 'boolean', new CustomBooleanTypeAdapter('Y', 'N'))
computed = this.computedColumn('computed', 'string')
optComputed = this.optionalComputedColumn('opt_computed', 'string')
constructor() {
super('t')
}
}
// interface DurationPlayload {
// startTime: number
// }
// class DurationLogginQueryRunner extends InterceptorQueryRunner<DurationPlayload> {
// onQuery(queryType: QueryType, query: string, params: any[]): DurationPlayload {
// console.log('onQuery', queryType, query, params)
// return { startTime: Date.now() }
// }
// onQueryResult(queryType: QueryType, query: string, params: any[], result: any, playload: DurationPlayload): void {
// const duration = Date.now() - playload.startTime
// console.log('onQueryResult', queryType, query, params, result, duration)
// }
// onQueryError(queryType: QueryType, query: string, params: any[], error: any, playload: DurationPlayload): void {
// const duration = Date.now() - playload.startTime
// console.log('onQueryError', queryType, query, params, error, duration)
// }
// }
// declare var a: ColumnsOf<MyConection, MyTable>
// declare var aa: keyof MyTable
// declare var ate: TypeOfColumn<MyConection, MyTable, 'oe'>
let t = new MyTable()
// class MyConection2 extends NoopConnection<MyConection2, 'MyConection2'> {
// }
let q = new class MyTable2 extends Table<MyConection, 'MyTable2'> {
f = this.column('f', 'int')
g = this.optionalColumn('g', 'string')
constructor() {
super('q')
}
}()
let cn = new MyConection(new ConsoleLogNoopQueryRunner())
cn.const(10, 'int')
let query = cn.insertInto(t)
.set({ c: 10, d: '', oc: 20, bool: true, customBool: true }).setIfValue({ c: null, e: cn.default() })
// .set(t.c).value(10)
// .set(t.c).value(12)
.ignoreIfSet('e').returningLastInsertedId()
console.log(query.query(), query.params())
const query0 = cn.insertInto(t)
.from(
cn.selectFrom(t)
.where(
t.bool
)
.select({
c: t.c,
d: t.d,
bool: t.customBool,
customBool: t.customBool,
optCustomBool: t.customBool
})
)
console.log(query0.query(), query0.params())
// query = cn.insertInto(t).dynamicSet().set({ c: 10 }).set({d: ''})
// console.log(query.query(), query.params())
// query = cn.insertInto(q).defaultValues()
// console.log(query.query(), query.params())
let query1 = cn.updateAllowingNoWhere(t)
.set({c: t.c, d: 'hola', e: new Date(), bool: t.bool.negate(), customBool: true})
.set({ c: 11 })
.set({ e: cn.default() })
.ignoreIfSet('e')
// .set(t.c).value(10)
// .set(t.c).value(11)
console.log(query1.query(), query1.params())
//let m = t.c.power(10)
// let mm = t.c.power(cn.pi())
// let mm1 = t.c.power(mm)
// let mm2 = t.c.power(q.c)
// let mm3 = cn.pi().power(cn.pi()).equals(3)
// let mm4 = cn.const(3).power(10).lessOrEquals(mm1)
// let cond = mm1.greaterOrEquals(7).negate()
const di: any = {}
let where
where = cn.true()
if (di.a) {
where = where.and(t.c.lessOrEquals(10))
}
if (!di.b) {
where = where.and(t.c.lessThan(1))
}
where = where.and(t.c.equals(2))
let query2 = cn.update(t)
.set({ c: t.c })
.where(where)
// .where(t.c.greaterThan(10).and(t.c.greaterThan(1)))
// .where(cn.pi().power(t.c).equals(3).and(t.c.greaterThan(10)))
// .whereAnd(
// cn.pi().power(t.c).equals(3),
// t.c.greaterOrEquals(10)
// )
// .set(t.c).value(t.c).where(cn.pi().power(t.c).equals(3))
console.log(query2.query(), query2.params())
q.f.abs()
let query3 = cn.update(t)
.set({ d: 'hello' })
.dynamicWhere()
query3 = query3.and(t.c.greaterOrEquals(10))
query3 = query3.and(t.d.equals('mm'))
console.log(query3.query(), query3.params())
let query4 = cn.deleteFrom(t)
.dynamicWhere()
query4 = query4.and(t.c.greaterOrEquals(33))
query4 = query4.and(t.d.equals('zz'))
console.log(query4.query(), query4.params())
// import { Table, Column } from "./query"
// import { PostgreSqlConnection } from "./client/postgreSql/postgreSql"
// let t = new Table(undefined, 't')
// let c = new Column<number>('c')
// let cn = new PostgreSqlConnection()
// cn.insertInto(t)
// .set(c).value(10)
// .set(c).value(12)
// .onConflictOnConstraint('f').doNothing().returningAll().execute()
let query5 = cn.selectFrom(t).where(t.c.equals(10)).and(t.bool).select({
d: t.d,
od: t.od,
e: t.e,
bool: cn.true().equals(t.bool.equals(t.bool)),
isBigFactorial: cn.isBigFactorial(t.c, 100),
now: cn.now(),
customBool: t.customBool,
optCustomBool: t.optCustomBool
}).orderByFromString('d, od desc, e asc').limit(5).offset(4)
//let r5 = query5.executeSelectOne()
console.log(query5.query(), query5.params())
let query6 = cn.selectDistinctFrom(t).where(t.c.is(10)).and(t.od.isNot('d')).and(t.customBool.equals(t.optCustomBool)).select({
d: t.d,
od: t.od
})
//let r6 = query6.executeSelectOne()
console.log(query6.query(), query6.params())
let q2 = q.as('a')
let query7 = cn.selectFrom(t).from(q2).where(t.c.equals(q2.f)).select({
d: t.d,
f: q2.f
})
//let r7 = query7.executeSelectOne()
console.log(query7.query(), query7.params())
let query8 = cn.selectFromNoTable().select({
date: cn.currentDate()
})
//let r8 = query8.executeSelectOne()
console.log(query8.query(), query8.params())
let query9 = cn.selectFrom(t).join(q).on(t.c.equals(q.f)).where(t.c.equals(10)).and(t.od.notEquals('d')).select({
d: t.d,
od: t.od,
f: q.f
})
//let r9 = query9.executeSelectOne()
console.log(query9.query(), query9.params())
let query10 = cn.selectFrom(t)
.innerJoin(q).dynamicOn().and(t.c.equals(q.f)).and(t.c.greaterOrEquals(12))
.where(t.c.equals(10)).and(t.od.notEquals('d'))
.select({
d: t.d,
od: t.od,
f: q.f
})
//let r10 = query10.executeSelectOne()
console.log(query10.query(), query10.params())
var ot = t.forUseInLeftJoinAs('jo')
let query11 = cn.selectFrom(q)
.leftOuterJoin(ot).on(ot.c.equals(q.f))
.innerJoin(q).on(ot.c.equals(q.f))
.where(ot.c.equals(10)).and(ot.od.notEquals('d'))
.select({
d: ot.d,
od: ot.od,
f: q.f
}).limit(10)
//let r11 = query11.executeSelectOne()
console.log(query11.query(), query11.params())
let subquery12 = cn.selectFrom(q).where(q.f.equals(1)).select({f: q.f})
let query12 = cn.selectDistinctFrom(t).where(t.c.equals(10)).and(cn.exists(subquery12)).select({
d: t.d,
od: t.od
})
//let r12 = query12.executeSelectOne()
console.log(query12.query(), query12.params())
let subquery13 = cn.subSelectUsing(t).from(q).where(q.f.equals(t.c)).select({f: q.f})
let query13 = cn.selectDistinctFrom(t).where(t.c.equals(10)).and(cn.notExists(subquery13)).select({
d: t.d,
od: t.od
})
//let r13 = query13.executeSelectOne()
console.log(query13.query(), query13.params())
let subquery14 = cn.selectFrom(q).where(q.f.equals(1)).selectOneColumn(q.f)
let query14 = cn.selectDistinctFrom(t).where(t.c.equals(10)).and(t.c.in(subquery14)).select({
d: t.d,
od: t.od
})
//let r14 = query14.executeSelectOne()
console.log(query14.query(), query14.params())
let subquery15 = cn.subSelectUsing(t).from(q).where(q.f.equals(t.c)).selectOneColumn(q.f)
let query15 = cn.selectDistinctFrom(t).where(t.c.equals(10)).and(t.c.notIn(subquery15)).select({
d: t.d,
od: t.od
})
//let r15 = query15.executeSelectOne()
console.log(query15.query(), query15.params())
cn.procedure1(16)
cn.function1(17).catch(_ => undefined) // ignore error
//cn.fragment`${t.c} <|> ${cn.const(7, 'int')}`.withType('boolean', 'required')
let query16 = cn.selectFrom(t).where(t.c.equals(9)).and(cn.fragmentWithType('boolean', 'required').sql`${t.c} <|> ${cn.const(7, 'int')}`).select({
d: cn.fragmentWithType('int', 'required').sql`max2(${t.d})`,
od: t.od
})
//let r16 = query16.executeSelectOne()
console.log(query16.query(), query16.params())
let query17 = cn.selectFrom(t).where(t.c.equals(10)).and(t.bool).select({
cd: t.d,
cod: t.od,
ce: t.e,
cbool: cn.true().equals(t.bool.equals(t.bool))
}).groupBy('cd', 'cod').groupBy('ce').orderByFromString('cd, cod desc, ce asc').limit(5).offset(4)
//let r5 = query5.executeSelectOne()
console.log(query17.query(), query17.params())
let query18 = cn.selectFrom(t).where(t.c.equals(10)).and(t.bool).select({
cd: t.d,
cod: t.od,
ce: t.e,
cbool: cn.true().equals(t.bool.equals(t.bool))
}).groupBy(t.d, t.od).groupBy(t.e).orderByFromString('cd, cod desc, ce asc').limit(5).offset(4)
//let r5 = query5.executeSelectOne()
console.log(query18.query(), query18.params())
let query19 = cn.selectFrom(t).where(t.c.equals(10)).and(t.bool).select({
cd: t.d,
cod: t.od,
ce: t.e,
cbool: cn.true().equals(t.bool.equals(t.bool))
}).groupBy('cd', 'cod').groupBy('ce').having(t.d.equals('a')).and(t.od.isNotNull()).orderByFromString('cd, cod desc, ce asc').limit(5).offset(4)
//let r5 = query5.executeSelectOne()
console.log(query19.query(), query19.params())
let query20 = cn.selectFrom(t).where(t.c.equals(10)).and(t.bool).select({
cd: t.d,
cod: t.od,
ce: t.e,
cbool: cn.true().equals(t.bool.equals(t.bool))
}).groupBy(t.d, t.od).groupBy(t.e).dynamicHaving().and(t.d.equals('a')).or(t.od.isNotNull()).orderByFromString('cd, cod desc, ce asc').limit(5).offset(4)
//let r5 = query5.executeSelectOne()
console.log(query20.query(), query20.params())
let query21 = cn.selectFrom(t).where(t.c.equals(10)).and(t.bool).groupBy(t.d, t.od).groupBy(t.e).select({
cd: t.d,
cod: t.od,
ce: t.e,
cbool: cn.true().equals(t.bool.equals(t.bool))
}).orderByFromString('cd, cod desc, ce asc').limit(5).offset(4)
//let r5 = query5.executeSelectOne()
console.log(query21.query(), query21.params())
let query22 = cn.selectFrom(t).where(t.c.equals(10)).and(t.bool).groupBy(t.d, t.od).groupBy(t.e).dynamicHaving().and(t.d.equals('a')).or(t.od.isNotNull()).select({
cd: t.d,
cod: t.od,
ce: t.e,
cbool: cn.true().equals(t.bool.equals(t.bool))
}).orderByFromString('cd, cod desc, ce asc').limit(5).offset(4)
//let r5 = query5.executeSelectOne()
console.log(query22.query(), query22.params())
let query23 = cn.selectFrom(t).where(t.c.equals(10)).and(t.bool).groupBy(t.od, t.e).select({
count: cn.stringConcat(t.d),
cod: t.od,
ce: t.e
}).orderByFromString('count, cod desc, ce asc').limit(5).offset(4)
//let r5 = query5.executeSelectOne()
console.log(query23.query(), query23.params())
cn.rollback()
const pushers = new (class extends Table<MyConection, 'pushers'> {
id = this.primaryKey('id', 'string');
meta = this.column<any>('meta', 'custom', 'json');
tags = this.column<string[]>('tags', 'custom', 'json');
constructor() {
super('pushers');
}
})();
let query24 = cn.insertInto(pushers).values({id:'uuid', meta: { whatever: 123 }, tags:['a', 'b', 'c']})
console.log(query24.query(), query24.params())
/********************************************************************************************** */
class AConection extends TypeSafeMySqlConnection<'adb'> { }
const tPerson = new class TPerson extends Table<AConection, 'TPerson'> {
public id = this.autogeneratedPrimaryKey("id", "int");
public email = this.column("email", "string");
public name = this.column("name", "string");
public tfn = this.column("tfn", "string");
public countryId = this.column("countryId", "int"); // FK
constructor() {
super("person"); // table name in the database
}
}()
const tUser = new class TUser extends Table<AConection, 'TUser'> {
public id = this.autogeneratedPrimaryKey("id", "int");
public personId = this.column("personId", "int");
public passwdId = this.column("passwdId", "int");
public dateRegister = this.column("dateRegister", "localDateTime");
public acceptGdpr = this.column("acceptGdpr", "boolean");
public enabled = this.column("enabled", "boolean");
public signInType = this.column("signInType", "int");
constructor() {
super("user"); // table name in the database
}
}()
const tPasswd = new class TPasswd extends Table<AConection, 'TPasswd'> {
public id = this.autogeneratedPrimaryKey("id", "int");
public passwd = this.column("passwd", "string");
public dateInit = this.column("dateInit", "localDateTime");
public dateEnd = this.column("dateEnd", "localDateTime");
constructor() {
super("passwd"); // table name in the database
}
}()
const cnn = new AConection(new ConsoleLogQueryRunner(new NoopQueryRunner()))
const username = 'un'
const passwords = tPasswd.as("passwords")
const persons = tPerson.as("persons")
const queryHandle = cnn
.selectFrom(tUser)
.join(persons).on(tUser.personId.equals(persons.id))
.join(passwords).on(tUser.passwdId.equals(passwords.id))
.where(persons.name.equals(username))
.and(tUser.acceptGdpr)
.and(tUser.enabled)
.selectOneColumn(passwords.passwd)
const querya = queryHandle.query()
const parmsa = queryHandle.params()
console.log(querya, parmsa);
/********************************************************************************************** */
class DBConection extends PostgreSqlConnection<'DBConnection'> {
// insesitiveCollation = 'acs'
bitwiseShiftLeft = this.buildFragmentWithArgs(
this.arg('int', 'required'),
this.arg('int', 'required')
).as((left, right) => {
// The fragment here is: ${left} << ${right}
// Could be another fragment like a function call: myFunction(${left}, ${right})
return this.fragmentWithType('int', 'required').sql`${left} << ${right}`
})
valuePlusOneEqualsIfValue = this.buildFragmentWithArgsIfValue(
this.arg('int', 'required'),
this.valueArg('int', 'optional')
).as((left, right) => {
// The fragment here is: ${left} + 1 = ${right}
// Could be another fragment like a function call: myFunction(${left}, ${right})
return this.fragmentWithType('boolean', 'required').sql`${left} + 1 = ${right}`
})
forSystemTimeBetween = this.createTableOrViewCustomization<Date, Date>((table, alias, fromDate, toDate) => {
const from = this.const(fromDate, 'localDateTime')
const to = this.const(toDate, 'localDateTime')
return this.rawFragment`${table} for system_time between ${from} and ${to} ${alias}`
})
}
const tCompany = new class TCompany extends Table<DBConection, 'TCompany'> {
id = this.autogeneratedPrimaryKey('id', 'int')
name = this.column('name', 'string')
parentId = this.optionalColumn('parent_id', 'int')
constructor() {
super('company'); // table name in the database
}
}()
const tCustomer = new class TCustomer extends Table<DBConection, 'TCustomer'> {
id = this.autogeneratedPrimaryKey('id', 'int')
firstName = this.column('first_name', 'string')
lastName = this.column('last_name', 'string')
birthday = this.optionalColumn('birthday', 'localDate')
companyId = this.column('company_id', 'int')
constructor() {
super('customer'); // table name in the database
}
}()
const vCustomerAndCompany = new class VCustomerAndCompany extends View<DBConection, 'VCustomerAndCompany'> {
companyId = this.column('company_id', 'int')
companyName = this.column('company_name', 'string')
customerId = this.column('customer_id', 'int')
customerFirstName = this.column('customer_first_name', 'string')
customerLastName = this.column('customer_last_name', 'string')
customerBirthday = this.optionalColumn('customer_birthday', 'localDate')
constructor() {
super('customer_company')
}
}()
const results: any[] = []
const postResults: any[] = []
const mockQueryRunner = new MockQueryRunner(
(_type, _query, _params, index) => {
return results[index]
}
)
const connection = new DBConection(/*postgre pg connection*/ new ConsoleLogQueryRunner(mockQueryRunner))
results.push({
id: 1,
firstName: 'First Name',
lastName: 'Last Name'
})
const customerId = 10
const customerWithId = connection.selectFrom(tCustomer)
.where(tCustomer.id.equals(customerId))
.select({
id: tCustomer.id,
firstName: tCustomer.firstName,
lastName: tCustomer.lastName,
birthday: tCustomer.birthday
})
.executeSelectOne()
// Query: select id as id, first_name as firstName, last_name as lastName, birthday as birthday from customer where id = $1
// Params: [ 10 ]
results.push([])
const firstNameContains = 'ohn'
const lastNameContains = null
const birthdayIs = null
const searchOrderBy = 'name insensitive, birthday asc nulls last'
const searchedCustomers = connection.selectFrom(tCustomer)
.where(
tCustomer.firstName.containsIfValue(firstNameContains)
.or(tCustomer.lastName.containsIfValue(lastNameContains))
).and(
tCustomer.birthday.equalsIfValue(birthdayIs)
)
.select({
id: tCustomer.id,
name: tCustomer.firstName.concat(' ').concat(tCustomer.lastName),
birthday: tCustomer.birthday
})
.orderByFromString(searchOrderBy)
.executeSelectMany()
// Query: select id as id, first_name || $1 || last_name as name, birthday as birthday from customer where first_name like ('%' || $2 || '%') order by lower(name), birthday asc nulls last
// Params: [ ' ', 'ohn' ]
results.push([])
let searchedCustomersWhere = connection.dynamicBooleanExpressionUsing(tCustomer)
if (firstNameContains) {
searchedCustomersWhere = searchedCustomersWhere.and(tCustomer.firstName.contains(firstNameContains))
}
if (lastNameContains) {
searchedCustomersWhere = searchedCustomersWhere.or(tCustomer.lastName.contains(lastNameContains))
}
if (birthdayIs) {
searchedCustomersWhere = searchedCustomersWhere.and(tCustomer.birthday.equals(birthdayIs))
}
const searchedCustomers2 = connection.selectFrom(tCustomer)
.where(searchedCustomersWhere)
.select({
id: tCustomer.id,
name: tCustomer.firstName.concat(' ').concat(tCustomer.lastName),
birthday: tCustomer.birthday
})
.orderByFromString(searchOrderBy)
.executeSelectMany()
// Query: select id as id, first_name || $1 || last_name as name, birthday as birthday from customer where first_name like ('%' || $2 || '%') order by lower(name), birthday asc nulls last
// Params: [ ' ', 'ohn' ]
results.push([])
const hideId = false
let searchedCustomersWhere3
if (firstNameContains) {
searchedCustomersWhere3 = tCustomer.firstName.contains(firstNameContains)
} else {
searchedCustomersWhere3 = connection.noValueBoolean()
}
if (lastNameContains) {
searchedCustomersWhere3 = mergeType(searchedCustomersWhere3).or(tCustomer.lastName.contains(lastNameContains))
}
if (birthdayIs) {
searchedCustomersWhere3 = mergeType(searchedCustomersWhere3).and(tCustomer.birthday.equals(birthdayIs))
}
searchedCustomersWhere3 = mergeType(searchedCustomersWhere3)
let idColumn
if (hideId) {
idColumn = connection.optionalConst(null, 'int')
} else {
idColumn = tCustomer.id
}
idColumn = mergeType(idColumn)
const searchedCustomers3 = connection.selectFrom(tCustomer)
.where(searchedCustomersWhere3)
.select({
id: idColumn,
name: tCustomer.firstName.concat(' ').concat(tCustomer.lastName),
birthday: tCustomer.birthday
})
.orderByFromString(searchOrderBy)
.executeSelectMany()
// Query: select id as id, first_name || $1 || last_name as name, birthday as birthday from customer where first_name like ('%' || $2 || '%') order by lower(name), birthday asc nulls last
// Params: [ ' ', 'ohn' ]
results.push([])
const firstName = 'John'
const lastName = null
const company = tCompany.as('comp')
const customersWithCompanyName = connection.selectFrom(tCustomer)
.innerJoin(company).on(tCustomer.companyId.equals(company.id))
.where(tCustomer.firstName.startsWithInsensitive(firstName))
.and(tCustomer.lastName.startsWithInsensitiveIfValue(lastName))
.select({
id: tCustomer.id,
firstName: tCustomer.firstName,
lastName: tCustomer.lastName,
birthday: tCustomer.birthday,
companyName: company.name
})
.orderBy('firstName', 'insensitive')
.orderBy('lastName', 'asc insensitive')
.executeSelectMany()
// Query: select customer.id as id, customer.first_name as firstName, customer.last_name as lastName, customer.birthday as birthday, comp.name as companyName from customer inner join company as comp on customer.company_id = comp.id where customer.first_name ilike ($1 || '%') order by lower(firstName), lower(lastName) asc
// Params: [ 'John' ]
results.push([])
const orderBy = 'customerFirstName asc nulls first, customerLastName'
const customerWithSelectedCompanies = connection.selectFrom(tCustomer)
.where(tCustomer.companyId.in(
connection.selectFrom(tCompany)
.where(tCompany.name.contains('Cia.'))
.selectOneColumn(tCompany.id)
)).select({
customerId: tCustomer.id,
customerFirstName: tCustomer.firstName,
customerLastName: tCustomer.lastName
}).orderByFromString(orderBy)
.executeSelectMany()
// Query: select id as customerId, first_name as customerFirstName, last_name as customerLastName from customer where company_id in (select id as result from company where name like ('%' || $1 || '%')) order by customerFirstName asc nulls first, customerLastName
// Params: [ 'Cia.' ]
results.push([])
const customerCountPerCompany = connection.selectFrom(tCompany)
.innerJoin(tCustomer).on(tCustomer.companyId.equals(tCompany.id))
.select({
companyId: tCompany.id,
companyName: tCompany.name,
customerCount: connection.count(tCustomer.id)
}).groupBy('companyId', 'companyName')
.executeSelectMany()
// Query: select company.id as companyId, company.name as companyName, count(customer.id) as customerCount from company inner join customer on customer.company_id = company.id group by company.id, company.name
// Params: []
results.push([])
const customerCountPerCompany2 = connection.selectFrom(tCompany)
.innerJoin(tCustomer).on(tCustomer.companyId.equals(tCompany.id))
.groupBy(tCompany.id, tCompany.name)
.select({
companyId: tCompany.id,
companyName: tCompany.name,
customerCount: connection.count(tCustomer.id)
})
.executeSelectMany()
// Query: select company.id as companyId, company.name as companyName, count(customer.id) as customerCount from company inner join customer on customer.company_id = company.id group by company.id, company.name
// Params: []
results.push([])
postResults.push(0)
const customerName = 'Smi'
const customerPageWithName = connection.selectFrom(tCustomer)
.where(
tCustomer.firstName.startsWithInsensitive(customerName)
).or(
tCustomer.lastName.startsWithInsensitive(customerName)
).select({
id: tCustomer.id,
firstName: tCustomer.firstName,
lastName: tCustomer.lastName
})
.orderBy('firstName')
.orderBy('lastName')
.limit(10)
.offset(20)
.executeSelectPage()
// Query: select id as id, first_name as firstName, last_name as lastName from customer where first_name ilike ($1 || '%') or last_name ilike ($2 || '%') order by firstName, lastName limit $3 offset $4
// Params: [ 'Smi', 'Smi', 10, 20 ]
// Query: select count(*) from customer where first_name ilike ($1 || '%') or last_name ilike ($2 || '%')
// Params: [ 'Smi', 'Smi' ]
results.push(null)
const id = 10
const customersUsingCustomFragment = connection.selectFrom(tCustomer)
.where(connection.fragmentWithType('boolean', 'required').sql`!!${tCustomer.id} = !!${connection.const(id, 'int')}`)
.select({
idAsString: connection.fragmentWithType('string', 'required').sql`${tCustomer.id}::varchar`,
name: tCustomer.firstName.concat(' ').concat(tCustomer.lastName)
})
.executeSelectNoneOrOne()
// Query: select id::varchar as idAsString, first_name || $1 || last_name as name from customer where !!id = !!$2
// Params: [ ' ', 10 ]
results.push([])
const bitwiseMovements = 1
const multiplier = 2
const companiesUsingCustomFunctionFragment = connection.selectFrom(tCompany)
.where(tCompany.id.multiply(multiplier).equals(connection.bitwiseShiftLeft(tCompany.id, bitwiseMovements)))
.select({
id: tCompany.id,
name: tCompany.name,
idMultiplyBy2: connection.bitwiseShiftLeft(tCompany.id, bitwiseMovements)
})
.executeSelectMany()
// Query: select id as id, name as name, id << $1 as idMultiplyBy2 from company where (id * $2) = (id << $3)
// Params: [ 1, 2, 1 ]
results.push([])
const noValue = null
const withValue = 2
const companiesUsingCustomFunctionFragmentIfValue = connection.selectFrom(tCompany)
.where(connection.valuePlusOneEqualsIfValue(tCompany.id, noValue))
.or(connection.valuePlusOneEqualsIfValue(tCompany.id, withValue))
.select({
id: tCompany.id,
name: tCompany.name,
})
.executeSelectMany()
// Query: select id as id, name as name from company where id + 1 = $1
// Params: [ 2 ]
results.push(1)
const insertCustomer = connection.insertInto(tCustomer).set({
firstName: 'John',
lastName: 'Smith',
companyId: 1
}).setIfNotSet({
birthday: new Date()
}).returningLastInsertedId()
.executeInsert()
// Query: insert into customer (first_name, last_name, company_id, birthday) values ($1, $2, $3, $4) returning id
// Params: [ 'John', 'Smith', 1, 2019-08-16T15:02:32.849Z ]
results.push([2, 3])
const valuesToInsert = [
{
firstName: 'John',
lastName: 'Smith',
companyId: 1
},
{
firstName: 'Other',
lastName: 'Person',
companyId: 1
}
]
const insertMultipleCustomers = connection.insertInto(tCustomer)
.values(valuesToInsert)
.returningLastInsertedId()
.executeInsert();
// Query: insert into customer (first_name, last_name, company_id) values ($1, $2, $3), ($4, $5, $6) returning id
// Params: [ 'John', 'Smith', 1, 'Other', 'Person', 1 ]
results.push(1)
const insertCustomersFromSelect = connection.insertInto(tCustomer)
.from(
connection.selectFrom(tCustomer)
.where(
tCustomer.companyId.equals(1)
)
.select({
firstName: tCustomer.firstName,
lastName: tCustomer.lastName,
companyId: tCustomer.companyId
})
)
.executeInsert();
// Query: insert into customer (first_name, last_name, company_id) select first_name as firstName, last_name as lastName, company_id as companyId from customer where company_id = $1
// Params: [ 1 ]
results.push(1)
const updateCustomer = connection.update(tCustomer).set({
firstName: 'John',
lastName: 'Smith',
birthday: new Date()
}).ignoreIfSet('birthday')
.where(tCustomer.id.equals(10))
.executeUpdate()
// Query: update customer set first_name = $1, last_name = $2 where id = $3
// Params: [ 'John', 'Smith', 10 ]
results.push(1)
const deleteCustomer = connection.deleteFrom(tCustomer)
.where(tCustomer.id.equals(10))
.executeDelete()
// Query: delete from customer where id = $1
// Params: [ 10 ]
results.push([])
const customerCountPerCompanyWith = connection.selectFrom(tCompany)
.innerJoin(tCustomer).on(tCustomer.companyId.equals(tCompany.id))
.select({
companyId: tCompany.id,
companyName: tCompany.name,
customerCount: connection.count(tCustomer.id)
}).groupBy('companyId', 'companyName')
.forUseInQueryAs('customerCountPerCompany')
const customerCountPerAcmeCompanies = connection.selectFrom(customerCountPerCompanyWith)
.where(customerCountPerCompanyWith.companyName.containsInsensitive('ACME'))
.select({
acmeCompanyId: customerCountPerCompanyWith.companyId,
acmeCompanyName: customerCountPerCompanyWith.companyName,
acmeCustomerCount: customerCountPerCompanyWith.customerCount
})
.executeSelectMany()
// Query: with customerCountPerCompany as (select company.id as companyId, company.name as companyName, count(customer.id) as customerCount from company inner join customer on customer.company_id = company.id group by company.id, company.name) select companyId as "acmeCompanyId", companyName as "acmeCompanyName", customerCount as "acmeCustomerCount" from customerCountPerCompany where companyName ilike ('%' || $1 || '%')
// Params: [ 'ACME' ]
const tCustomCompany = new class TCustomCompany extends Table<DBConection, 'TCustomCompany'> {
id = this.autogeneratedPrimaryKey('id', 'int');
name = this.column('name', 'string');
isBig = this.column('is_big', 'boolean', new CustomBooleanTypeAdapter('Y', 'N'));
constructor() {
super('custom_company'); // table name in the database
}
}()
results.push(1)
const insertCustomCompany = connection.insertInto(tCustomCompany).set({
name: 'My Big Company',
isBig: true
}).returningLastInsertedId()
.executeInsert()
// Query: insert into custom_company (name, is_big) values ($1, case when $2 then 'Y' else 'N' end) returning id
// Params: [ 'My Big Company', true ]
results.push([])
const selectAllBigCompanies = connection.selectFrom(tCustomCompany)
.where(tCustomCompany.isBig)
.select({
id: tCustomCompany.id,
name: tCustomCompany.name,
isBig: tCustomCompany.isBig
}).executeSelectMany()
// Query: select id as id, name as name, (is_big = 'Y') as isBig from custom_company where (is_big = 'Y')
// Params: []
results.push([])
type FilterType = DynamicCondition<{
id: 'int',
firstName: 'string',
lastName: 'string',
birthday: 'localDate',
companyName: 'string'
}>
const filter: FilterType = {
or: [
{ firstName: { startsWithInsensitive: 'John' } },
{ lastName: { startsWithInsensitiveIfValue: 'Smi', endsWith: 'th' } }
],
companyName: {equals: 'ACME'}
}
const selectFields = {
id: tCustomer.id,
firstName: tCustomer.firstName,
lastName: tCustomer.lastName,
birthday: tCustomer.birthday,
companyName: tCompany.name
}
const dynamicWhere = connection.dynamicConditionFor(selectFields).withValues(filter)
const customersWithDynamicCondition = connection.selectFrom(tCustomer)
.innerJoin(tCompany).on(tCustomer.companyId.equals(tCompany.id))
.where(dynamicWhere)
.select(selectFields)
.orderBy('firstName', 'insensitive')
.orderBy('lastName', 'asc insensitive')
.executeSelectMany()
// Query: select customer.id as id, customer.first_name as "firstName", customer.last_name as "lastName", customer.birthday as birthday, company.name as "companyName" from customer inner join company on customer.company_id = company.id where (customer.first_name ilike ($1 || '%') or (customer.last_name ilike ($2 || '%') and customer.last_name like ('%' || $3))) and company.name = $4 order by lower("firstName"), lower("lastName") asc
// Params: [ 'John', 'Smi', 'th', 'ACME' ]
results.push([])
const allDataWithName = connection.selectFrom(tCustomer)
.select({
id: tCustomer.id,
name: tCustomer.firstName.concat(' ').concat(tCustomer.lastName),
type: connection.const<'customer' | 'company'>('customer', 'enum', 'customerOrCompany')
}).unionAll(
connection.selectFrom(tCompany)
.select({
id: tCompany.id,
name: tCompany.name,
type: connection.const<'customer' | 'company'>('company', 'enum', 'customerOrCompany')
})
).executeSelectMany()
// Query: select id as id, first_name || $1 || last_name as name, $2 as type from customer union all select id as id, name as name, $3 as type from company
// Params: [ ' ', 'customer', 'company' ]
results.push([{
id: 10,
name: 'ACME Inc.'
}, {
id: 11,
name: 'ACME Corp.'
}])
postResults.push([{
id: 12,
firstName: 'John',
lastName: 'Smith',
birthday: new Date('1990/1/14'),
companyId: 10
}, {
id: 13,
firstName: 'Jorge',
lastName: 'Justo',
birthday: new Date('1991/2/16'),
companyId: 10
}, {
id: 14,
firstName: 'Maria',
lastName: 'Rodriguez',
birthday: new Date('1992/3/18'),
companyId: 11
}])
const companiesWithCustomers = connection.selectFrom(tCompany)
.select({
id: tCompany.id,
name: tCompany.name
}).where(
tCompany.name.containsInsensitive('ACME')
).composeDeletingInternalProperty({
externalProperty: 'id',
internalProperty: 'companyId',
propertyName: 'customers'
}).withMany((ids) => {
return connection.selectFrom(tCustomer)
.select({
id: tCustomer.id,
firstName: tCustomer.firstName,
lastName: tCustomer.lastName,
birthday: tCustomer.birthday,
companyId: tCustomer.companyId
}).where(
tCustomer.companyId.in(ids)
).executeSelectMany()
}).executeSelectMany()
// ---------------
results.push({
id: 12,
firstName: 'John',
lastName: 'Smith',
birthday: new Date('1990/1/14'),
companyId: 10
})
postResults.push([{
id: 10,
name: 'ACME Inc.'
}])
const customerWithCompany = connection.selectFrom(tCustomer)
.select({
id: tCustomer.id,
firstName: tCustomer.firstName,
lastName: tCustomer.lastName,
birthday: tCustomer.birthday,
companyId: tCustomer.companyId
}).where(
tCustomer.id .equals(12)
).composeDeletingExternalProperty({
externalProperty: 'companyId',
internalProperty: 'id',
propertyName: 'company'
}).withOne((ids) => {
return connection.selectFrom(tCompany)
.select({
id: tCompany.id,
name: tCompany.name
}).where(
tCompany.id.in(ids)
).executeSelectMany()
}).executeSelectOne()
// ---------------
results.push({
id: 12,
firstName: 'John',
lastName: 'Smith',
birthday: new Date('1990/1/14'),
companyId: 10,
companyName: 'ACME Inc.'
})
const customerWithCompanyInOneQuery = connection.selectFrom(tCustomer)
.innerJoin(tCompany).on(tCompany.id.equals(tCustomer.companyId))
.select({
id: tCustomer.id,
firstName: tCustomer.firstName,
lastName: tCustomer.lastName,
birthday: tCustomer.birthday,
companyId: tCompany.id,
companyName: tCompany.name
}).where(
tCustomer.id .equals(12)
).split('company', {
id: 'companyId',
name: 'companyName'
}).executeSelectOne()
// ---------------
results.push({
id: 12,
firstName: 'John',
lastName: 'Smith',
birthday: new Date('1990/1/14'),
'company.id': 10,
'company.name': 'ACME Inc.'
})
type QueryFilterType = DynamicCondition<{
id: 'int',
firstName: 'string',
lastName: 'string',
birthday: 'localDate',
'company.id': 'int',
'company.name': 'string'
}>
const queryFilter: QueryFilterType = {
'company.name': {equals: 'ACME'},
or: [
{ firstName: { containsInsensitive: 'John' } },
{ lastName: { containsInsensitive: 'Smi' } }
]
}
const queryOrderBy = 'company.name asc insensitive, birthday desc'
const querySelectFields = {
id: tCustomer.id,
firstName: tCustomer.firstName,
lastName: tCustomer.lastName,
birthday: tCustomer.birthday,
'company.id': tCompany.id,
'company.name': tCompany.name
}
const queryDynamicWhere = connection.dynamicConditionFor(querySelectFields).withValues(queryFilter)
const customerWithCompanyObject = connection.selectFrom(tCustomer)
.innerJoin(tCompany).on(tCompany.id.equals(tCustomer.companyId))
.select(querySelectFields)
.where(queryDynamicWhere)
.orderByFromString(queryOrderBy)
.split('company', {
id: 'company.id',
name: 'company.name'
}).executeSelectOne()
// Query: select customer.id as id, customer.first_name as "firstName", customer.last_name as "lastName", customer.birthday as birthday, company.id as "company.id", company.name as "company.name" from customer inner join company on company.id = customer.company_id where company.name = $1 and (customer.first_name ilike ('%' || $2 || '%') or customer.last_name ilike ('%' || $3 || '%')) order by lower("company.name") asc, birthday desc
// Params: [ 'John', 'Smi', 'ACME' ]
results.push([])
const recursiveParentCompany = connection.selectFrom(tCompany)
.where(tCompany.id.equals(10))
.select({
id: tCompany.id,
name: tCompany.name,
parentId: tCompany.parentId
}).recursiveUnion((child) => {
return connection.selectFrom(tCompany)
.join(child).on(child.parentId.equals(tCompany.id))
.select({
id: tCompany.id,
name: tCompany.name,
parentId: tCompany.parentId
})
}).executeSelectMany()
// Query: with recursive recursive_select_1 as (select id as id, name as name, parent_id as parentId from company where id = $1 union select company.id as id, company.name as name, company.parent_id as parentId from company join recursive_select_1 on recursive_select_1.parentId = company.id) select id as id, name as name, parentId as "parentId" from recursive_select_1
// Params: [ 10 ]
results.push([])
const recursiveOnParentCompany = connection.selectFrom(tCompany)
.where(tCompany.id.equals(10))
.select({
id: tCompany.id,
name: tCompany.name,
parentId: tCompany.parentId
}).recursiveUnionOn((child) => {
return child.parentId.equals(tCompany.id)
}).executeSelectMany()
// Query: with recursive recursive_select_1 as (select id as id, name as name, parent_id as parentId from company where id = $1 union select company.id as id, company.name as name, company.parent_id as parentId from company join recursive_select_1 on recursive_select_1.parentId = company.id) select id as id, name as name, parentId as "parentId" from recursive_select_1
// Params: [ 10 ]
results.push([])
const recursiveChildrenCompany = connection.selectFrom(tCompany)
.where(tCompany.id.equals(10))
.select({
id: tCompany.id,
name: tCompany.name,
parentId: tCompany.parentId
}).recursiveUnionAll((parent) => {
return connection.selectFrom(tCompany)
.join(parent).on(parent.id.equals(tCompany.parentId))
.select({
id: tCompany.id,
name: tCompany.name,
parentId: tCompany.parentId
})
}).executeSelectMany()
// Query: with recursive recursive_select_1 as (select id as id, name as name, parent_id as parentId from company where id = $1 union all select company.id as id, company.name as name, company.parent_id as parentId from company join recursive_select_1 on recursive_select_1.id = company.parent_id) select id as id, name as name, parentId as "parentId" from recursive_select_1
// Params: [ 10 ]
results.push([])
const recursiveOnChildrenCompany = connection.selectFrom(tCompany)
.where(tCompany.id.equals(10))
.select({
id: tCompany.id,
name: tCompany.name,
parentId: tCompany.parentId
}).recursiveUnionAllOn((parent) => {
return parent.id.equals(tCompany.parentId)
}).executeSelectMany()
// Query: with recursive recursive_select_1 as (select id as id, name as name, parent_id as parentId from company where id = $1 union all select company.id as id, company.name as name, company.parent_id as parentId from company join recursive_select_1 on recursive_select_1.id = company.parent_id) select id as id, name as name, parentId as "parentId" from recursive_select_1
// Params: [ 10 ]
results.push([{
id: 18,
name: 'name'
}, {
id: 19,
name: 'name2',
parentId: 18,
parentName: 'name'
}])
const parent = tCompany.forUseInLeftJoinAs('parent')
const leftJoinCompany = connection.selectFrom(tCompany)
.leftJoin(parent).on(tCompany.parentId.equals(parent.id))
.select({
id: tCompany.id,
name: tCompany.name,
parentId: parent.id,
parentName: parent.name
}).guidedSplitOptional('parent', {
id: 'parentId!',
name: 'parentName!'
}).executeSelectMany()
// Query: select company.id as id, company.name as name, parent.id as parentId, parent.name as parentName from company left join company as parent on company.parent_id = parent.id
// Params: [ ]
results.push({
id: 1,
firstName: 'First Name',
lastName: 'Last Name'
})
const availableFields = {
id: tCustomer.id,
firstName: tCustomer.firstName,
lastName: tCustomer.lastName,
birthday: tCustomer.birthday
}
const fieldsToPick = {
firstName: true,
lastName: true
}
// include allways id field as required
const pickedFields = dynamicPick(availableFields, fieldsToPick, ['id'])
const customerWithIdPeaking = connection.selectFrom(tCustomer)
.select(pickedFields)
.executeSelectOne()
// Query: select id as id, first_name as "firstName", last_name as "lastName" from customer
// Params: [ ]
results.push([])
const availableFields2 = {
id: tCustomer.id,
firstName: tCustomer.firstName,
lastName: tCustomer.lastName,
birthday: tCustomer.birthday,
companyId: tCompany.id,
companyName: tCompany.name
}
const fieldsToPick2 = {
firstName: true,
lastName: true
}
// include allways id field as required
const pickedFields2 = dynamicPick(availableFields2, fieldsToPick2, ['id'])
const customerWithOptionalCompany = connection.selectFrom(tCustomer)
.optionalInnerJoin(tCompany).on(tCompany.id.equals(tCustomer.companyId))
.select(pickedFields2)
.where(tCustomer.id.equals(12))
.executeSelectMany()
// Query: select customer.id as id, customer.first_name as "firstName", customer.last_name as "lastName" from customer where customer.id = $1
// Params: [ 12 ]
/*
const fieldsToPick2 = {
firstName: true,
lastName: true,
companyName: true
}
// Query: select customer.id as id, customer.first_name as "firstName", customer.last_name as "lastName", company.name as "companyName" from customer inner join company on company.id = customer.company_id where customer.id = $1
// Params: [ 12 ]
*/
results.push([])
const customerIn2019 = connection.forSystemTimeBetween(tCustomer, 'customerIn2019', new Date('2019-01-01'), new Date('2020-01-01'))
const customerInSystemTime = connection.selectFrom(customerIn2019)
.where(customerIn2019.id.equals(10))
.select({
id: customerIn2019.id,
firstName: customerIn2019.firstName,
lastName: customerIn2019.lastName,
birthday: customerIn2019.birthday
})
.executeSelectMany()
// Query: select id as id, first_name as "firstName", last_name as "lastName", birthday as birthday from customer for system_time between $1 and $2 where id = $3
// Params: [ 2019-01-01T00:00:00.000Z, 2020-01-01T00:00:00.000Z, 10 ]
results.push({
id: 1,
firstName: 'First Name',
lastName: 'Last Name'
})
const customizedSelect = connection.selectFrom(tCustomer)
.where(tCustomer.id.equals(10))
.select({
id: tCustomer.id,
firstName: tCustomer.firstName,
lastName: tCustomer.lastName,
birthday: tCustomer.birthday
}).customizeQuery({
afterSelectKeyword: connection.rawFragment`/*+ some hints */`,
afterQuery: connection.rawFragment`for update`
})
.executeSelectOne()
// Query: select /*+ some hints */ id as id, first_name as "firstName", last_name as "lastName", birthday as birthday from customer where id = $1 for update
// Params: [ 10 ]
results.push(1)
const customizedUpdate = connection.update(tCustomer).set({
firstName: 'John',
lastName: 'Smith'
}).where(tCustomer.id.equals(10))
.customizeQuery({
afterUpdateKeyword: connection.rawFragment`/*+ some hints */`,
afterQuery: connection.rawFragment`keep plan`,
})
.executeUpdate()
// Query: update /*+ some hints */ customer set first_name = $1, last_name = $2 where id = $3 keep plan
// Params: [ 'John', 'Smith', 10 ]
results.push(1)
const customizedDelete = connection.deleteFrom(tCustomer)
.where(tCustomer.id.equals(10))
.customizeQuery({
afterDeleteKeyword: connection.rawFragment`/*+ some hints */`,
afterQuery: connection.rawFragment`keep plan`,
})
.executeDelete()
// Query: delete /*+ some hints */ from customer where id = $1 keep plan
// Params: [ 10 ]
results.push(1)
const customizedInsert = connection.insertInto(tCustomer).set({
firstName: 'John',
lastName: 'Smith',
companyId: 1
}).customizeQuery({
afterInsertKeyword: connection.rawFragment`/*+ some hints */`,
afterQuery: connection.rawFragment`log errors reject limit unlimited`
}).executeInsert()
// Query: insert /*+ some hints */ into customer (first_name, last_name, company_id) values ($1, $2, $3) log errors reject limit unlimited
// Params: [ 'John', 'Smith', 1 ]
results.push({
id: 9,
firstName: 'First Name',
lastName: 'Last Name',
companyId: 7
})
const selectAll = connection.selectFrom(tCustomer)
.select(extractColumnsFrom(tCustomer))
.where(tCustomer.id.equals(9))
.executeSelectOne()
// Query: select id as id, first_name as "firstName", last_name as "lastName", birthday as birthday, company_id as "companyId" from customer where id = $1
// Params: [ 9 ]
results.push({
'customer.id': 12,
'customer.firstName': 'John',
'customer.lastName': 'Smith',
'customer.birthday': new Date('1990/1/14'),
'company.id': 10,
'company.name': 'ACME Inc.'
})
const customerColumns = {
id: tCustomer.id,
firstName: tCustomer.firstName,
lastName: tCustomer.lastName,
birthday: tCustomer.birthday
}
const companyColumns = {
id: tCompany.id,
name: tCompany.name
}
const customerWithCompanyPrefixed = connection.selectFrom(tCustomer)
.innerJoin(tCompany).on(tCompany.id.equals(tCustomer.companyId))
.select({
...prefixDotted(customerColumns, 'customer'),
...prefixDotted(companyColumns, 'company')
}).where(
tCustomer.id.equals(12)
)
.split('customer', prefixMapForSplitDotted(customerColumns, 'customer'))
.split('company', prefixMapForSplitDotted(companyColumns, 'company'))
.executeSelectOne()
// Query: select customer.id as "customer.id", customer.first_name as "customer.firstName", customer.last_name as "customer.lastName", customer.birthday as "customer.birthday", company.id as "company.id", company.name as "company.name" from customer inner join company on company.id = customer.company_id where customer.id = $1
// Params: [ 12 ]
results.push({
customerId: 12,
customerFirstName: 'John',
customerLastName: 'Smith',
customerBirthday: new Date('1990/1/14'),
companyId: 10,
companyName: 'ACME Inc.'
})
const customerWithCompanyPrefixed2 = connection.selectFrom(tCustomer)
.innerJoin(tCompany).on(tCompany.id.equals(tCustomer.companyId))
.select({
...prefixCapitalized(customerColumns, 'customer'),
...prefixCapitalized(companyColumns, 'company')
}).where(
tCustomer.id.equals(12)
)
.split('customer', prefixMapForSplitCapitalized(customerColumns, 'customer'))
.split('company', prefixMapForSplitCapitalized(companyColumns, 'company'))
.executeSelectOne()
// Query: select customer.id as "customerId", customer.first_name as "customerFirstName", customer.last_name as "customerLastName", customer.birthday as "customerBirthday", company.id as "companyId", company.name as "companyName" from customer inner join company on company.id = customer.company_id where customer.id = $1
// Params: [ 12 ]
results.push([{
id: 18,
name: 'name'
}, {
id: 19,
name: 'name2',
parentId: 18,
parentName: 'name',
parentParentId: null
}])
const parentCompany = tCompany.forUseInLeftJoinAs('parent')
const companyFields = {
id: tCompany.id,
name: tCompany.name
}
const parentCompanyFields = {
id: parentCompany.id,
name: parentCompany.name,
parentId: parentCompany.parentId
}
const companyPrefixed = connection.selectFrom(tCompany)
.leftJoin(parent).on(tCompany.parentId.equals(parent.id))
.select({
...companyFields,
...prefixCapitalized(parentCompanyFields, 'parent')
}).guidedSplitOptional('parent', prefixMapForGuidedSplitCapitalized(parentCompanyFields, tCompany, 'parent'))
.executeSelectMany()
// Query: select company.id as id, company.name as name, parent.id as "parentId", parent.name as "parentName", parent.parent_id as "parentParentId" from company left join company as parent on company.parent_id = parent.id
// Params: [ ]
results.push([{
id: 18,
name: 'name'
}, {
id: 19,
name: 'name2',
'parent.id': 18,
'parent.name': 'name',
'parent.parentId': 8
}])
const companyPrefixed2 = connection.selectFrom(tCompany)
.leftJoin(parent).on(tCompany.parentId.equals(parent.id))
.select({
...companyFields,
...prefixDotted(parentCompanyFields, 'parent')
}).guidedSplitOptional('parent', prefixMapForGuidedSplitDotted(parentCompanyFields, tCompany, 'parent'))
.executeSelectMany()
// Query: select company.id as id, company.name as name, parent.id as "parent.id", parent.name as "parent.name", parent.parent_id as "parent.parentId" from company left join company as parent on company.parent_id = parent.id
// Params: [ ]
results.push([{
id: 18,
name: 'name'
}, {
id: 19,
name: 'name2',
parentId: 18,
parentName: 'name'
}])
const parentFields = {
parentId: parentCompany.id,
parentName: parentCompany.name,
parentParentId: parentCompany.parentId
}
const companyPrefixed3 = connection.selectFrom(tCompany)
.leftJoin(parent).on(tCompany.parentId.equals(parent.id))
.select({
id: tCompany.id,
name: tCompany.name,
...parentFields
}).guidedSplitOptional('parent', mapForGuidedSplit(parentFields, {
parentId: tCompany.id,
parentName: tCompany.name,
parentParentId: tCompany.parentId
}))
.executeSelectMany()
// Query: select company.id as id, company.name as name, parent.id as "parentId", parent.name as "parentName", parent.parent_id as "parentParentId" from company left join company as parent on company.parent_id = parent.id
// Params: [ ]
results.push([{
id: 18,
name: 'name'
}, {
id: 19,
name: 'name2',
parentId: 18,
parentName: 'name'
}, {
id: 20,
name: 'name3',
parentId: 19,
parentName: 'name2',
parentParentId: 18,
parentParentName: 'name',
parentParentParentId: 17
}])
const parentParent = tCompany.forUseInLeftJoinAs('parentParent')
const companyMultiSplit = connection.selectFrom(tCompany)
.leftJoin(parent).on(tCompany.parentId.equals(parent.id))
.leftJoin(parentParent).on(parent.parentId.equals(parentParent.id))
.select({
id: tCompany.id,
name: tCompany.name,
parentId: parent.id,
parentName: parent.name,
parentParentId: parentParent.id,
parentParentName: parentParent.name,
parentParentParentId: parentParent.parentId,
}).guidedSplitOptional('parentParent', {
id: 'parentParentId!',
name: 'parentParentName!',
parentId: 'parentParentParentId'
}).guidedSplitOptional('parent', {
id: 'parentId!',
name: 'parentName!',
parent: 'parentParent'
})
.executeSelectMany()
// Query: select company.id as id, company.name as name, parent.id as "parentId", parent.name as "parentName", parentParent.id as "parentParentId", parentParent.name as "parentParentName", parentParent.parent_id as "parentParentParentId" from company left join company as parent on company.parent_id = parent.id left join company as parentParent on parent.parent_id = parentParent.id
// Params: [ ]
results.push([])
const acmeId = connection.selectFrom(tCompany)
.where(tCompany.name.equals('ACME'))
.selectOneColumn(tCompany.id)
.forUseAsInlineQueryValue()
const acmeCustomers = connection.selectFrom(tCustomer)
.where(tCustomer.companyId.equals(acmeId))
.select({
id: tCustomer.id,
name: tCustomer.firstName.concat(' ').concat(tCustomer.lastName)
})
.executeSelectMany()
// Query: select id as id, first_name || $1 || last_name as name from customer where company_id = (select id as result from company where name = $2)
// Params: [ ' ', 'ACME' ]
results.push({
id: 10,
name: 'ACME'
})
const deletedAcmeCompany = connection.deleteFrom(tCompany)
.where(tCompany.name.equals('ACME'))
.returning({
id: tCompany.id,
name: tCompany.name
})
.executeDeleteOne()
// Query: delete from company where name = $1 returning id as id, name as name
// Params: [ 'ACME' ]
results.push('Ron')
const updatedSmithFirstName = connection.update(tCustomer)
.set({
firstName: 'Ron'
})
.where(tCustomer.id.equals(1))
.returningOneColumn(tCustomer.firstName)
.executeUpdateOne()
// Query: update customer set first_name = $1 where id = $2 returning first_name as result
// Params: [ 'Ron', 1 ]
results.push({
oldLastName: 'Shith',
newLastName: 'Thomson'
})
const oldCustomerValues = tCustomer.oldValues()
const updatedLastNames = connection.update(tCustomer)
.set({
lastName: 'Thomson'
})
.where(tCustomer.id.equals(2))
.returning({
oldLastName: oldCustomerValues.lastName,
newLastName: tCustomer.lastName
})
.executeUpdateOne()
// Query: update customer as _new_ set last_name = $1 from (select _old_.* from customer as _old_ where _old_.id = $2 for no key update of _old_) as _old_ where _new_.id = _old_.id returning _old_.last_name as "oldLastName", _new_.last_name as "newLastName"
// Params: [ 'Thomson', 2 ]
results.push({
id: 1,
firstName: 'John',
lastName: 'Smith',
})
const insertReturningCustomerData = connection.insertInto(tCustomer).set({
firstName: 'John',
lastName: 'Smith',
companyId: 1
}).returning({
id: tCustomer.id,
firstName: tCustomer.firstName,
lastName: tCustomer.lastName
})
.executeInsertOne()
// Query: insert into customer (first_name, last_name, company_id) values ($1, $2, $3) returning id as id, first_name as "firstName", last_name as "lastName"
// Params: [ 'John', 'Smith', 1 ]
results.push(1)
const addACMECompanyNameToLastName = connection.update(tCustomer)
.from(tCompany)
.set({
lastName: tCustomer.lastName.concat(' - ').concat(tCompany.name)
})
.where(tCustomer.companyId.equals(tCompany.id))
.and(tCompany.name.containsInsensitive('ACME'))
.executeUpdate()
// Query: update customer set last_name = customer.last_name || $1 || company.name from company where customer.company_id = company.id and company.name ilike ('%' || $2 || '%')
// Params: [ ' - ', 'ACME' ]
results.push(1)
const deleteACMECustomers = connection.deleteFrom(tCustomer)
.using(tCompany)
.where(tCustomer.companyId.equals(tCompany.id))
.and(tCompany.name.containsInsensitive('ACME'))
.executeDelete()
// Query: delete from customer using company where customer.company_id = company.id and company.name ilike ('%' || $1 || '%')
// Params: [ 'ACME' ]
results.push(...postResults)
vCustomerAndCompany.as('foo')
searchedCustomers.finally(() => undefined)
searchedCustomers2.finally(() => undefined)
searchedCustomers3.finally(() => undefined)
customersWithCompanyName.finally(() => undefined)
customerWithSelectedCompanies.finally(() => undefined)
customerCountPerCompany.finally(() => undefined)
customerCountPerCompany2.finally(() => undefined)
insertCustomer.finally(() => undefined)
insertMultipleCustomers.finally(() => undefined)
insertCustomersFromSelect.finally(() => undefined)
updateCustomer.finally(() => undefined)
deleteCustomer.finally(() => undefined)
customersUsingCustomFragment.finally(() => undefined)
companiesUsingCustomFunctionFragment.finally(() => undefined)
companiesUsingCustomFunctionFragmentIfValue.finally(() => undefined)
customerPageWithName.finally(() => undefined)
customerWithId.finally(() => undefined)
customerCountPerAcmeCompanies.finally(() => undefined)
insertCustomCompany.finally(() => undefined)
selectAllBigCompanies.finally(() => undefined)
customersWithDynamicCondition.finally(() => undefined)
allDataWithName.finally(() => undefined)
companiesWithCustomers.then((result) => {
console.log('companiesWithCustomers', result)
console.log('companiesWithCustomers resulr[0].customers', result[0]!.customers)
console.log('companiesWithCustomers resulr[1].customers', result[1]!.customers)
})
customerWithCompany.then((result) => {
console.log('customerWithCompany', result)
})
customerWithCompanyInOneQuery.then((result) => {
console.log('customerWithCompanyInOneQuery', result)
})
customerWithCompanyObject.then((result) => {
console.log('customerWithCompanyObject', result)
})
recursiveParentCompany.finally(() => undefined)
recursiveOnParentCompany.finally(() => undefined)
recursiveChildrenCompany.finally(() => undefined)
recursiveOnChildrenCompany.finally(() => undefined)
leftJoinCompany.finally(() => undefined)
customerWithIdPeaking.finally(() => undefined)
customerWithOptionalCompany.finally(() => undefined)
customerInSystemTime.finally(() => undefined)
customizedSelect.finally(() => undefined)
customizedUpdate.finally(() => undefined)
customizedDelete.finally(() => undefined)
customizedInsert.finally(() => undefined)
selectAll.finally(() => undefined)
customerWithCompanyPrefixed.then((result) => {
console.log('customerWithCompanyPrefixed', result)
})
customerWithCompanyPrefixed2.then((result) => {
console.log('customerWithCompanyPrefixed2', result)
})
companyPrefixed.then((result) => {
console.log('companyPrefixed', result)
})
companyPrefixed2.then((result) => {
console.log('companyPrefixed2', result)
})
companyPrefixed3.then((result) => {
console.log('companyPrefixed3', result)
})
companyMultiSplit.then((result) => {
result.map((value, i) => {
console.log('companyMultiSplit[' + i + ']', value)
})
})
acmeCustomers.finally(() => undefined)
deletedAcmeCompany.finally(() => undefined)
updatedSmithFirstName.finally(() => undefined)
updatedLastNames.finally(() => undefined)
insertReturningCustomerData.finally(() => undefined)
addACMECompanyNameToLastName.finally(() => undefined)
deleteACMECustomers.finally(() => undefined)
/*
PostgreSql update multitable with old values emulation:
No secondary table used in set or return
First attempt:
update customer as _new_
set last_name = $1
from (
select _old_.*
from customer as _old_, company
where _old_.company_id = company.id
and company.name = $2
and _old_.first_name = $3
for no key update of _old_
) as _old_
where _new_.id = _old_.id
returning _old_.last_name as "oldLastName", _new_.last_name as "newLastName"
Final:
update customer as _new_
set last_name = $1
from (
select _old_.*
from customer as _old_, company
where _old_.company_id = company.id
and company.name = $2
and _old_.first_name = $3
for no key update of _old_
) as _old_
where _new_.id = _old_.id
returning _old_.last_name as "oldLastName", _new_.last_name as "newLastName"
Secondary table used in set
First attempt:
update customer as _new_
set last_name = _new_.last_name || $1 || company.name
from company, (
select _old_.*
from customer as _old_, company
where _old_.company_id = company.id
and company.name = $2
and _old_.first_name = $3
for no key update of _old_, company
) as _old_
where _new_.id = _old_.id
and _new_.company_id = company.id
and company.name = $4
and _new_.first_name = $5
returning _old_.last_name as "oldLastName", _new_.last_name as "newLastName"
Final:
update customer as _new_
set last_name = _new_.last_name || $1 || _old_.company__name
from (
select _old_.*,
company.name as company__name
from customer as _old_, company
where _old_.company_id = company.id
and company.name = $2
and _old_.first_name = $3
for no key update of _old_
) as _old_
where _new_.id = _old_.id
returning _old_.last_name as "oldLastName", _new_.last_name as "newLastName"
Secondary table used in return
First attempt:
update customer as _new_
set last_name = $1
from company, (
select _old_.*
from customer as _old_, company
where _old_.company_id = company.id
and company.name = $2
and _old_.first_name = $3 for
no key update of _old_, company
) as _old_
where _new_.id = _old_.id
and _new_.company_id = company.id
and company.name = $4
and _new_.first_name = $5
returning _old_.last_name as "oldLastName", _new_.last_name || $6 || company.name as "newLastName"
Final:
update customer as _new_
set last_name = $1
from (
select _old_.*,
company.name as company__name
from customer as _old_, company
where _old_.company_id = company.id
and company.name = $2
and _old_.first_name = $3
for no key update of _old_
) as _old_
where _new_.id = _old_.id
returning _old_.last_name as "oldLastName", _new_.last_name || $4 || _old_.company__name as "newLastName"
*/
// case when then end
// agragate functions, group by, having
// begin transaction, commit, rollback
// return last inserted id
// with, with recursive
// from select
// window, over
// insert multiple
// union, intersect
// call stored procedure
// functions: coalesce, ifnull, min, max, nullIf <-- implentadas como valueWhenNull, minValue, maxValue, excepto nullIf
// maths: acosh-, asinh-, atanh-, difference(descartar), degrees-, radians-, cosh-, sinh-, tanh-, coth-,
// string: repeat(replicate) [no oracle], indexof(strpos, charindex) [difiere el resultado cuando no lo encuentra],
// left(leftstr) [no disponible en oracle, usar substring], right(rightstr) [no disponible en oracle, usar substring]
// lpad(padl) [no disponible en sql server], rpad(padr) [no disponible en sql server], padc?-,
// order by null first, last
/*
returning lastInsertedId sequence
MariaDB no yes no
MySql no yes no
Oracle yes* no yes
Postgre yes no yes
Sqlite no yes no
Sqlserver yes no yes
* It doesn't work when you insert multiple rows
*/
/*
Things that I want to implement:
+ return last inserted id
+ begin transaction, commit, rollback
+ call stored procedure
+ sequences
+ order by null first, last: https://stackoverflow.com/questions/12503120/how-to-do-nulls-last-in-sqlite https://nickstips.wordpress.com/2010/09/30/sql-order-by-with-null-values-last/
+ sql fragments
2nd to implement:
+ basic agragate functions
+ group by
+ having
3rd to implement:
+ insert multiple
+ insert from select
4th to implement:
+ with
+ with recursive
+ union, intersect
5th to implement:
+ returning
6th to implement:
+ update multiple from
Things that I don't want to implement by now
- agregate functions: filter
- agregate functions: order by
- window, over
- complex agragate functions
Things that probably I'm not going to implement due alternative syntax exists:
- from select
Links:
- Sqlite bug update returning: https://sqlite.org/forum/forumpost/e70ea1b15f
- Modern SQL: https://modern-sql.com
- Pagination with Relative Cursors: https://shopify.engineering/pagination-relative-cursors
- Online test: https://sqliteonline.com/
Documentation:
- PostgreSql: https://www.postgresql.org/docs/13/sql-delete.html
- SqlServer: https://docs.microsoft.com/es-es/sql/t-sql/statements/delete-transact-sql?view=sql-server-ver15
- Sqlite: https://www.sqlite.org/index.html
- MySql: https://dev.mysql.com/doc/refman/8.0/en/delete.html
- MariaBD: https://mariadb.com/kb/en/delete/
- Oracle SQL Language refernec: https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/DELETE.html#GUID-156845A5-B626-412B-9F95-8869B988ABD7
- Oracle PL/SQL Langage reference: https://docs.oracle.com/en/database/oracle/oracle-database/21/lnpls/DELETE-statement-extension.html#GUID-9BEEC5E0-EF77-4E88-9DD4-B9BA1EABABCF
- Oracle 11g Database Advanced Application Developer's Guide: https://docs.oracle.com/cd/B28359_01/appdev.111/b28424/adfns_flashback.htm#g1026131
- Oracle 11g Database PL/SQL Language Reference: https://docs.oracle.com/database/121/LNPLS/langelems.htm#LNPLS013
Others:
- Join-Monster: https://join-monster.readthedocs.io/en/latest/
*/ | the_stack |
import { expect } from 'chai';
import * as fse from 'fs-extra';
import * as _git from 'nodegit';
import * as path from 'path';
import { VcsAccountDummy, VcsAuthenticationInfoDummy } from '../../core/dummies';
import { GitMergeConflictedError } from '../../core/git';
import { VcsFileChange, VcsFileChangeStatusTypes } from '../../core/vcs';
import { datetime, DateUnits } from '../../libs/datetime';
import { GitService } from './git.service';
describe('mainProcess.services.GitService', () => {
let git: GitService;
const tmpPath = path.resolve(process.cwd(), 'tmp/');
function getFixturePath(name: string): string {
return path.resolve(process.cwd(), 'test/workspace-fixtures/', name, '_git/');
}
async function makeTmpPath(createGit: boolean = false): Promise<void> {
await fse.ensureDir(tmpPath);
if (createGit) {
const repo = await _git.Repository.init(tmpPath, 0);
repo.free();
}
}
async function removeTmpPath(): Promise<void> {
await fse.remove(tmpPath);
}
beforeEach(() => {
git = new GitService();
git.init();
});
afterEach(async () => {
git.destroy();
await removeTmpPath();
});
describe('isRepositoryExists', () => {
it('should return false as promise if directory is not exists.', async () => {
const result = await git.isRepositoryExists(tmpPath);
expect(result).to.equal(false);
});
it('should return true as promise if directory is exists and its git directory.', async () => {
await makeTmpPath(true);
const result = await git.isRepositoryExists(tmpPath);
expect(result).to.equal(true);
});
});
describe('createRepository', () => {
it('should create git repository.', async () => {
await makeTmpPath();
await git.createRepository(tmpPath);
const isRepositoryExists = await git.isRepositoryExists(tmpPath);
expect(isRepositoryExists).to.equal(true);
});
});
describe('cloneRepository', () => {
});
describe('getFileChanges', () => {
it('should return vcs file change list as promise.', async () => {
await makeTmpPath(true);
await fse.writeFile(path.resolve(tmpPath, 'test-file'), 'some data');
const fileChanges = await git.getFileChanges(tmpPath);
expect(fileChanges[0]).to.deep.equals({
filePath: 'test-file',
workingDirectoryPath: tmpPath,
absoluteFilePath: path.resolve(tmpPath, 'test-file'),
status: VcsFileChangeStatusTypes.NEW,
} as VcsFileChange);
});
});
describe('commit', () => {
const testFiles: VcsFileChange[] = [];
beforeEach(async () => {
await makeTmpPath(true);
const fileAPath = path.resolve(tmpPath, 'a');
const fileBPath = path.resolve(tmpPath, 'b');
const fileCPath = path.resolve(tmpPath, 'c');
await Promise.all([
fse.writeFile(fileAPath, 'a data'),
fse.writeFile(fileBPath, 'b data'),
fse.writeFile(fileCPath, 'c data'),
]);
testFiles.push(
{
filePath: 'a',
workingDirectoryPath: tmpPath,
absoluteFilePath: fileBPath,
status: VcsFileChangeStatusTypes.NEW,
},
{
filePath: 'b',
workingDirectoryPath: tmpPath,
absoluteFilePath: fileBPath,
status: VcsFileChangeStatusTypes.NEW,
},
);
});
it('should commit on head.', async () => {
const author = new VcsAccountDummy().create();
const commitId = await git.commit({
workspaceDirPath: tmpPath,
fileChanges: testFiles,
author,
message: 'Summary\n\nDescription',
});
const repo = await _git.Repository.open(tmpPath);
const headCommit = await repo.getHeadCommit();
expect(headCommit.author().name()).to.equal(author.name);
expect(headCommit.author().email()).to.equal(author.email);
expect(headCommit.committer().name()).to.equal(author.name);
expect(headCommit.committer().email()).to.equal(author.email);
expect(headCommit.summary()).to.equal('Summary');
expect(headCommit.message()).to.equal('Summary\n\nDescription');
expect(headCommit.id().tostrS()).to.equal(commitId);
headCommit.free();
repo.free();
});
it('should commit removed file.', async () => {
});
});
describe('getCommitHistory', () => {
const author = new VcsAccountDummy().create();
async function commitFile(fileName: string, timestamp: number, message: string): Promise<void> {
const filePath = path.resolve(tmpPath, fileName);
await fse.writeFile(filePath, 'data');
await git.commit({
workspaceDirPath: tmpPath,
fileChanges: [
{
filePath: fileName,
absoluteFilePath: filePath,
status: VcsFileChangeStatusTypes.NEW,
workingDirectoryPath: tmpPath,
},
],
author,
message,
createdAt: {
time: Math.floor(timestamp / 1000),
offset: 0,
},
});
}
beforeEach(async () => {
await makeTmpPath(true);
});
it('should get history by pagination.', async () => {
// Make commits.
const timestamp = new Date().getTime();
await commitFile('a', timestamp, 'message1');
await commitFile('b', timestamp + 1000, 'message2');
await commitFile('c', timestamp + 2000, 'message3');
await commitFile('d', timestamp + 3000, 'message4');
await commitFile('e', timestamp + 4000, 'message5');
// First load
const first = await git.getCommitHistory({
workspaceDirPath: tmpPath,
size: 3,
});
expect(first.history.length).to.equals(3);
expect(first.history[0].summary).to.equals('message5');
expect(first.history[1].summary).to.equals('message4');
expect(first.history[2].summary).to.equals('message3');
expect(first.next).not.to.equals(null);
const second = await git.getCommitHistory(first.next);
expect(second.history.length).to.equals(2);
expect(second.history[0].summary).to.equals('message2');
expect(second.history[1].summary).to.equals('message1');
expect(second.next).to.equals(null);
});
it('should get history by date range.', async () => {
const today = datetime.today();
const yesterday = datetime.today();
datetime.add(yesterday, DateUnits.DAY, -1);
const tomorrow = datetime.today();
datetime.add(tomorrow, DateUnits.DAY, 1);
await commitFile('a', yesterday.getTime(), 'yesterday');
await commitFile('b', today.getTime(), 'today');
await commitFile('c', tomorrow.getTime(), 'tomorrow');
const yesterdayAndToday = await git.getCommitHistory({
workspaceDirPath: tmpPath,
dateRange: {
since: yesterday.getTime(),
until: today.getTime(),
},
});
expect(yesterdayAndToday.history.length).to.equals(2);
expect(yesterdayAndToday.history[0].summary).to.equals('today');
expect(yesterdayAndToday.history[1].summary).to.equals('yesterday');
const todayAndTomorrow = await git.getCommitHistory({
workspaceDirPath: tmpPath,
dateRange: {
since: today.getTime(),
until: tomorrow.getTime(),
},
});
expect(todayAndTomorrow.history.length).to.equals(2);
expect(todayAndTomorrow.history[0].summary).to.equals('tomorrow');
expect(todayAndTomorrow.history[1].summary).to.equals('today');
const farFuture = datetime.today();
datetime.add(farFuture, DateUnits.DAY, 5);
const nothing = await git.getCommitHistory({
workspaceDirPath: tmpPath,
dateRange: {
since: farFuture.getTime(),
until: farFuture.getTime(),
},
});
expect(nothing.history.length).to.equals(0);
});
});
describe('isRemoteExists', () => {
beforeEach(async () => {
await makeTmpPath(true);
});
it('should return \'false\' if repository has not remote.', async () => {
const result = await git.isRemoteExists({
workspaceDirPath: tmpPath,
remoteName: 'origin',
});
expect(result).to.equals(false);
});
});
describe('getRemoteUrl', () => {
beforeEach(async () => {
await makeTmpPath(true);
});
it('should return url of remote.', async () => {
// First set remote..
const remoteName = 'my_remote';
const remoteUrl = 'some_remote_url';
const repo = await _git.Repository.open(tmpPath);
await _git.Remote.create(repo, remoteName, remoteUrl);
const result = await git.getRemoteUrl({
workspaceDirPath: tmpPath,
remoteName,
});
expect(result).to.equals(remoteUrl);
});
});
describe('setRemote', () => {
beforeEach(async () => {
await makeTmpPath(true);
});
it('should remove exists remote and set new remote.', async () => {
const remoteName = 'origin';
const prevRemoteUrl = 'previous_remote_url';
const nextRemoteUrl = 'next_remote_url';
// Set previous remote...
const repo = await _git.Repository.open(tmpPath);
await _git.Remote.create(repo, remoteName, prevRemoteUrl);
await git.setRemote({
workspaceDirPath: tmpPath,
remoteName,
remoteUrl: nextRemoteUrl,
});
// Check changed remote
const remote = await repo.getRemote(remoteName);
expect(remote.url()).to.equals(nextRemoteUrl);
remote.free();
repo.free();
});
});
/**
* NOTE: This tests require network connection.
* If your network is slow, this test is likely to be timed out.
*/
describe('syncWithRemote', () => {
it('should throw \'MERGE_CONFLICTED\' error when conflict happens during merges '
+ 'fetched branch.', async () => {
let error = null;
try {
await git.syncWithRemote({
workspaceDirPath: getFixturePath('conflict'),
remoteName: 'origin',
authentication: new VcsAuthenticationInfoDummy().create(),
author: new VcsAccountDummy().create(),
});
} catch (err) {
error = err;
}
expect(error).not.equals(null);
expect(error instanceof GitMergeConflictedError).to.equals(true);
});
});
}); | the_stack |
import {
CancellationToken,
ConfigurationTarget,
CustomTextEditorProvider,
Disposable,
Position,
Range,
TextDocument,
Uri,
WebviewPanel,
window,
workspace,
WorkspaceEdit,
} from 'vscode';
import { getNonce } from '@env/crypto';
import { ShowQuickCommitCommand } from '../../commands';
import { configuration } from '../../configuration';
import { CoreCommands } from '../../constants';
import type { Container } from '../../container';
import { RepositoryChange, RepositoryChangeComparisonMode } from '../../git/models';
import { Logger } from '../../logger';
import { Messages } from '../../messages';
import { executeCoreCommand } from '../../system/command';
import { gate } from '../../system/decorators/gate';
import { debug } from '../../system/decorators/log';
import { join, map } from '../../system/iterable';
import { normalizePath } from '../../system/path';
import { IpcMessage, onIpc } from '../protocol';
import {
AbortCommandType,
Author,
ChangeEntryCommandType,
Commit,
DidChangeNotificationType,
DisableCommandType,
MoveEntryCommandType,
RebaseEntry,
RebaseEntryAction,
StartCommandType,
State,
SwitchCommandType,
} from './protocol';
const maxSmallIntegerV8 = 2 ** 30; // Max number that can be stored in V8's smis (small integers)
let ipcSequence = 0;
function nextIpcId() {
if (ipcSequence === maxSmallIntegerV8) {
ipcSequence = 1;
} else {
ipcSequence++;
}
return `host:${ipcSequence}`;
}
let webviewId = 0;
function nextWebviewId() {
if (webviewId === maxSmallIntegerV8) {
webviewId = 1;
} else {
webviewId++;
}
return webviewId;
}
const rebaseRegex = /^\s?#\s?Rebase\s([0-9a-f]+)(?:..([0-9a-f]+))?\sonto\s([0-9a-f]+)\s.*$/im;
const rebaseCommandsRegex = /^\s?(p|pick|r|reword|e|edit|s|squash|f|fixup|d|drop)\s([0-9a-f]+?)\s(.*)$/gm;
const rebaseActionsMap = new Map<string, RebaseEntryAction>([
['p', 'pick'],
['pick', 'pick'],
['r', 'reword'],
['reword', 'reword'],
['e', 'edit'],
['edit', 'edit'],
['s', 'squash'],
['squash', 'squash'],
['f', 'fixup'],
['fixup', 'fixup'],
['d', 'drop'],
['drop', 'drop'],
]);
interface RebaseEditorContext {
dispose(): void;
readonly id: number;
readonly document: TextDocument;
readonly panel: WebviewPanel;
readonly repoPath: string;
readonly subscriptions: Disposable[];
abortOnClose: boolean;
pendingChange?: boolean;
}
export class RebaseEditorProvider implements CustomTextEditorProvider, Disposable {
private readonly _disposable: Disposable;
constructor(private readonly container: Container) {
this._disposable = Disposable.from(
window.registerCustomEditorProvider('gitlens.rebase', this, {
supportsMultipleEditorsPerDocument: false,
webviewOptions: {
retainContextWhenHidden: true,
},
}),
);
}
dispose() {
this._disposable.dispose();
}
get enabled(): boolean {
const associations = configuration.inspectAny<
{ [key: string]: string } | { viewType: string; filenamePattern: string }[]
>('workbench.editorAssociations')?.globalValue;
if (associations == null || associations.length === 0) return true;
if (Array.isArray(associations)) {
const association = associations.find(a => a.filenamePattern === 'git-rebase-todo');
return association != null ? association.viewType === 'gitlens.rebase' : true;
}
const association = associations['git-rebase-todo'];
return association != null ? association === 'gitlens.rebase' : true;
}
private _disableAfterNextUse: boolean = false;
async enableForNextUse() {
if (!this.enabled) {
await this.setEnabled(true);
this._disableAfterNextUse = true;
}
}
async setEnabled(enabled: boolean): Promise<void> {
this._disableAfterNextUse = false;
const inspection = configuration.inspectAny<
{ [key: string]: string } | { viewType: string; filenamePattern: string }[]
>('workbench.editorAssociations');
let associations = inspection?.globalValue;
if (Array.isArray(associations)) {
associations = associations.reduce((accumulator, current) => {
accumulator[current.filenamePattern] = current.viewType;
return accumulator;
}, Object.create(null) as Record<string, string>);
}
if (associations == null) {
if (enabled) return;
associations = {
'git-rebase-todo': 'default',
};
} else {
associations['git-rebase-todo'] = enabled ? 'gitlens.rebase' : 'default';
}
await configuration.updateAny('workbench.editorAssociations', associations, ConfigurationTarget.Global);
}
@debug({ args: false })
async resolveCustomTextEditor(document: TextDocument, panel: WebviewPanel, _token: CancellationToken) {
const repoPath = normalizePath(Uri.joinPath(document.uri, '..', '..', '..').fsPath);
const repo = this.container.git.getRepository(repoPath);
const subscriptions: Disposable[] = [];
const context: RebaseEditorContext = {
dispose: () => Disposable.from(...subscriptions).dispose(),
id: nextWebviewId(),
subscriptions: subscriptions,
document: document,
panel: panel,
repoPath: repo?.path ?? repoPath,
abortOnClose: true,
};
subscriptions.push(
panel.onDidDispose(() => {
// If the user closed this without taking an action, consider it an abort
if (context.abortOnClose) {
void this.abort(context);
}
Disposable.from(...subscriptions).dispose();
}),
panel.onDidChangeViewState(() => {
if (!context.pendingChange) return;
void this.getStateAndNotify(context);
}),
panel.webview.onDidReceiveMessage(e => this.onMessageReceived(context, e)),
workspace.onDidChangeTextDocument(e => {
if (e.contentChanges.length === 0 || e.document.uri.toString() !== document.uri.toString()) return;
void this.getStateAndNotify(context);
}),
workspace.onDidSaveTextDocument(e => {
if (e.uri.toString() !== document.uri.toString()) return;
void this.getStateAndNotify(context);
}),
);
if (repo != null) {
subscriptions.push(
repo.onDidChange(e => {
if (!e.changed(RepositoryChange.Rebase, RepositoryChangeComparisonMode.Any)) return;
void this.getStateAndNotify(context);
}),
);
}
panel.webview.options = { enableCommandUris: true, enableScripts: true };
panel.webview.html = await this.getHtml(context);
if (this._disableAfterNextUse) {
this._disableAfterNextUse = false;
void this.setEnabled(false);
}
}
@gate((context: RebaseEditorContext) => `${context.id}`)
private async getStateAndNotify(context: RebaseEditorContext) {
if (!context.panel.visible) {
context.pendingChange = true;
return;
}
const state = await this.parseState(context);
void this.postMessage(context, {
id: nextIpcId(),
method: DidChangeNotificationType.method,
params: { state: state },
});
}
private async parseState(context: RebaseEditorContext): Promise<State> {
const branch = await this.container.git.getBranch(context.repoPath);
const state = await parseRebaseTodo(this.container, context.document.getText(), context.repoPath, branch?.name);
return state;
}
private async postMessage(context: RebaseEditorContext, message: IpcMessage) {
try {
const success = await context.panel.webview.postMessage(message);
context.pendingChange = !success;
return success;
} catch (ex) {
Logger.error(ex);
context.pendingChange = true;
return false;
}
}
private onMessageReceived(context: RebaseEditorContext, e: IpcMessage) {
switch (e.method) {
// case ReadyCommandType.method:
// onIpcCommand(ReadyCommandType, e, params => {
// this.parseDocumentAndSendChange(panel, document);
// });
// break;
case AbortCommandType.method:
onIpc(AbortCommandType, e, () => this.abort(context));
break;
case DisableCommandType.method:
onIpc(DisableCommandType, e, () => this.disable(context));
break;
case StartCommandType.method:
onIpc(StartCommandType, e, () => this.rebase(context));
break;
case SwitchCommandType.method:
onIpc(SwitchCommandType, e, () => this.switch(context));
break;
case ChangeEntryCommandType.method:
onIpc(ChangeEntryCommandType, e, async params => {
const entries = parseRebaseTodoEntries(context.document);
const entry = entries.find(e => e.ref === params.ref);
if (entry == null) return;
const start = context.document.positionAt(entry.index);
const range = context.document.validateRange(
new Range(new Position(start.line, 0), new Position(start.line, maxSmallIntegerV8)),
);
let action = params.action;
const edit = new WorkspaceEdit();
// Fake the new set of entries, to check if last entry is a squash/fixup
const newEntries = [...entries];
newEntries.splice(entries.indexOf(entry), 1, {
...entry,
action: params.action,
});
let squashing = false;
for (const entry of newEntries) {
if (entry.action === 'squash' || entry.action === 'fixup') {
squashing = true;
} else if (squashing) {
if (entry.action !== 'drop') {
squashing = false;
}
}
}
// Ensure that the last entry isn't a squash/fixup
if (squashing) {
const lastEntry = newEntries[newEntries.length - 1];
if (entry.ref === lastEntry.ref) {
action = 'pick';
} else {
const start = context.document.positionAt(lastEntry.index);
const range = context.document.validateRange(
new Range(new Position(start.line, 0), new Position(start.line, maxSmallIntegerV8)),
);
edit.replace(context.document.uri, range, `pick ${lastEntry.ref} ${lastEntry.message}`);
}
}
edit.replace(context.document.uri, range, `${action} ${entry.ref} ${entry.message}`);
await workspace.applyEdit(edit);
});
break;
case MoveEntryCommandType.method:
onIpc(MoveEntryCommandType, e, async params => {
const entries = parseRebaseTodoEntries(context.document);
const entry = entries.find(e => e.ref === params.ref);
if (entry == null) return;
const index = entries.findIndex(e => e.ref === params.ref);
let newIndex;
if (params.relative) {
if ((params.to === -1 && index === 0) || (params.to === 1 && index === entries.length - 1)) {
return;
}
newIndex = index + params.to;
} else {
if (index === params.to) return;
newIndex = params.to;
}
const newEntry = entries[newIndex];
let newLine = context.document.positionAt(newEntry.index).line;
if (newIndex < index) {
newLine++;
}
const start = context.document.positionAt(entry.index);
const range = context.document.validateRange(
new Range(new Position(start.line, 0), new Position(start.line + 1, 0)),
);
// Fake the new set of entries, so we can ensure that the last entry isn't a squash/fixup
const newEntries = [...entries];
newEntries.splice(index, 1);
newEntries.splice(newIndex, 0, entry);
let squashing = false;
for (const entry of newEntries) {
if (entry.action === 'squash' || entry.action === 'fixup') {
squashing = true;
} else if (squashing) {
if (entry.action !== 'drop') {
squashing = false;
}
}
}
const edit = new WorkspaceEdit();
let action = entry.action;
// Ensure that the last entry isn't a squash/fixup
if (squashing) {
const lastEntry = newEntries[newEntries.length - 1];
if (entry.ref === lastEntry.ref) {
action = 'pick';
} else {
const start = context.document.positionAt(lastEntry.index);
const range = context.document.validateRange(
new Range(new Position(start.line, 0), new Position(start.line, maxSmallIntegerV8)),
);
edit.replace(context.document.uri, range, `pick ${lastEntry.ref} ${lastEntry.message}`);
}
}
edit.delete(context.document.uri, range);
edit.insert(
context.document.uri,
new Position(newLine, 0),
`${action} ${entry.ref} ${entry.message}\n`,
);
await workspace.applyEdit(edit);
});
break;
}
}
private async abort(context: RebaseEditorContext) {
context.abortOnClose = false;
// Avoid triggering events by disposing them first
context.dispose();
// Delete the contents to abort the rebase
const edit = new WorkspaceEdit();
edit.replace(context.document.uri, new Range(0, 0, context.document.lineCount, 0), '');
await workspace.applyEdit(edit);
await context.document.save();
context.panel.dispose();
}
private async disable(context: RebaseEditorContext) {
await this.abort(context);
await this.setEnabled(false);
}
private async rebase(context: RebaseEditorContext) {
context.abortOnClose = false;
// Avoid triggering events by disposing them first
context.dispose();
await context.document.save();
context.panel.dispose();
}
private switch(context: RebaseEditorContext) {
context.abortOnClose = false;
void Messages.showRebaseSwitchToTextWarningMessage();
// Open the text version of the document
void executeCoreCommand(CoreCommands.Open, context.document.uri, {
override: false,
preview: false,
});
}
private async getHtml(context: RebaseEditorContext): Promise<string> {
const webRootUri = Uri.joinPath(this.container.context.extensionUri, 'dist', 'webviews');
const uri = Uri.joinPath(webRootUri, 'rebase.html');
const content = new TextDecoder('utf8').decode(await workspace.fs.readFile(uri));
const bootstrap = await this.parseState(context);
const cspSource = context.panel.webview.cspSource;
const cspNonce = getNonce();
const root = context.panel.webview.asWebviewUri(this.container.context.extensionUri).toString();
const webRoot = context.panel.webview.asWebviewUri(webRootUri).toString();
const html = content
.replace(/#{(head|body|endOfBody)}/i, (_substring, token) => {
switch (token) {
case 'endOfBody':
return `<script type="text/javascript" nonce="#{cspNonce}">window.bootstrap = ${JSON.stringify(
bootstrap,
)};</script>`;
default:
return '';
}
})
.replace(/#{(cspSource|cspNonce|root|webroot)}/g, (substring, token) => {
switch (token) {
case 'cspSource':
return cspSource;
case 'cspNonce':
return cspNonce;
case 'root':
return root;
case 'webroot':
return webRoot;
default:
return '';
}
});
return html;
}
}
async function parseRebaseTodo(
container: Container,
contents: string | { entries: RebaseEntry[]; onto: string },
repoPath: string,
branch: string | undefined,
): Promise<Omit<State, 'rebasing'>> {
let onto: string;
let entries;
if (typeof contents === 'string') {
entries = parseRebaseTodoEntries(contents);
[, , , onto] = rebaseRegex.exec(contents) ?? ['', '', ''];
} else {
({ entries, onto } = contents);
}
const authors = new Map<string, Author>();
const commits: Commit[] = [];
const log = await container.git.getLogForSearch(repoPath, {
pattern: `${onto ? `#:${onto} ` : ''}${join(
map(entries, e => `#:${e.ref}`),
' ',
)}`,
});
const foundCommits = log != null ? [...log.commits.values()] : [];
const ontoCommit = onto ? foundCommits.find(c => c.ref.startsWith(onto)) : undefined;
if (ontoCommit != null) {
const { name, email } = ontoCommit.author;
if (!authors.has(name)) {
authors.set(name, {
author: name,
avatarUrl: (
await ontoCommit.getAvatarUri({ defaultStyle: container.config.defaultGravatarsStyle })
).toString(true),
email: email,
});
}
commits.push({
ref: ontoCommit.ref,
author: name,
date: ontoCommit.formatDate(container.config.defaultDateFormat),
dateFromNow: ontoCommit.formatDateFromNow(),
message: ontoCommit.message || 'root',
});
}
for (const entry of entries) {
const commit = foundCommits.find(c => c.ref.startsWith(entry.ref));
if (commit == null) continue;
// If the onto commit is contained in the list of commits, remove it and clear the 'onto' value — See #1201
if (commit.ref === ontoCommit?.ref) {
commits.splice(0, 1);
onto = '';
}
const { name, email } = commit.author;
if (!authors.has(name)) {
authors.set(name, {
author: name,
avatarUrl: (
await commit.getAvatarUri({ defaultStyle: container.config.defaultGravatarsStyle })
).toString(true),
email: email,
});
}
commits.push({
ref: commit.ref,
author: name,
date: commit.formatDate(container.config.defaultDateFormat),
dateFromNow: commit.formatDateFromNow(),
message: commit.message ?? commit.summary,
});
}
return {
branch: branch ?? '',
onto: onto,
entries: entries,
authors: [...authors.values()],
commits: commits,
commands: {
commit: ShowQuickCommitCommand.getMarkdownCommandArgs(`\${commit}`, repoPath),
},
};
}
function parseRebaseTodoEntries(contents: string): RebaseEntry[];
function parseRebaseTodoEntries(document: TextDocument): RebaseEntry[];
function parseRebaseTodoEntries(contentsOrDocument: string | TextDocument): RebaseEntry[] {
const contents = typeof contentsOrDocument === 'string' ? contentsOrDocument : contentsOrDocument.getText();
const entries: RebaseEntry[] = [];
let match;
let action;
let ref;
let message;
do {
match = rebaseCommandsRegex.exec(contents);
if (match == null) break;
[, action, ref, message] = match;
entries.push({
index: match.index,
action: rebaseActionsMap.get(action) ?? 'pick',
// Stops excessive memory usage -- https://bugs.chromium.org/p/v8/issues/detail?id=2869
ref: ` ${ref}`.substr(1),
// Stops excessive memory usage -- https://bugs.chromium.org/p/v8/issues/detail?id=2869
message: message == null || message.length === 0 ? '' : ` ${message}`.substr(1),
});
} while (true);
return entries.reverse();
} | the_stack |
import * as reflect from 'jsii-reflect';
import * as log4js from 'log4js';
import { validateStabilities } from './stability';
import {
Analysis,
FailedAnalysis,
isSuperType,
isNominalSuperType,
} from './type-analysis';
import { IReport } from './types';
const LOG = log4js.getLogger('jsii-diff');
/**
* The updated type is still nominally assignable to all original base types
*
* Make sure the following remains compilable:
*
* ```
* BASE instance = new CLASS();
* ```
*
* Where CLASS ≤: BASE.
*/
export function validateBaseTypeAssignability<T extends reflect.ReferenceType>(
original: T,
updated: T,
mismatches: IReport,
) {
const ana = assignableToAllBaseTypes(original, updated);
if (!ana.success) {
mismatches.report({
ruleKey: 'base-types',
message: `not assignable to all base types anymore: ${ana.reasons.join(
', ',
)}`,
violator: original,
});
}
}
/**
* The updated type has not been newly made abstract
*
* Make sure the following remains compilable:
*
* ```
* new CLASS();
* ```
*/
export function validateNotMadeAbstract(
original: reflect.ClassType,
updated: reflect.ClassType,
mismatches: IReport,
) {
if (updated.abstract && !original.abstract) {
mismatches.report({
ruleKey: 'made-abstract',
message: 'has gone from non-abstract to abstract',
violator: original,
});
}
}
/**
* The updated type has not had its @subclassable attribute removed
*
* This would lift a restriction we can't afford.
*/
export function validateSubclassableNotRemoved<T extends reflect.ReferenceType>(
original: T,
updated: T,
mismatches: IReport,
) {
if (original.docs.subclassable && !updated.docs.subclassable) {
mismatches.report({
ruleKey: 'remove-subclassable',
message: 'has gone from @subclassable to non-@subclassable',
violator: original,
});
}
}
/**
* Check that the `static`-ness of a member hasn't changed
*/
export function validateStaticSame<T extends reflect.Method | reflect.Property>(
original: T,
updated: T,
mismatches: IReport,
) {
if (original.static !== updated.static) {
mismatches.report({
ruleKey: 'changed-static',
violator: original,
message: `used to be ${
original.static ? 'static' : 'not static'
}, is now ${updated.static ? 'static' : 'not static'}`,
});
}
}
/**
* Check that the `async`-ness of a method hasn't changed
*/
export function validateAsyncSame(
original: reflect.Method,
updated: reflect.Method,
mismatches: IReport,
) {
if (original.async !== updated.async) {
const origQual = original.async ? 'asynchronous' : 'synchronous';
const updQual = updated.async ? 'asynchronous' : 'synchronous';
mismatches.report({
ruleKey: 'changed-async',
violator: original,
message: `was ${origQual}, is now ${updQual}`,
});
}
}
/**
* Once variadic, can never be made non-variadic anymore (because I could always have been passing N+1 arguments)
*/
export function validateNotMadeNonVariadic<
T extends reflect.Method | reflect.Initializer,
>(original: T, updated: T, mismatches: IReport) {
if (original.variadic && !updated.variadic) {
mismatches.report({
ruleKey: 'changed-variadic',
violator: original,
message: 'used to be variadic, not variadic anymore.',
});
}
}
/**
* Check that no new abstract members were added to a subclassable type
*
* You cannot have added abstract members to the class/interface, as they are
* an added burden on potential implementors.
*/
export function validateNoNewAbstractMembers<T extends reflect.ReferenceType>(
original: T,
updated: T,
mismatches: IReport,
) {
const absMemberNames = new Set(
updated.allMembers.filter((m) => m.abstract).map((m) => m.name),
);
const originalMemberNames = new Set(original.allMembers.map((m) => m.name));
for (const name of absMemberNames) {
if (!originalMemberNames.has(name)) {
mismatches.report({
ruleKey: 'new-abstract-member',
message: `adds requirement for subclasses to implement '${name}'.`,
violator: updated.getMembers(true)[name],
});
}
}
}
/**
* Validate that a method return type is the same or strengthened
*
* Make sure the following remains compilable:
*
* ```
* T value = object.method();
* ```
*
* Where RETURN_TYPE(method) ≤: T.
*/
export function validateReturnTypeNotWeakened(
original: reflect.Method,
updated: reflect.Method,
mismatches: IReport,
) {
const retAna = isCompatibleReturnType(original.returns, updated.returns);
if (!retAna.success) {
mismatches.report({
ruleKey: 'change-return-type',
violator: original,
message: `returns ${describeOptionalValueMatchingFailure(
original.returns,
updated.returns,
retAna,
)}`,
});
}
}
/**
* Validate that a method return type is the exact same
*
* Necessary for subclassable types in C#.
*/
export function validateReturnTypeSame(
original: reflect.Method,
updated: reflect.Method,
mismatches: IReport,
) {
const origDescr = reflect.OptionalValue.describe(original.returns);
const updaDescr = reflect.OptionalValue.describe(updated.returns);
if (origDescr !== updaDescr) {
mismatches.report({
ruleKey: 'change-return-type',
violator: original,
message: `returns ${updaDescr} (formerly ${origDescr})`,
});
}
}
/**
* Validate that a property type is the same or strengthened
*
* Make sure the following remains compilable:
*
* ```
* T value = object.prop;
* ```
*
* Where RETURN_TYPE(prop) ≤: T.
*/
export function validatePropertyTypeNotWeakened(
original: reflect.Property,
updated: reflect.Property,
mismatches: IReport,
) {
const ana = isCompatibleReturnType(original, updated);
if (!ana.success) {
mismatches.report({
ruleKey: 'changed-type',
violator: original,
message: `type ${describeOptionalValueMatchingFailure(
original,
updated,
ana,
)}`,
});
}
}
/**
* Validate that a property type is the exact same
*
* Necessary for subclassable types in C#.
*/
export function validatePropertyTypeSame(
original: reflect.Property,
updated: reflect.Property,
mismatches: IReport,
) {
const oldDesc = reflect.OptionalValue.describe(original);
const newDesc = reflect.OptionalValue.describe(updated);
if (oldDesc !== newDesc) {
mismatches.report({
ruleKey: 'changed-type',
violator: original,
message: `changed to ${newDesc} (formerly ${oldDesc})`,
});
}
}
/**
* Validate that a method return type is the same or weakened
*
* Make sure the following remains compilable if U is changed:
*
* ```
* function method(arg: U) { ... }
*
* object.method(<T>value);
* ```
*
* Where T ≤: U.
*/
export function validateParameterTypeWeakened(
method: reflect.Method | reflect.Initializer,
original: reflect.Parameter,
updated: reflect.Parameter,
mismatches: IReport,
) {
const argAna = isCompatibleArgumentType(original.type, updated.type);
if (!argAna.success) {
mismatches.report({
ruleKey: 'incompatible-argument',
violator: method,
message: `argument ${
original.name
}, takes ${describeOptionalValueMatchingFailure(
original,
updated,
argAna,
)}`,
});
return;
}
}
/**
* Validate that a method parameter type is the exact same
*
* Necessary for subclassable types in C#.
*/
export function validateParameterTypeSame(
method: reflect.Method | reflect.Initializer,
original: reflect.Parameter,
updated: reflect.Parameter,
mismatches: IReport,
) {
if (original.type.toString() !== updated.type.toString()) {
mismatches.report({
ruleKey: 'incompatible-argument',
violator: method,
message: `argument ${
original.name
}, takes ${updated.type.toString()} (formerly ${original.type.toString()}): type is @subclassable`,
});
}
}
function describeOptionalValueMatchingFailure(
origType: reflect.OptionalValue,
updatedType: reflect.OptionalValue,
analysis: FailedAnalysis,
) {
const origDescr = reflect.OptionalValue.describe(origType);
const updaDescr = reflect.OptionalValue.describe(updatedType);
if (origDescr !== updaDescr) {
return `${updaDescr} (formerly ${origDescr}): ${analysis.reasons.join(
', ',
)}`;
}
return `${updaDescr}: ${analysis.reasons.join(', ')}`;
}
/**
* Validate that each param in the old callable is still available in the new callable, and apply custom validation to the pairs
*
* Make sure the following remains compilable:
*
* ```
* object.method(a1, a2, ..., aN);
* ```
*
* (All types still assignable)
*/
export function validateExistingParams<
T extends reflect.Initializer | reflect.Method,
>(
original: T,
updated: T,
mismatches: IReport,
validateParam: (
oldParam: reflect.Parameter,
newParam: reflect.Parameter,
) => void,
) {
original.parameters.forEach((param, i) => {
const updatedParam = findParam(updated.parameters, i);
if (updatedParam === undefined) {
mismatches.report({
ruleKey: 'removed-argument',
violator: original,
message: `argument ${param.name}, not accepted anymore.`,
});
return;
}
validateParam(param, updatedParam);
});
}
/**
* Validate that no new required params got added to the end of the method
*
* Make sure the following remains compilable:
*
* ```
* object.method(a1, a2, ..., aN);
* ```
*
* (Not too few arguments)
*/
export function validateNoNewRequiredParams<
T extends reflect.Initializer | reflect.Method,
>(original: T, updated: T, mismatches: IReport) {
updated.parameters.forEach((param, i) => {
if (param.optional) {
return;
}
const origParam = findParam(original.parameters, i);
if (!origParam || origParam.optional) {
mismatches.report({
ruleKey: 'new-argument',
violator: original,
message: `argument ${param.name}, newly required argument.`,
});
}
});
}
export function validateMethodCompatible<
T extends reflect.Method | reflect.Initializer,
>(original: T, updated: T, mismatches: IReport) {
validateStabilities(original, updated, mismatches);
// Type guards on original are duplicated on updated to help tsc... They are required to be the same type by the declaration.
if (reflect.isMethod(original) && reflect.isMethod(updated)) {
validateStaticSame(original, updated, mismatches);
validateAsyncSame(original, updated, mismatches);
validateReturnTypeNotWeakened(original, updated, mismatches);
}
validateNotMadeNonVariadic(original, updated, mismatches);
// Check that every original parameter can still be mapped to a parameter in the updated method
validateExistingParams(
original,
updated,
mismatches,
(oldParam, newParam) => {
validateParameterTypeWeakened(original, oldParam, newParam, mismatches);
},
);
validateNoNewRequiredParams(original, updated, mismatches);
}
/**
* Check if a class/interface has been marked as @subclassable
*/
export function subclassableType(x: reflect.Documentable) {
return x.docs.subclassable;
}
/**
* Find the indicated parameter with the given index
*
* May return the last parameter if it's variadic
*/
function findParam(
parameters: reflect.Parameter[],
i: number,
): reflect.Parameter | undefined {
if (i < parameters.length) {
return parameters[i];
}
const lastParam =
parameters.length > 0 ? parameters[parameters.length - 1] : undefined;
if (lastParam && lastParam.variadic) {
return lastParam;
}
return undefined;
}
/**
* Validate that a previously mutable property is not made immutable
*
* Make sure the following remains compilable:
*
* ```
* object.prop = value;
* ```
*/
export function validateNotMadeImmutable(
original: reflect.Property,
updated: reflect.Property,
mismatches: IReport,
) {
if (updated.immutable && !original.immutable) {
mismatches.report({
ruleKey: 'removed-mutability',
violator: original,
message: 'used to be mutable, is now immutable',
});
}
}
export function* memberPairs<
T extends reflect.TypeMember,
U extends reflect.ReferenceType,
>(
origClass: U,
xs: T[],
updatedClass: U,
mismatches: IReport,
): IterableIterator<[T, reflect.TypeMember]> {
for (const origMember of xs) {
LOG.trace(`${origClass.fqn}#${origMember.name}`);
const updatedMember = updatedClass.allMembers.find(
(m) => m.name === origMember.name,
);
if (!updatedMember) {
mismatches.report({
ruleKey: 'removed',
violator: origMember,
message: 'has been removed',
});
continue;
}
if (origMember.kind !== updatedMember.kind) {
mismatches.report({
ruleKey: 'changed-kind',
violator: origMember,
message: `changed from ${origMember.kind} to ${updatedMember.kind}`,
});
}
if (!origMember.protected && updatedMember.protected) {
mismatches.report({
ruleKey: 'hidden',
violator: origMember,
message: "changed from 'public' to 'protected'",
});
}
yield [origMember, updatedMember];
}
}
/**
* Whether we are strengthening the postcondition (output type of a method or property)
*
* Strengthening output values is allowed!
*/
function isCompatibleReturnType(
original: reflect.OptionalValue,
updated: reflect.OptionalValue,
): Analysis {
if (original.type.void) {
return { success: true };
} // If we didn't use to return anything, returning something now is fine
if (updated.type.void) {
return { success: false, reasons: ["now returning 'void'"] };
} // If we used to return something, we can't stop doing that
if (!original.optional && updated.optional) {
return { success: false, reasons: ['output type is now optional'] };
}
return isSuperType(original.type, updated.type, updated.system);
}
/**
* Whether we are weakening the pre (input type of a method)
*
* Weakening preconditions is allowed!
*/
function isCompatibleArgumentType(
original: reflect.TypeReference,
updated: reflect.TypeReference,
): Analysis {
// Input can never be void, so no need to check
return isSuperType(updated, original, updated.system);
}
/**
* Verify assignability to supertypes
*
* For every base type B of type T, someone could have written:
*
* ```
* const variable: B = new T();
* ```
*
* This code needs to be valid in the updated assembly, so for each
* B an updated type B' needs to exist in the new assembly which is
* still a supertype of T'.
*/
function assignableToAllBaseTypes(
original: reflect.ReferenceType,
updated: reflect.ReferenceType,
): Analysis {
for (const B of baseTypes(original)) {
const result = isNominalSuperType(
B.reference,
updated.reference,
updated.system,
);
if (!result.success) {
return result;
}
}
return { success: true };
}
/**
* Return all base types of the given reference type
*/
function baseTypes(type: reflect.ReferenceType) {
const ret = new Array<reflect.ReferenceType>();
const todo: reflect.ReferenceType[] = [type];
const seen = new Set<string>();
while (todo.length > 0) {
const next = todo.pop()!;
if (seen.has(next.fqn)) {
continue;
}
ret.push(next);
seen.add(next.fqn);
todo.push(...next.interfaces);
if (next.isClassType() && next.base) {
todo.push(next.base);
}
}
return ret;
}
/**
* Validate that each enum member in the old enum enum, and apply custom validation to the enums
*
* Make sure the following remains compilable:
*
* ```
* T x = ENUM.member;
* ```
*
* (For every member of enum)
*/
export function validateExistingMembers(
original: reflect.EnumType,
updated: reflect.EnumType,
mismatches: IReport,
validateMember: (
oldParam: reflect.EnumMember,
newParam: reflect.EnumMember,
) => void,
) {
for (const origMember of original.members) {
const updatedMember = updated.members.find(
(m) => m.name === origMember.name,
);
if (!updatedMember) {
mismatches.report({
ruleKey: 'removed',
violator: origMember,
message: `member ${origMember.name} has been removed`,
});
continue;
}
validateMember(origMember, updatedMember);
}
} | the_stack |
const jStat: any = require('jStat').jStat;
export enum StatisticResult {Slower, Undecided, Faster}
export enum DisplayMode { DisplayMean, DisplayMedian, BoxPlot }
export enum FrameworkType { KEYED, NON_KEYED }
export interface Framework {
name: string;
type: FrameworkType;
issues: number[];
displayname: string;
}
export enum Severity {Error, Categorization}
interface Category {
id: number;
text: string;
issues: Array<number>;
}
export const categories: Category[] = [
{id:1, text:"[Note]: Manual DOM manipulations", issues: [772]},
{id:2, text:"[Note]:View state on the model", issues: [800]},
{id:3, text:"[Note]: Explicit requestAnimationFrame calls", issues: [796]},
{id:4, text:"[Note]: Manual event delegation", issues: [801]},
{id:5, text:"[Issue]: Errors in the implementation", issues: [634, 694]},
]
export const knownIssues = [
{issue: 634, severity: Severity.Error, text:"[Issue]: The HTML structure for the implementation is not fully correct.", link: "https://github.com/krausest/js-framework-benchmark/issues/634"},
{issue: 694, severity: Severity.Error, text:"[Issue]: Keyed implementations must move the DOM nodes for swap rows ", link: "https://github.com/krausest/js-framework-benchmark/issues/694"},
{issue: 772, severity: Severity.Categorization, text:"[Note]: Implementation uses manual DOM manipulations", link: "https://github.com/krausest/js-framework-benchmark/issues/772"},
{issue: 796, severity: Severity.Categorization, text:"[Note]: Implementation uses explicit requestAnimationFrame calls", link: "https://github.com/krausest/js-framework-benchmark/issues/796"},
{issue: 800, severity: Severity.Categorization, text:"[Note]: View state on the model", link: "https://github.com/krausest/js-framework-benchmark/issues/800"},
{issue: 801, severity: Severity.Categorization, text:"[Note]: Implementation uses manual event delegation", link: "https://github.com/krausest/js-framework-benchmark/issues/801"},
];
export function findIssue(issueNumber: number) {
return knownIssues.find(i => i.issue === issueNumber)
}
export enum BenchmarkType { CPU, MEM, STARTUP }
export interface Benchmark {
id: string;
type: BenchmarkType;
label: string;
description: string;
}
export interface RawResult {
f: string;
b: string;
v: number[];
}
export interface Result {
framework: string;
benchmark: string;
values: number[];
mean: number;
median: number;
standardDeviation: number;
}
interface ResultData {
benchmarks: Array<Benchmark>;
results: Array<Array<TableResultValueEntry|null>>;
geomMean: Array<TableResultGeommeanEntry|null>;
comparison: Array<TableResultComparisonEntry|null>;
}
export const SORT_BY_NAME = 'SORT_BY_NAME';
export const SORT_BY_GEOMMEAN_CPU = 'SORT_BY_GEOMMEAN_CPU';
export const SORT_BY_GEOMMEAN_MEM = 'SORT_BY_GEOMMEAN_MEM';
export const SORT_BY_GEOMMEAN_STARTUP = 'SORT_BY_GEOMMEAN_STARTUP';
export type T_SORT_BY_GEOMMEAN = typeof SORT_BY_GEOMMEAN_CPU | typeof SORT_BY_GEOMMEAN_MEM | typeof SORT_BY_GEOMMEAN_STARTUP;
const computeColor = function(factor: number): string {
if (factor < 2.0) {
const a = (factor - 1.0);
const r = (1.0-a)* 99 + a * 255;
const g = (1.0-a)* 191 + a * 236;
const b = (1.0-a)* 124 + a * 132;
return `rgb(${r.toFixed(0)}, ${g.toFixed(0)}, ${b.toFixed(0)})`
} else {
const a = Math.min((factor - 2.0) / 2.0, 1.0);
const r = (1.0-a)* 255 + a * 249;
const g = (1.0-a)* 236 + a * 105;
const b = (1.0-a)* 132 + a * 108;
return `rgb(${r.toFixed(0)}, ${g.toFixed(0)}, ${b.toFixed(0)})`
}
}
export class TableResultValueEntry {
constructor(public key: string, public value: number, public formattedValue: string,
public deviation: string|null, public factor: number, public formattedFactor: string,
public bgColor: string, public textColor: string,
public statisticResult: StatisticResult,
public statisticallySignificantFactor: string|number|undefined = undefined) {
}
}
export class TableResultComparisonEntry {
constructor(public key: string, public framework: Framework, public label: string,
public bgColor: string, public textColor: string) {
}
}
export class TableResultGeommeanEntry {
constructor(public key: string, public framework: Framework, public mean: number, public bgColor: string, public textColor: string) {
}
}
export interface ResultLookup {
(benchmark: Benchmark, framework: Framework): Result|null;
}
export function convertToMap(results: Array<Result>): ResultLookup {
const resultMap = new Map<string, Map<string, Result>>();
results.forEach(r => {
if (!resultMap.has(r.benchmark)) resultMap.set(r.benchmark, new Map<string,Result>());
resultMap.get(r.benchmark)!.set(r.framework, r);
});
return (benchmark: Benchmark, framework: Framework) => {
const m = resultMap.get(benchmark.id);
if (!m) return null;
const v = m.get(framework.name);
if (!v) return null;
return v;
}
}
const undecided: [string, string, StatisticResult] = ['#fff','#000',StatisticResult.Undecided];
const faster: [string, string, StatisticResult] = ['#00b300','#fff',StatisticResult.Faster];
const slower: [string, string, StatisticResult] = ['#b30000','#fff',StatisticResult.Slower];
function colorsForStatisticResult(statisticResult: StatisticResult) {
switch(statisticResult) {
case StatisticResult.Faster:
return faster;
case StatisticResult.Slower:
return slower;
default:
return undecided;
}
}
const statisticComputeColor = function(sign: number, pValue: number): [string, string, StatisticResult] {
if (pValue > 0.10) {
return undecided; //['#fff','#000', StatisticResult.Undecided];
}
if (sign <= 0) {
// let a = 0.8; //(0.1 - pValue) * 10.0;
// let r = 0;
// let g = (1.0-a)* 255 + a * 160;
// let b = 0;
// return [`rgb(${r.toFixed(0)}, ${g.toFixed(0)}, ${b.toFixed(0)})`, '#fff', StatisticResult.Faster];
return faster;
} else {
// let a = 0.8; //(0.1 - pValue) * 10.0;
// let r = (1.0-a)* 255 + a * 160;
// let g = 0;
// let b = 0;
return slower; //[`rgb(${r.toFixed(0)}, ${g.toFixed(0)}, ${b.toFixed(0)})`, '#fff', StatisticResult.Slower];
}
}
const formatEn = new Intl.NumberFormat('en-US', {minimumFractionDigits: 1, maximumFractionDigits: 1, useGrouping: true});
export class ResultTableData {
resultsMap = new Map<BenchmarkType, ResultData>();
// // Rows
// benchmarksCPU: Array<Benchmark>;
// benchmarksStartup: Array<Benchmark>;
// benchmarksMEM: Array<Benchmark>;
// Columns
frameworks: Array<Framework>;
selectedFameworks: Set<Framework>;
// Cell data
// resultsCPU: Array<Array<TableResultValueEntry|null>>; // [benchmark][framework]
// geomMeanCPU: Array<TableResultGeommeanEntry|null>;
// geomMeanStartup: Array<TableResultGeommeanEntry|null>;
// geomMeanMEM: Array<TableResultGeommeanEntry|null>;
// resultsStartup: Array<Array<TableResultValueEntry|null>>;
// resultsMEM: Array<Array<TableResultValueEntry|null>>;
constructor(public allFrameworks: Array<Framework>, public allBenchmarks: Array<Benchmark>, public results: ResultLookup,
public selectedFrameworksInDropdown: Set<Framework>, public selectedBenchmarks: Set<Benchmark>, type: FrameworkType, sortKey: string,
public displayMode: DisplayMode, public compareWith: Framework|undefined, public selectedCategories: Set<number>) {
this.selectedFameworks = new Set<Framework>();
const allowedIssues = new Set<number>();
categories.forEach(c => {
if (selectedCategories.has(c.id)) {
for (const i of c.issues) { allowedIssues.add(i); }
}
});
console.log("ResultTableData", allowedIssues, selectedCategories);
selectedFrameworksInDropdown.forEach(f => {
if (f.issues.every(i => allowedIssues.has(i))
|| (f.name === 'vanillajs-keyed') || (f.name === 'vanillajs-1-keyed')
|| (f.name === 'vanillajs-non-keyed') || (f.name === 'vanillajs-1-non-keyed')
) {
this.selectedFameworks.add(f);
}
})
this.frameworks = this.allFrameworks.filter(framework => framework.type === type && this.selectedFameworks.has(framework));
this.update(sortKey);
}
private update(sortKey: string) {
console.time("update");
const createResult = (type: BenchmarkType): ResultData => {
const benchmarks = this.allBenchmarks.filter(benchmark => benchmark.type === type && this.selectedBenchmarks.has(benchmark));
const results = benchmarks.map(benchmark => this.computeFactors(benchmark));
const geomMean = this.frameworks.map((framework, idx) => {
const resultsForFramework = results.map(arr => arr[idx]);
return this.computeGeometricMean(framework, benchmarks, resultsForFramework);
});
const comparison = this.frameworks.map((framework, idx) => {
const resultsForFramework = results.map(arr => arr[idx]);
return this.computeComparison(framework, benchmarks, resultsForFramework);
});
return {benchmarks, results, geomMean, comparison}
}
[BenchmarkType.CPU, BenchmarkType.MEM, BenchmarkType.STARTUP].forEach((type) =>
this.resultsMap.set(type, createResult(type))
)
this.sortBy(sortKey);
console.timeEnd("update");
}
public getResult(type: BenchmarkType): ResultData {
return this.resultsMap.get(type)!
}
sortBy(sortKey: string) {
const zipped = this.frameworks.map((f,frameworkIndex) => {
let sortValue;
if (sortKey === SORT_BY_NAME) sortValue = f.name;
else if (sortKey === SORT_BY_GEOMMEAN_CPU) sortValue = this.getResult(BenchmarkType.CPU).geomMean[frameworkIndex]!.mean || Number.POSITIVE_INFINITY;
else if (sortKey === SORT_BY_GEOMMEAN_MEM) sortValue = this.getResult(BenchmarkType.MEM).geomMean[frameworkIndex]!.mean || Number.POSITIVE_INFINITY;
else if (sortKey === SORT_BY_GEOMMEAN_STARTUP) sortValue = this.getResult(BenchmarkType.STARTUP).geomMean[frameworkIndex]!.mean || Number.POSITIVE_INFINITY;
else {
const cpuIdx = this.getResult(BenchmarkType.CPU).benchmarks.findIndex(b => b.id === sortKey);
const memIdx = this.getResult(BenchmarkType.MEM).benchmarks.findIndex(b => b.id === sortKey);
const startupIdx = this.getResult(BenchmarkType.STARTUP).benchmarks.findIndex(b => b.id === sortKey);
if (cpuIdx>-1) sortValue = this.getResult(BenchmarkType.CPU).results[cpuIdx][frameworkIndex]?.value ?? Number.POSITIVE_INFINITY;
else if (startupIdx>-1) sortValue = this.getResult(BenchmarkType.STARTUP).results[startupIdx][frameworkIndex]?.value ?? Number.POSITIVE_INFINITY;
else if (memIdx>-1) sortValue = this.getResult(BenchmarkType.MEM).results[memIdx][frameworkIndex]?.value ?? Number.POSITIVE_INFINITY;
else throw Error(`sortKey ${sortKey} not found`);
}
return {
framework: f,
origIndex: frameworkIndex,
sortValue: sortValue
};
});
zipped.sort((a,b) => { if (a.sortValue! < b.sortValue!) return -1; else if (a.sortValue === b.sortValue) return 0; return 1;})
const remappedIdx = zipped.map(z => z.origIndex);
this.frameworks = this.remap(remappedIdx, this.frameworks);
[BenchmarkType.CPU, BenchmarkType.MEM, BenchmarkType.STARTUP].forEach((type) => {
this.getResult(type).results = this.getResult(type).results.map(row => this.remap(remappedIdx, row));
});
[BenchmarkType.CPU, BenchmarkType.MEM, BenchmarkType.STARTUP].forEach((type) => {
this.getResult(type).geomMean = this.remap(remappedIdx, this.getResult(type).geomMean);
});
[BenchmarkType.CPU, BenchmarkType.MEM, BenchmarkType.STARTUP].forEach((type) => {
this.getResult(type).comparison = this.remap(remappedIdx, this.getResult(type).comparison);
});
}
remap<T>(remappedIdx: Array<number>, array: Array<T>): Array<T> {
const copy = new Array<T>(array.length);
remappedIdx.forEach((idx, i) => {
copy[i] = array[idx];
});
return copy;
}
computeGeometricMean(framework: Framework, benchmarksCPU: Array<Benchmark>, resultsCPUForFramework: Array<TableResultValueEntry|null>) {
let count = 0.0;
const gMean = resultsCPUForFramework.reduce((gMean, r) => {
if (r !== null) {
count++;
gMean *= (r.factor as number);
}
return gMean;
}, 1.0);
const value = Math.pow(gMean, 1 / count);
return this.compareWith ? new TableResultGeommeanEntry(framework.name, framework, value, '#fff', '#000') :
new TableResultGeommeanEntry(framework.name, framework, value, computeColor(value), '#000');
}
computeComparison(framework: Framework, benchmarksCPU: Array<Benchmark>, resultsCPUForFramework: Array<TableResultValueEntry|null>) {
if (this.compareWith) {
let statisticResult: StatisticResult|undefined = undefined;
resultsCPUForFramework.forEach((r) => {
if (r?.statisticResult !== StatisticResult.Undecided) {
if (statisticResult === undefined) {
statisticResult = r?.statisticResult;
} else {
if (statisticResult!==r?.statisticResult) statisticResult = StatisticResult.Undecided
}
}
});
let label = '';
statisticResult = statisticResult! ?? StatisticResult.Undecided;
if (statisticResult === StatisticResult.Faster) {
label = 'faster!';
} else if (statisticResult === StatisticResult.Slower) {
label = 'slower!';
}
return new TableResultComparisonEntry(framework.name, framework, label, colorsForStatisticResult(statisticResult)[0], colorsForStatisticResult(statisticResult)[1]);
} else {
return new TableResultComparisonEntry(framework.name, framework, '', '#fff', '#000');
}
}
computeFactors(benchmark: Benchmark): Array<TableResultValueEntry|null> {
const benchmarkResults = this.frameworks.map(f => this.results(benchmark, f));
const selectFn = (result: Result|null) => {
if (result===null) return 0;
if (this.displayMode === DisplayMode.DisplayMedian) {
return result.median;
} else {
return result.mean;
}
}
const min = benchmarkResults.reduce((min, result) => result===null ? min : Math.min(min, selectFn(result)), Number.POSITIVE_INFINITY);
return this.frameworks.map(f => {
const result = this.results(benchmark, f);
if (result === null) return null;
const value = selectFn(result);
const factor = value/min;
const conficenceInterval = 1.959964 * (result.standardDeviation || 0) / Math.sqrt(result.values.length);
const conficenceIntervalStr = benchmark.type === BenchmarkType.MEM ? null : conficenceInterval.toFixed(1);
const formattedValue = formatEn.format(value);
if (!this.compareWith) {
return new TableResultValueEntry(f.name, value, formattedValue, conficenceIntervalStr, factor, factor.toFixed(2), computeColor(factor), '#000', StatisticResult.Undecided);
} else {
const compareWithResults = this.results(benchmark, this.compareWith)!;
// let meanStr = 'x'; //mean.toLocaleString('en-US', {minimumFractionDigits: 1, maximumFractionDigits: 1, useGrouping: true});
// X1,..,Xn: this Framework, Y1, ..., Ym: selected Framework
// https://de.wikipedia.org/wiki/Zweistichproben-t-Test
let statisticalResult = undefined;
let statisticalCol = undefined;
const compareWithMean = compareWithResults.mean;
const stdDev = result.standardDeviation || 0;
const compareWithResultsStdDev = compareWithResults.standardDeviation || 0;
const x1 = result.mean;
const x2 = compareWithMean;
const s1_2 = stdDev*stdDev;
const s2_2 = compareWithResultsStdDev * compareWithResultsStdDev;
const n1 = 10;
const n2 = 10;
const ny = Math.pow(s1_2/n1 + s2_2/n2, 2) / (s1_2*s1_2 / (n1*n1*(n1-1)) + s2_2*s2_2/(n2*n2*(n2-1)));
const t = (x1-x2)/Math.sqrt(s1_2/n1 + s2_2/n2);
const p = (1.0-jStat.studentt.cdf( Math.abs(t), ny ))*2;
statisticalCol = statisticComputeColor(t, p);
statisticalResult = (p*100).toFixed(3)+"%";
return new TableResultValueEntry(f.name, value, formattedValue, conficenceIntervalStr, factor, factor.toFixed(2), statisticalCol[0], statisticalCol[1], statisticalCol[2], statisticalResult);
}
});
}
filterResults = function(bench: Benchmark, frameworks: Array<Framework>, results: Array<Result>) {
return frameworks.reduce((array, framework) => {
const res = results.filter(r => r.benchmark === bench.id && r.framework === framework.name);
if (res.length===1) array.push(res[0]);
else array.push(null);
return array;
}, new Array<Result|null>());
}
} | the_stack |
import React, {
useCallback, useState, FC, useEffect,
} from 'react';
import nodePath from 'path';
import { pathUtils, pagePathUtils } from '@growi/core';
import { useDrag, useDrop } from 'react-dnd';
import { useTranslation } from 'react-i18next';
import { UncontrolledTooltip, DropdownToggle } from 'reactstrap';
import { bookmark, unbookmark, resumeRenameOperation } from '~/client/services/page-operation';
import { toastWarning, toastError, toastSuccess } from '~/client/util/apiNotification';
import { apiv3Put, apiv3Post } from '~/client/util/apiv3-client';
import TriangleIcon from '~/components/Icons/TriangleIcon';
import {
IPageHasId, IPageInfoAll, IPageToDeleteWithMeta,
} from '~/interfaces/page';
import { IPageForPageDuplicateModal } from '~/stores/modal';
import { useSWRxPageChildren } from '~/stores/page-listing';
import { usePageTreeDescCountMap } from '~/stores/ui';
import loggerFactory from '~/utils/logger';
import ClosableTextInput, { AlertInfo, AlertType } from '../../Common/ClosableTextInput';
import CountBadge from '../../Common/CountBadge';
import { PageItemControl } from '../../Common/Dropdown/PageItemControl';
import { ItemNode } from './ItemNode';
const logger = loggerFactory('growi:cli:Item');
interface ItemProps {
isEnableActions: boolean
itemNode: ItemNode
targetPathOrId?: string
isOpen?: boolean
isEnabledAttachTitleHeader?: boolean
onRenamed?(): void
onClickDuplicateMenuItem?(pageToDuplicate: IPageForPageDuplicateModal): void
onClickDeleteMenuItem?(pageToDelete: IPageToDeleteWithMeta): void
}
// Utility to mark target
const markTarget = (children: ItemNode[], targetPathOrId?: string): void => {
if (targetPathOrId == null) {
return;
}
children.forEach((node) => {
if (node.page._id === targetPathOrId || node.page.path === targetPathOrId) {
node.page.isTarget = true;
}
return node;
});
};
const bookmarkMenuItemClickHandler = async(_pageId: string, _newValue: boolean): Promise<void> => {
const bookmarkOperation = _newValue ? bookmark : unbookmark;
await bookmarkOperation(_pageId);
};
/**
* Return new page path after the droppedPagePath is moved under the newParentPagePath
* @param droppedPagePath
* @param newParentPagePath
* @returns
*/
const getNewPathAfterMoved = (droppedPagePath: string, newParentPagePath: string): string => {
const pageTitle = nodePath.basename(droppedPagePath);
return nodePath.join(newParentPagePath, pageTitle);
};
/**
* Return whether the fromPage could be moved under the newParentPage
* @param fromPage
* @param newParentPage
* @param printLog
* @returns
*/
const isDroppable = (fromPage?: Partial<IPageHasId>, newParentPage?: Partial<IPageHasId>, printLog = false): boolean => {
if (fromPage == null || newParentPage == null || fromPage.path == null || newParentPage.path == null) {
if (printLog) {
logger.warn('Any of page, page.path or droppedPage.path is null');
}
return false;
}
const newPathAfterMoved = getNewPathAfterMoved(fromPage.path, newParentPage.path);
return pagePathUtils.canMoveByPath(fromPage.path, newPathAfterMoved) && !pagePathUtils.isUsersTopPage(newParentPage.path);
};
const Item: FC<ItemProps> = (props: ItemProps) => {
const { t } = useTranslation();
const {
itemNode, targetPathOrId, isOpen: _isOpen = false, isEnabledAttachTitleHeader,
onRenamed, onClickDuplicateMenuItem, onClickDeleteMenuItem, isEnableActions,
} = props;
const { page, children } = itemNode;
const [currentChildren, setCurrentChildren] = useState(children);
const [isOpen, setIsOpen] = useState(_isOpen);
const [isNewPageInputShown, setNewPageInputShown] = useState(false);
const [shouldHide, setShouldHide] = useState(false);
const [isRenameInputShown, setRenameInputShown] = useState(false);
const [isCreating, setCreating] = useState(false);
const { data, mutate: mutateChildren } = useSWRxPageChildren(isOpen ? page._id : null);
// descendantCount
const { getDescCount } = usePageTreeDescCountMap();
const descendantCount = getDescCount(page._id) || page.descendantCount || 0;
// hasDescendants flag
const isChildrenLoaded = currentChildren?.length > 0;
const hasDescendants = descendantCount > 0 || isChildrenLoaded;
// to re-show hidden item when useDrag end() callback
const displayDroppedItemByPageId = useCallback((pageId) => {
const target = document.getElementById(`pagetree-item-${pageId}`);
if (target == null) {
return;
}
// wait 500ms to avoid removing before d-none is set by useDrag end() callback
setTimeout(() => {
target.classList.remove('d-none');
}, 500);
}, []);
const [, drag] = useDrag({
type: 'PAGE_TREE',
item: { page },
canDrag: () => {
if (page.path == null) {
return false;
}
return !pagePathUtils.isUsersProtectedPages(page.path);
},
end: (item, monitor) => {
// in order to set d-none to dropped Item
const dropResult = monitor.getDropResult();
if (dropResult != null) {
setShouldHide(true);
}
},
collect: monitor => ({
isDragging: monitor.isDragging(),
canDrag: monitor.canDrag(),
}),
});
const pageItemDropHandler = async(item: ItemNode) => {
const { page: droppedPage } = item;
if (!isDroppable(droppedPage, page, true)) {
return;
}
if (droppedPage.path == null || page.path == null) {
return;
}
const newPagePath = getNewPathAfterMoved(droppedPage.path, page.path);
try {
await apiv3Put('/pages/rename', {
pageId: droppedPage._id,
revisionId: droppedPage.revision,
newPagePath,
isRenameRedirect: false,
updateMetadata: true,
});
await mutateChildren();
if (onRenamed != null) {
onRenamed();
}
// force open
setIsOpen(true);
}
catch (err) {
// display the dropped item
displayDroppedItemByPageId(droppedPage._id);
if (err.code === 'operation__blocked') {
toastWarning(t('pagetree.you_cannot_move_this_page_now'));
}
else {
toastError(t('pagetree.something_went_wrong_with_moving_page'));
}
}
};
const [{ isOver }, drop] = useDrop<ItemNode, Promise<void>, { isOver: boolean }>(() => ({
accept: 'PAGE_TREE',
drop: pageItemDropHandler,
hover: (item, monitor) => {
// when a drag item is overlapped more than 1 sec, the drop target item will be opened.
if (monitor.isOver()) {
setTimeout(() => {
if (monitor.isOver()) {
setIsOpen(true);
}
}, 600);
}
},
canDrop: (item) => {
const { page: droppedPage } = item;
return isDroppable(droppedPage, page);
},
collect: monitor => ({
isOver: monitor.isOver(),
}),
}));
const hasChildren = useCallback((): boolean => {
return currentChildren != null && currentChildren.length > 0;
}, [currentChildren]);
const onClickLoadChildren = useCallback(async() => {
setIsOpen(!isOpen);
}, [isOpen]);
const onClickPlusButton = useCallback(() => {
setNewPageInputShown(true);
if (hasDescendants) {
setIsOpen(true);
}
}, [hasDescendants]);
const duplicateMenuItemClickHandler = useCallback((): void => {
if (onClickDuplicateMenuItem == null) {
return;
}
const { _id: pageId, path } = page;
if (pageId == null || path == null) {
throw Error('Any of _id and path must not be null.');
}
const pageToDuplicate = { pageId, path };
onClickDuplicateMenuItem(pageToDuplicate);
}, [onClickDuplicateMenuItem, page]);
const renameMenuItemClickHandler = useCallback(() => {
setRenameInputShown(true);
}, []);
const onPressEnterForRenameHandler = async(inputText: string) => {
const parentPath = pathUtils.addTrailingSlash(nodePath.dirname(page.path ?? ''));
const newPagePath = nodePath.resolve(parentPath, inputText);
if (newPagePath === page.path) {
setRenameInputShown(false);
return;
}
try {
setRenameInputShown(false);
await apiv3Put('/pages/rename', {
pageId: page._id,
revisionId: page.revision,
newPagePath,
});
if (onRenamed != null) {
onRenamed();
}
toastSuccess(t('renamed_pages', { path: page.path }));
}
catch (err) {
setRenameInputShown(true);
toastError(err);
}
};
const deleteMenuItemClickHandler = useCallback(async(_pageId: string, pageInfo: IPageInfoAll | undefined): Promise<void> => {
if (onClickDeleteMenuItem == null) {
return;
}
if (page._id == null || page.revision == null || page.path == null) {
throw Error('Any of _id, revision, and path must not be null.');
}
const pageToDelete: IPageToDeleteWithMeta = {
data: {
_id: page._id,
revision: page.revision as string,
path: page.path,
},
meta: pageInfo,
};
onClickDeleteMenuItem(pageToDelete);
}, [onClickDeleteMenuItem, page]);
const onPressEnterForCreateHandler = async(inputText: string) => {
setNewPageInputShown(false);
const parentPath = pathUtils.addTrailingSlash(page.path as string);
const newPagePath = nodePath.resolve(parentPath, inputText);
const isCreatable = pagePathUtils.isCreatablePage(newPagePath);
if (!isCreatable) {
toastWarning(t('you_can_not_create_page_with_this_name'));
return;
}
let initBody = '';
if (isEnabledAttachTitleHeader) {
const pageTitle = nodePath.basename(newPagePath);
initBody = pathUtils.attachTitleHeader(pageTitle);
}
try {
setCreating(true);
await apiv3Post('/pages/', {
path: newPagePath,
body: initBody,
grant: page.grant,
grantUserGroupId: page.grantedGroup,
createFromPageTree: true,
});
mutateChildren();
if (!hasDescendants) {
setIsOpen(true);
}
toastSuccess(t('successfully_saved_the_page'));
}
catch (err) {
toastError(err);
}
finally {
setCreating(false);
}
};
const inputValidator = (title: string | null): AlertInfo | null => {
if (title == null || title === '' || title.trim() === '') {
return {
type: AlertType.WARNING,
message: t('form_validation.title_required'),
};
}
return null;
};
/**
* Users do not need to know if all pages have been renamed.
* Make resuming rename operation appears to be working fine to allow users for a seamless operation.
*/
const pathRecoveryMenuItemClickHandler = async(pageId: string): Promise<void> => {
try {
await resumeRenameOperation(pageId);
if (onRenamed != null) {
onRenamed();
}
toastSuccess(t('page_operation.paths_recovered'));
}
catch {
toastError(t('page_operation.path_recovery_failed'));
}
};
// didMount
useEffect(() => {
if (hasChildren()) setIsOpen(true);
}, [hasChildren]);
/*
* Make sure itemNode.children and currentChildren are synced
*/
useEffect(() => {
if (children.length > currentChildren.length) {
markTarget(children, targetPathOrId);
setCurrentChildren(children);
}
}, [children, currentChildren.length, targetPathOrId]);
/*
* When swr fetch succeeded
*/
useEffect(() => {
if (isOpen && data != null) {
const newChildren = ItemNode.generateNodesFromPages(data.children);
markTarget(newChildren, targetPathOrId);
setCurrentChildren(newChildren);
}
}, [data, isOpen, targetPathOrId]);
// Rename process
// Icon that draw attention from users for some actions
const shouldShowAttentionIcon = !!page.processData?.Rename?.isProcessable;
return (
<div
id={`pagetree-item-${page._id}`}
className={`grw-pagetree-item-container ${isOver ? 'grw-pagetree-is-over' : ''}
${shouldHide ? 'd-none' : ''}`}
>
<li
ref={(c) => { drag(c); drop(c) }}
className={`list-group-item list-group-item-action border-0 py-0 pr-3 d-flex align-items-center
${page.isTarget ? 'grw-pagetree-current-page-item' : ''}`}
id={page.isTarget ? 'grw-pagetree-current-page-item' : `grw-pagetree-list-${page._id}`}
>
<div className="grw-triangle-container d-flex justify-content-center">
{hasDescendants && (
<button
type="button"
className={`grw-pagetree-triangle-btn btn ${isOpen ? 'grw-pagetree-open' : ''}`}
onClick={onClickLoadChildren}
>
<div className="d-flex justify-content-center">
<TriangleIcon />
</div>
</button>
)}
</div>
{ isRenameInputShown
? (
<ClosableTextInput
value={nodePath.basename(page.path ?? '')}
placeholder={t('Input page name')}
onClickOutside={() => { setRenameInputShown(false) }}
onPressEnter={onPressEnterForRenameHandler}
inputValidator={inputValidator}
/>
)
: (
<>
{ shouldShowAttentionIcon && (
<>
<i id="path-recovery" className="fa fa-warning mr-2 text-warning"></i>
<UncontrolledTooltip placement="top" target="path-recovery" fade={false}>
{t('tooltip.operation.attention.rename')}
</UncontrolledTooltip>
</>
)}
<a href={`/${page._id}`} className="grw-pagetree-title-anchor flex-grow-1">
<p className={`text-truncate m-auto ${page.isEmpty && 'grw-sidebar-text-muted'}`}>{nodePath.basename(page.path ?? '') || '/'}</p>
</a>
</>
)}
{descendantCount > 0 && !isRenameInputShown && (
<div className="grw-pagetree-count-wrapper">
<CountBadge count={descendantCount} />
</div>
)}
<div className="grw-pagetree-control d-flex">
<PageItemControl
pageId={page._id}
isEnableActions={isEnableActions}
onClickBookmarkMenuItem={bookmarkMenuItemClickHandler}
onClickDuplicateMenuItem={duplicateMenuItemClickHandler}
onClickRenameMenuItem={renameMenuItemClickHandler}
onClickDeleteMenuItem={deleteMenuItemClickHandler}
onClickPathRecoveryMenuItem={pathRecoveryMenuItemClickHandler}
isInstantRename
// Todo: It is wanted to find a better way to pass operationProcessData to PageItemControl
operationProcessData={page.processData}
>
{/* pass the color property to reactstrap dropdownToggle props. https://6-4-0--reactstrap.netlify.app/components/dropdowns/ */}
<DropdownToggle color="transparent" className="border-0 rounded btn-page-item-control p-0 grw-visible-on-hover mr-1">
<i className="icon-options fa fa-rotate-90 p-1"></i>
</DropdownToggle>
</PageItemControl>
{!pagePathUtils.isUsersTopPage(page.path ?? '') && (
<button
type="button"
className="border-0 rounded btn btn-page-item-control p-0 grw-visible-on-hover"
onClick={onClickPlusButton}
>
<i className="icon-plus d-block p-0" />
</button>
)}
</div>
</li>
{isEnableActions && isNewPageInputShown && (
<ClosableTextInput
placeholder={t('Input page name')}
onClickOutside={() => { setNewPageInputShown(false) }}
onPressEnter={onPressEnterForCreateHandler}
inputValidator={inputValidator}
/>
)}
{
isOpen && hasChildren() && currentChildren.map((node, index) => (
<div key={node.page._id} className="grw-pagetree-item-children">
<Item
isEnableActions={isEnableActions}
itemNode={node}
isOpen={false}
targetPathOrId={targetPathOrId}
isEnabledAttachTitleHeader={isEnabledAttachTitleHeader}
onRenamed={onRenamed}
onClickDuplicateMenuItem={onClickDuplicateMenuItem}
onClickDeleteMenuItem={onClickDeleteMenuItem}
/>
{ isCreating && (currentChildren.length - 1 === index) && (
<div className="text-muted text-center">
<i className="fa fa-spinner fa-pulse mr-1"></i>
</div>
)}
</div>
))
}
</div>
);
};
export default Item; | the_stack |
import * as _ from "underscore";
import {UserDatasource} from "../../../model/user-datasource";
import {A_Expr, BoolExpr, JoinExpr, JoinType, RangeVar, ResTarget, SqlDialect, VisualQueryModel, VisualQueryService} from "../../../services/VisualQueryService";
import {QueryParser} from "../../wrangler/query-parser";
import {SparkConstants} from "./spark-constants";
import {StringUtils} from "../../../../common/utils/StringUtils";
import {SparkDataSet} from "../../../model/spark-data-set.model";
import {DataSource} from "../../../catalog/api/models/datasource";
/** Name of the DatasourceProvider variable */
export const DATASOURCE_PROVIDER = "datasourceProvider";
export const DATASET_PROVIDER = "catalogDataSetProvider";
/**
* Handles transformations from a visual query model to Spark.
*/
export class SparkQueryParser extends QueryParser {
/**
* Constructs a {@code SparkQueryParser}.
*/
constructor(visualQueryService: VisualQueryService) {
super(visualQueryService);
}
/**
* Generates a Spark script for the specified SQL query and optional data source.
*
* @param sql - the SQL query
* @param datasources - the data source
* @returns the Spark script
* @throws {Error} if there are too many data sources
*/
protected fromSql(sql: string, datasources: UserDatasource[], catalogDataSources?:DataSource[]): string {
if(catalogDataSources){
return this.fromCatalogDataSourceSql(sql,catalogDataSources);
}
else {
return this.fromUserDatasourceSql(sql,datasources);
}
}
protected fromUserDatasourceSql(sql: string, datasources: UserDatasource[]): string {
if (datasources != null && datasources.length !== 1) {
throw new Error("Not valid datasources: " + datasources);
} else if (datasources != null && datasources.length > 0 && datasources[0].id === SparkConstants.USER_FILE_DATASOURCE) {
return "";
} else if (datasources == null || datasources.length === 0 || datasources[0].id === SparkConstants.HIVE_DATASOURCE) {
return "var " + SparkConstants.DATA_FRAME_VARIABLE + " = sqlContext.sql(\"" + StringUtils.escapeScala(sql) + "\")\n";
} else {
let subquery = "(" + sql + ") AS KYLO_SPARK_QUERY";
return "var " + SparkConstants.DATA_FRAME_VARIABLE + " = " + DATASOURCE_PROVIDER + ".getTableFromDatasource(\"" + StringUtils.escapeScala(subquery) + "\", \""
+ datasources[0].id + "\", sqlContext)\n";
}
}
private fromCatalogDataSourceSql(sql: string, catalogDataSources?: DataSource[]): string {
let hiveDataSource: DataSource = null;
if(catalogDataSources) {
hiveDataSource = catalogDataSources.find(ds => ds.connector.pluginId == "hive");
}
if (catalogDataSources != null && catalogDataSources.length !== 1) {
//only allowed if using 1 datasource
throw new Error("Not valid datasources: " + catalogDataSources);
} else if (catalogDataSources == null || (hiveDataSource != null && hiveDataSource != undefined && catalogDataSources[0].id === hiveDataSource.id)) {
return "var " + SparkConstants.DATA_FRAME_VARIABLE + " = sqlContext.sql(\"" + StringUtils.escapeScala(sql) + "\")\n";
} else {
let subquery = "(" + sql + ") AS KYLO_SPARK_QUERY";
return "var " + SparkConstants.DATA_FRAME_VARIABLE + " = " + DATASOURCE_PROVIDER + ".getTableFromCatalogDataSource(\"" + StringUtils.escapeScala(subquery) + "\", \""
+ catalogDataSources[0].id + "\", sqlContext)\n";
}
}
/**
* Generates a Spark script for the specified visual query model and data sources.
*
* @param visualQueryModel - the visual query model
*/
protected fromVisualQueryModel(visualQueryModel: VisualQueryModel): string {
let self = this;
let tree = VisualQueryService.sqlBuilder(visualQueryModel, SqlDialect.HIVE).buildTree();
// Group targets by table
let targetsByTableAlias = {};
tree.targetList.forEach(function (target: ResTarget) {
if (typeof targetsByTableAlias[target.val.fields[0]] === "undefined") {
targetsByTableAlias[target.val.fields[0]] = [];
}
targetsByTableAlias[target.val.fields[0]].push(target);
});
// Build join script
let joinScript = "";
let tablesByAlias: { [s: string]: RangeVar } = {};
for (const expr of tree.fromClause) {
if (joinScript.length === 0) {
joinScript += "var " + SparkConstants.DATA_FRAME_VARIABLE + " = " + self.getJoinScript(expr, tablesByAlias, true);
} else {
joinScript += self.getJoinScript(expr, tablesByAlias, false);
}
}
// Build table script
let script = "";
_.keys(tablesByAlias).sort().forEach(function (alias) {
let table = tablesByAlias[alias];
script += "val " + alias + " = ";
//TODO for A2A release change this logic to use table.dataset first
//This check here will use hive sqlContext instead of the kyloCatalog for Hive data sources
if (table.dataset != undefined || (typeof table.datasourceId === "string" && table.datasourceId.toLowerCase() !== SparkConstants.HIVE_DATASOURCE.toLowerCase() )) {
if(table.dataset != undefined && !table.datasetMatchesUserDataSource ) {
script += DATASET_PROVIDER +".read(\""+table.dataset.id+"\")";
}else {
script += DATASOURCE_PROVIDER + ".getTableFromDatasource(\"" + StringUtils.escapeScala(table.schemaname + "." + table.relname) + "\", \"" + table.datasourceId
+ "\", sqlContext)";
}
} else {
script += "sqlContext.table(\"" + StringUtils.escapeScala(table.schemaname + "." + table.relname) + "\")"
}
script += ".alias(\"" + alias + "\")\n";
});
script += joinScript+this.joinSelect(tree.targetList);
return script;
}
public joinSelect(targetList:ResTarget[]){
let firstTarget = true;
let script = ".select(";
targetList.forEach(function (target: ResTarget) {
if (firstTarget) {
firstTarget = false;
} else {
script += ", ";
}
script += target.val.fields[0] + ".col(\"" + StringUtils.escapeScala(target.val.fields[1]) + "\")";
if (target.name !== null || target.description !== null) {
script += ".as(\"" + StringUtils.escapeScala((target.name !== null) ? target.name : target.val.fields[1]) + "\"";
if (target.description !== null && target.description != undefined) {
script += ", new org.apache.spark.sql.types.MetadataBuilder().putString(\"comment\", \"" + StringUtils.escapeScala(target.description) + "\").build()";
}
script += ")"
}
});
script += ")\n";
return script;
}
public parseJoinType(joinType:JoinType) {
let join = "";
if (joinType === VisualQueryService.JoinType.JOIN_INNER) {
join = "inner";
} else if (joinType=== VisualQueryService.JoinType.JOIN_LEFT) {
join = "leftouter";
} else if (joinType === VisualQueryService.JoinType.JOIN_RIGHT) {
join = "rightouter"
} else if (joinType === VisualQueryService.JoinType.FULL_JOIN) {
join = "fullouter"
} else {
throw new Error("Not a supported join type: " + joinType);
}
return join;
}
/**
* Generates a Spark script for the specified join expression.
*
* @private
* @param expr - the join expression
* @param tablesByAlias - map of table alias to range var
* @param first - true if this is the first table in the script, or false otherwise
* @returns the Spark script
* @throws {Error} if the join expression is not valid
*/
private getJoinScript(expr: JoinExpr | RangeVar, tablesByAlias: { [s: string]: RangeVar }, first: boolean): string {
if (expr.type === VisualQueryService.NodeTag.RangeVar) {
let rangeVar = expr as RangeVar;
tablesByAlias[rangeVar.aliasName] = rangeVar;
if (first) {
return rangeVar.aliasName;
} else {
return ".join(" + rangeVar.aliasName + ")";
}
} else if (expr.type === VisualQueryService.NodeTag.JoinExpr) {
let joinExpr = expr as JoinExpr;
tablesByAlias[joinExpr.rarg.aliasName] = joinExpr.rarg;
let script = this.getJoinScript(joinExpr.larg, tablesByAlias, first);
script += ".join(" + joinExpr.rarg.aliasName;
if (joinExpr.jointype !== VisualQueryService.JoinType.JOIN) {
script += ", ";
if (joinExpr.quals !== null) {
script += this.getQualifierScript(joinExpr.quals);
} else {
script += "functions.lit(1)";
}
script += ", ";
script +="\""+this.parseJoinType(joinExpr.jointype)+"\"";
}
script += ")";
return script;
} else {
throw new Error("Unsupported type: " + expr.type);
}
}
/**
* Generates a Spark script for the specified qualifier expression.
*
* @param qualifier - the qualifier expression
* @returns the Spark script
* @throws {Error} if the qualifier expression is not valid
*/
private getQualifierScript(qualifier: A_Expr | BoolExpr): string {
if (qualifier.type === VisualQueryService.NodeTag.A_Expr) {
let aExpr = qualifier as A_Expr;
return aExpr.lexpr.fields[0] + ".col(\"" + StringUtils.escapeScala(aExpr.lexpr.fields[1]) + "\").equalTo(" + aExpr.rexpr.fields[0] + ".col(\""
+ StringUtils.escapeScala(aExpr.rexpr.fields[1]) + "\"))";
} else if (qualifier.type === VisualQueryService.NodeTag.BoolExpr) {
let boolExpr = qualifier as BoolExpr;
return this.getQualifierScript(boolExpr.args[0]) + ".and(" + this.getQualifierScript(boolExpr.args[1]) + ")";
} else {
throw new Error("Unsupported type: " + qualifier.type);
}
}
} | the_stack |
import type { TextDocumentContentChangeEvent } from 'vscode-languageserver-textdocument'
import { TextDocument } from 'vscode-languageserver-textdocument'
import type { ExternalEventEmitter, Externals, FsWatcher, IntervalId } from '../common/index.js'
import { bufferToString, Logger, SingletonPromise, StateProxy } from '../common/index.js'
import type { AstNode } from '../node/index.js'
import { FileNode } from '../node/index.js'
import { file } from '../parser/index.js'
import { traversePreOrder } from '../processor/index.js'
import type { LanguageError } from '../source/index.js'
import { Source } from '../source/index.js'
import { SymbolUtil } from '../symbol/index.js'
import { CacheService } from './CacheService.js'
import type { Config } from './Config.js'
import { ConfigService, LinterConfigValue } from './Config.js'
import { BinderContext, CheckerContext, LinterContext, ParserContext, UriBinderContext } from './Context.js'
import type { Dependency } from './Dependency.js'
import { DependencyKey } from './Dependency.js'
import { Downloader } from './Downloader.js'
import { LinterErrorReporter } from './ErrorReporter.js'
import { ArchiveUriSupporter, FileService, FileUriSupporter } from './FileService.js'
import type { RootUriString } from './fileUtil.js'
import { fileUtil } from './fileUtil.js'
import { MetaRegistry } from './MetaRegistry.js'
import { ProfilerFactory } from './Profiler.js'
const CacheAutoSaveInterval = 600_000 // 10 Minutes.
export type ProjectInitializerContext = Pick<Project, 'cacheRoot' | 'config' | 'downloader' | 'externals' | 'logger' | 'meta' | 'projectRoot'>
export type SyncProjectInitializer = (this: void, ctx: ProjectInitializerContext) => Record<string, string> | void
export type AsyncProjectInitializer = (this: void, ctx: ProjectInitializerContext) => PromiseLike<Record<string, string> | void>
export type ProjectInitializer = SyncProjectInitializer | AsyncProjectInitializer
export interface ProjectOptions {
cacheRoot: RootUriString,
defaultConfig?: Config,
downloader?: Downloader,
externals: Externals,
fs?: FileService,
initializers?: readonly ProjectInitializer[],
logger?: Logger,
profilers?: ProfilerFactory,
/**
* A file URI to the root of this project.
*/
projectRoot: RootUriString,
symbols?: SymbolUtil,
}
export interface DocAndNode {
doc: TextDocument,
node: FileNode<AstNode>,
}
interface DocumentEvent extends DocAndNode { }
interface DocumentErrorEvent extends DocumentEvent {
errors: LanguageError[],
}
interface FileEvent {
uri: string,
}
interface EmptyEvent { }
interface RootsEvent {
roots: readonly RootUriString[]
}
interface SymbolRegistrarEvent {
id: string,
checksum: string | undefined,
}
export type ProjectData = Pick<Project, 'cacheRoot' | 'config' | 'downloader' | 'ensureBound' | 'externals' | 'fs' | 'logger' | 'meta' | 'profilers' | 'projectRoot' | 'roots' | 'symbols' | 'ctx'>
/* istanbul ignore next */
/**
* Manage all tracked documents and errors.
*
* The four stages of processing a document:
* 1. `read` - read the file from the external file system as a `TextDocument`.
* 2. `parse` - Parse the `TextDocument` into an `AstNode`.
* 3. `bind` - Bind the `AstNode` and populate both the global symbol table and the local symbol tables on the nodes.
* 4. `check` (includes `lint`) - Check the `AstNode` with information from the symbol tables.
*
* **Caching**
*
* The global symbol table along with a list of file URIs and checksums is cached in memory and is periodically saved to disk.
*
* The `TextDocument`s and file `AstNode`s (including their local symbol tables) managed by the client are stored in memory until the client sends a `didClose` notification.
*
* Some `TextDocument`s may be cached to avoid excessive reading from the file system.
*
* **INIT and READY**
*
* When a new instance of the {@link Project} class is constructed, its INIT and READY processes are immediately started in serial.
*
* During the INIT process of the project, the config and language feature initialization are processed.
* The Promise returned by the {@link init} function resolves when the INIT process is complete.
*
* During the READY process of the project, the whole project is analyzed mainly to populate the global symbol table.
* The Promise returned by the {@link ready} function resolves when the READY process is complete.
*
* The following generally happens during the READY process:
* 1. A list of file URIs under the project is obtained.
* 2. The global symbol cache, if available, is loaded and validated against the know list of files.
* A list of files that need to be (re)processed is returned in this step.
* 3. For each files in the new list, the file is read, parsed, bound, and checked.
*
* **EDITING**
*
* After the READY process is complete, editing text documents as signaled by the client or the file watcher results in the file being re-processed.
*/
export class Project implements ExternalEventEmitter {
private static readonly RootSuffix = '/pack.mcmeta'
readonly #cacheSaverIntervalId: IntervalId
readonly cacheService: CacheService
/**
* URI of files that are currently managed by the language client.
*/
readonly #clientManagedUris = new Set<string>()
readonly #clientManagedDocAndNodes = new Map<string, DocAndNode>()
readonly #configService: ConfigService
readonly #eventEmitter: ExternalEventEmitter
readonly #initializers: readonly ProjectInitializer[]
#initPromise!: Promise<void>
#readyPromise!: Promise<void>
readonly #watchedFiles = new Set<string>()
#watcher!: FsWatcher
#watcherReady = false
#isReady = false
get isReady(): boolean {
return this.#isReady
}
config!: Config
readonly downloader: Downloader
readonly externals: Externals
readonly fs: FileService
readonly logger: Logger
readonly meta = new MetaRegistry()
readonly profilers: ProfilerFactory
readonly projectRoot: RootUriString
symbols: SymbolUtil
#dependencyRoots!: Set<RootUriString>
#dependencyFiles!: Set<string>
#roots: readonly RootUriString[] = []
/**
* All tracked root URIs. Each URI in this array is guaranteed to end with a slash (`/`).
*
* Includes the roots of all dependencies, the project root, and all data pack roots identified
* by `pack.mcmeta` files.
*
* Some URIs in the array may overlap with each other. In such cases, the deeper ones are guaranteed to come
* before the shallower ones (e.g. `file:///foo/bar/` will come before `file:///foo/`).
*/
get roots(): readonly RootUriString[] {
return this.#roots
}
#ctx!: Record<string, string>
/**
* Arbitrary information that will be included in the `project` property of all `Context`s.
*/
get ctx() {
return this.#ctx
}
#cacheRoot: RootUriString
/**
* File URI to a directory where all cache files of Spyglass should be stored.
*/
get cacheRoot(): RootUriString {
return this.#cacheRoot
}
private updateRoots(): void {
const rawRoots = [...this.#dependencyRoots, this.projectRoot]
const ans = new Set(rawRoots)
// Identify roots indicated by `pack.mcmeta`.
for (const file of this.getTrackedFiles()) {
if (file.endsWith(Project.RootSuffix) && rawRoots.some(r => file.startsWith(r))) {
ans.add(file.slice(0, 1 - Project.RootSuffix.length) as RootUriString)
}
}
this.#roots = [...ans].sort((a, b) => b.length - a.length)
this.emit('rootsUpdated', { roots: this.#roots })
}
on(event: 'documentErrorred', callbackFn: (data: DocumentErrorEvent) => void): this
on(event: 'documentUpdated', callbackFn: (data: DocumentEvent) => void): this
// `documentRemoved` uses a `FileEvent` instead of `DocumentEvent`, as it doesn't have access to
// the document anymore.
on(event: 'documentRemoved', callbackFn: (data: FileEvent) => void): this
on(event: `file${'Created' | 'Modified' | 'Deleted'}`, callbackFn: (data: FileEvent) => void): this
on(event: 'ready', callbackFn: (data: EmptyEvent) => void): this
on(event: 'rootsUpdated', callbackFn: (data: RootsEvent) => void): this
on(event: 'symbolRegistrarExecuted', callbackFn: (data: SymbolRegistrarEvent) => void): this
on(event: string, callbackFn: (...args: any[]) => unknown): this {
this.#eventEmitter.on(event, callbackFn)
return this
}
once(event: 'documentErrorred', callbackFn: (data: DocumentErrorEvent) => void): this
once(event: 'documentUpdated', callbackFn: (data: DocumentEvent) => void): this
once(event: 'documentRemoved', callbackFn: (data: FileEvent) => void): this
once(event: `file${'Created' | 'Modified' | 'Deleted'}`, callbackFn: (data: FileEvent) => void): this
once(event: 'ready', callbackFn: (data: EmptyEvent) => void): this
once(event: 'rootsUpdated', callbackFn: (data: RootsEvent) => void): this
once(event: 'symbolRegistrarExecuted', callbackFn: (data: SymbolRegistrarEvent) => void): this
once(event: string, callbackFn: (...args: any[]) => unknown): this {
this.#eventEmitter.once(event, callbackFn)
return this
}
emit(event: 'documentErrorred', data: DocumentErrorEvent): boolean
emit(event: 'documentUpdated', data: DocumentEvent): boolean
emit(event: 'documentRemoved', data: FileEvent): boolean
emit(event: `file${'Created' | 'Modified' | 'Deleted'}`, data: FileEvent): boolean
emit(event: 'ready', data: EmptyEvent): boolean
emit(event: 'rootsUpdated', data: RootsEvent): boolean
emit(event: 'symbolRegistrarExecuted', data: SymbolRegistrarEvent): boolean
emit(event: string, ...args: unknown[]): boolean {
return this.#eventEmitter.emit(event, ...args)
}
/**
* Get all files that are tracked and supported.
*
* Files in cached archives may not show up in the result as those files
* are not loaded into the memory.
*/
getTrackedFiles(): string[] {
const extensions: string[] = this.meta.getSupportedFileExtensions()
return [...this.#dependencyFiles, ...this.#watchedFiles]
.filter(file => extensions.includes(fileUtil.extname(file) ?? ''))
}
constructor({
cacheRoot,
defaultConfig,
downloader,
externals,
fs = FileService.create(externals, cacheRoot),
initializers = [],
logger = Logger.create(),
profilers = ProfilerFactory.noop(),
projectRoot,
}: ProjectOptions) {
this.#cacheRoot = cacheRoot
this.#eventEmitter = new externals.event.EventEmitter()
this.externals = externals
this.fs = fs
this.#initializers = initializers
this.logger = logger
this.profilers = profilers
this.projectRoot = projectRoot
this.cacheService = new CacheService(cacheRoot, this)
this.#configService = new ConfigService(this, defaultConfig)
this.downloader = downloader ?? new Downloader(cacheRoot, externals, logger)
this.symbols = new SymbolUtil({}, externals.event.EventEmitter)
this.#ctx = {}
this.logger.info(`[Project] [init] cacheRoot = “${cacheRoot}”`)
this.#configService
.on('changed', ({ config }) => {
this.config = config
this.logger.info('[Project] [Config] Changed')
})
.on('error', ({ error, uri }) => this.logger.error(`[Project] [Config] Failed loading “${uri}”`, error))
this.setInitPromise()
this.setReadyPromise()
this.#cacheSaverIntervalId = setInterval(() => this.cacheService.save(), CacheAutoSaveInterval)
this
.on('documentUpdated', ({ doc, node }) => {
if (!this.#isReady) {
return
}
this.emit('documentErrorred', {
doc,
errors: FileNode.getErrors(node),
node,
})
})
.on('fileCreated', async ({ uri }) => {
if (uri.endsWith(Project.RootSuffix)) {
this.updateRoots()
}
this.bindUri(uri)
return this.ensureBound(uri)
})
.on('fileModified', async ({ uri }) => {
if (this.isOnlyWatched(uri)) {
await this.ensureBound(uri)
}
})
.on('fileDeleted', ({ uri }) => {
if (uri.endsWith(Project.RootSuffix)) {
this.updateRoots()
}
this.symbols.clear({ uri })
this.tryClearingCache(uri)
})
.on('ready', () => {
this.#isReady = true
// // Recheck client managed files after the READY process, as they may have incomplete results and are user-facing.
// const promises: Promise<unknown>[] = []
// for (const { doc, node } of this.#clientManagedDocAndNodes.values()) {
// promises.push(this.check(doc, node))
// }
// Promise.all(promises).catch(e => this.logger.error('[Project#ready] Error occurred when rechecking client managed files after READY', e))
})
}
private setInitPromise(): void {
const loadConfig = async () => {
this.config = await this.#configService.load()
}
const callIntializers = async () => {
const initCtx: ProjectInitializerContext = {
cacheRoot: this.cacheRoot,
config: this.config,
downloader: this.downloader,
externals: this.externals,
logger: this.logger,
meta: this.meta,
projectRoot: this.projectRoot,
}
const results = await Promise.allSettled(this.#initializers.map(init => init(initCtx)))
let ctx: Record<string, string> = {}
results.forEach(async (r, i) => {
if (r.status === 'rejected') {
this.logger.error(`[Project] [callInitializers] [${i}] “${this.#initializers[i].name}”`, r.reason)
} else if (r.value) {
ctx = { ...ctx, ...r.value }
}
})
this.#ctx = ctx
}
const init = async () => {
const __profiler = this.profilers.get('project#init')
const { symbols } = await this.cacheService.load()
this.symbols = new SymbolUtil(symbols, this.externals.event.EventEmitter)
this.symbols.buildCache()
__profiler.task('Load Cache')
await loadConfig()
__profiler.task('Load Config')
await callIntializers()
__profiler.task('Initialize').finalize()
}
this.#initPromise = init()
}
private setReadyPromise(): void {
const getDependencies = async () => {
const ans: Dependency[] = []
for (const dependency of this.config.env.dependencies) {
if (DependencyKey.is(dependency)) {
const provider = this.meta.getDependencyProvider(dependency)
if (provider) {
try {
ans.push(await provider())
this.logger.info(`[Project] [getDependencies] Executed provider “${dependency}”`)
} catch (e) {
this.logger.error(`[Project] [getDependencies] Bad provider “${dependency}”`, e)
}
} else {
this.logger.error(`[Project] [getDependencies] Bad dependency “${dependency}”: no associated provider`)
}
} else {
ans.push({ uri: dependency })
}
}
return ans
}
const listDependencyFiles = async () => {
const dependencies = await getDependencies()
const fileUriSupporter = await FileUriSupporter.create(dependencies, this.externals, this.logger)
const archiveUriSupporter = await ArchiveUriSupporter.create(dependencies, this.externals, this.logger, this.cacheService.checksums.roots)
this.fs.register('file:', fileUriSupporter, true)
this.fs.register(ArchiveUriSupporter.Protocol, archiveUriSupporter, true)
}
const listProjectFiles = () => new Promise<void>(resolve => {
this.#watcherReady = false
this.#watcher = this.externals.fs
.watch(this.projectRoot)
.once('ready', () => {
this.#watcherReady = true
resolve()
})
.on('add', uri => {
this.#watchedFiles.add(uri)
if (this.#watcherReady) {
this.emit('fileCreated', { uri })
}
})
.on('change', uri => {
if (this.#watcherReady) {
this.emit('fileModified', { uri })
}
})
.on('unlink', uri => {
this.#watchedFiles.delete(uri)
if (this.#watcherReady) {
this.emit('fileDeleted', { uri })
}
})
.on('error', e => {
this.logger.error('[Project] [chokidar]', e)
})
})
const ready = async () => {
await this.init()
const __profiler = this.profilers.get('project#ready')
await Promise.all([
listDependencyFiles(),
listProjectFiles(),
])
this.#dependencyFiles = new Set(this.fs.listFiles())
this.#dependencyRoots = new Set(this.fs.listRoots())
this.updateRoots()
__profiler.task('List URIs')
for (const [id, { checksum, registrar }] of this.meta.symbolRegistrars) {
const cacheChecksum = this.cacheService.checksums.symbolRegistrars[id]
if (cacheChecksum === undefined || checksum !== cacheChecksum) {
this.symbols.clear({ contributor: `symbol_registrar/${id}` })
this.symbols.contributeAs(`symbol_registrar/${id}`, () => {
registrar(this.symbols, { logger: this.logger })
})
this.emit('symbolRegistrarExecuted', { id, checksum })
} else {
this.logger.info(`[SymbolRegistrar] Skipped “${id}” thanks to cache ${checksum}`)
}
}
__profiler.task('Register Symbols')
const { addedFiles, changedFiles, removedFiles } = await this.cacheService.validate()
for (const uri of removedFiles) {
this.symbols.clear({ uri })
}
__profiler.task('Validate Cache')
if (addedFiles.length > 0) {
this.bindUri(addedFiles)
}
__profiler.task('Bind URIs')
const files = [...addedFiles, ...changedFiles].sort(this.meta.uriSorter)
__profiler.task('Sort URIs')
const __bindProfiler = this.profilers.get('project#ready#bind', 'top-n', 50)
for (const uri of files) {
await this.ensureBound(uri)
__bindProfiler.task(uri)
}
__bindProfiler.finalize()
__profiler.task('Bind Files')
__profiler.finalize()
this.emit('ready', {})
}
this.#readyPromise = ready()
}
/**
* Load the config file and initialize parsers and processors.
*/
async init(): Promise<this> {
await this.#initPromise
return this
}
/**
* Finish the initial run of parsing, binding, and checking the entire project.
*/
async ready(): Promise<this> {
await this.#readyPromise
return this
}
/**
* Behavior of the `Project` instance is undefined after this function has settled.
*/
async close(): Promise<void> {
clearInterval(this.#cacheSaverIntervalId)
await this.#watcher.close()
await this.cacheService.save()
}
async restart(): Promise<void> {
try {
await this.#watcher.close()
this.setReadyPromise()
await this.ready()
} catch (e) {
this.logger.error('[Project#reset]', e)
}
}
resetCache(): void {
return this.cacheService.reset()
}
normalizeUri(uri: string): string {
return this.fs.mapFromDisk(this.externals.uri.normalize(uri))
}
private static readonly TextDocumentCacheMaxLength = 268435456
#textDocumentCache = new Map<string, Promise<TextDocument | undefined> | TextDocument>()
#textDocumentCacheLength = 0
private removeCachedTextDocument(uri: string): void {
const doc = this.#textDocumentCache.get(uri)
if (doc && !(doc instanceof Promise)) {
this.#textDocumentCacheLength -= doc.getText().length
}
this.#textDocumentCache.delete(uri)
}
private async read(uri: string): Promise<TextDocument | undefined> {
const getLanguageID = (uri: string): string => {
const ext = fileUtil.extname(uri) ?? '.plaintext'
return this.meta.getLanguageID(ext) ?? ext.slice(1)
}
const createTextDocument = async (uri: string): Promise<TextDocument | undefined> => {
const languageId = getLanguageID(uri)
if (!this.meta.isSupportedLanguage(languageId)) {
return undefined
}
try {
const content = bufferToString(await this.fs.readFile(uri))
return TextDocument.create(uri, languageId, -1, content)
} catch (e) {
this.logger.warn(`[Project] [read] Failed creating TextDocument for “${uri}”`, e)
return undefined
}
}
const trimCache = (): void => {
const iterator = this.#textDocumentCache.keys()
while (this.#textDocumentCacheLength > Project.TextDocumentCacheMaxLength) {
const result = iterator.next()
if (result.done) {
throw new Error(`[Project] [read] Cache is too large with length ${this.#textDocumentCacheLength} even though it's empty; make sure to call 'removeCachedTextDocument()' instead of 'this.#textDocumentCache.delete()'`)
}
this.removeCachedTextDocument(result.value)
}
}
const getCacheHandlingPromise = async (uri: string): Promise<TextDocument | undefined> => {
if (this.#textDocumentCache.has(uri)) {
const ans = this.#textDocumentCache.get(uri)!
// Move the entry to the end of the cache.
// The goal is that more-frequently-used entries are preferably not trimmed.
this.#textDocumentCache.delete(uri)
this.#textDocumentCache.set(uri, ans)
return ans
} else {
const promise = createTextDocument(uri)
this.#textDocumentCache.set(uri, promise)
// We replace the Promise in the cache with the TextDocument after it resolves,
// or removes it from the cache if it resolves to undefined.
const doc = await promise
if (this.#textDocumentCache.get(uri) === promise) {
// The Promise in the cache is the same as the one we created earlier.
// This check is to make sure we don't set a wrong TextDocument to the cache in case the cache was modified elsewhere.
if (doc) {
this.#textDocumentCache.set(uri, doc)
this.#textDocumentCacheLength += doc.getText().length
trimCache()
} else {
this.#textDocumentCache.delete(uri)
}
}
return doc
}
}
uri = this.normalizeUri(uri)
if (this.#clientManagedUris.has(uri)) {
const result = this.#clientManagedDocAndNodes.get(uri)
if (result) {
return result.doc
}
throw new Error(`[Project] [read] Client-managed URI “${uri}” does not have a TextDocument in the cache`)
}
return getCacheHandlingPromise(uri)
}
private parse(doc: TextDocument): FileNode<AstNode> {
const ctx = ParserContext.create(this, { doc })
const src = new Source(doc.getText())
const node = file()(src, ctx)
return node
}
@SingletonPromise()
private async bind(doc: TextDocument, node: FileNode<AstNode>): Promise<void> {
if (node.binderErrors) {
return
}
try {
const binder = this.meta.getBinder(node.type)
const ctx = BinderContext.create(this, { doc })
ctx.symbols.clear({ contributor: 'binder', uri: doc.uri })
await ctx.symbols.contributeAsAsync('binder', async () => {
const proxy = StateProxy.create(node)
await binder(proxy, ctx)
node.binderErrors = ctx.err.dump()
})
} catch (e) {
this.logger.error(`[Project] [bind] Failed for “${doc.uri}” #${doc.version}`, e)
}
}
@SingletonPromise()
private async check(doc: TextDocument, node: FileNode<AstNode>): Promise<void> {
if (node.checkerErrors) {
return
}
try {
const checker = this.meta.getChecker(node.type)
const ctx = CheckerContext.create(this, { doc })
ctx.symbols.clear({ contributor: 'checker', uri: doc.uri })
await ctx.symbols.contributeAsAsync('checker', async () => {
await checker(StateProxy.create(node), ctx)
node.checkerErrors = ctx.err.dump()
this.lint(doc, node)
})
} catch (e) {
this.logger.error(`[Project] [check] Failed for “${doc.uri}” #${doc.version}`, e)
}
}
private lint(doc: TextDocument, node: FileNode<AstNode>): void {
if (node.linterErrors) {
return
}
node.linterErrors = []
try {
for (const [ruleName, rawValue] of Object.entries(this.config.lint)) {
const result = LinterConfigValue.destruct(rawValue)
if (!result) {
// Rule is disabled (i.e. set to `null`) in the config.
continue
}
const { ruleSeverity, ruleValue } = result
const { configValidator, linter, nodePredicate } = this.meta.getLinter(ruleName)
if (!configValidator(ruleName, ruleValue, this.logger)) {
// Config value is invalid.
continue
}
const ctx = LinterContext.create(this, {
doc,
err: new LinterErrorReporter(ruleName, ruleSeverity),
ruleName,
ruleValue,
})
traversePreOrder(
node,
() => true,
() => true,
node => {
if (nodePredicate(node)) {
const proxy = StateProxy.create(node)
linter(proxy, ctx)
}
}
);
(node.linterErrors as LanguageError[]).push(...ctx.err.dump())
}
} catch (e) {
this.logger.error(`[Project] [lint] Failed for “${doc.uri}” #${doc.version}`, e)
}
}
@SingletonPromise()
async ensureBound(uri: string): Promise<void> {
const doc = await this.read(uri)
if (!doc || !(await this.cacheService.hasFileChangedSinceCache(doc))) {
return
}
const node = this.parse(doc)
await this.bind(doc, node)
this.emit('documentUpdated', { doc, node })
}
private bindUri(param: string | string[]): void {
const ctx = UriBinderContext.create(this)
if (typeof param === 'string') {
ctx.symbols.clear({ contributor: 'uri_binder', uri: param })
}
ctx.symbols.contributeAs('uri_binder', () => {
const uris = Array.isArray(param) ? param : [param]
for (const binder of this.meta.uriBinders) {
binder(uris, ctx)
}
})
}
/**
* Notify that a new document was opened in the editor.
*/
async onDidOpen(uri: string, languageID: string, version: number, content: string): Promise<void> {
uri = this.normalizeUri(uri)
if (!fileUtil.isFileUri(uri)) {
return // We only accept `file:` scheme for client-managed URIs.
}
const doc = TextDocument.create(uri, languageID, version, content)
const node = this.parse(doc)
this.#clientManagedUris.add(uri)
this.#clientManagedDocAndNodes.set(uri, { doc, node })
if (this.#isReady) {
await this.bind(doc, node)
await this.check(doc, node)
}
}
/**
* Notify that an existing document was changed in the editor.
* @throws If there is no `TextDocument` corresponding to the URI.
*/
async onDidChange(uri: string, changes: TextDocumentContentChangeEvent[], version: number): Promise<void> {
uri = this.normalizeUri(uri)
if (!fileUtil.isFileUri(uri)) {
return // We only accept `file:` scheme for client-managed URIs.
}
const doc = this.#clientManagedDocAndNodes.get(uri)?.doc
if (!doc) {
throw new Error(`TextDocument for “${uri}” is ${!doc ? 'not cached' : 'a Promise'}. This should not happen. Did the language client send a didChange notification without sending a didOpen one, or is there a logic error on our side resulting the 'read' function overriding the 'TextDocument' created in the 'didOpen' notification handler?`)
}
TextDocument.update(doc, changes, version)
const node = this.parse(doc)
this.#clientManagedDocAndNodes.set(uri, { doc, node })
if (this.#isReady) {
await this.bind(doc, node)
await this.check(doc, node)
}
}
/**
* Notify that an existing document was closed in the editor.
*/
onDidClose(uri: string): void {
uri = this.normalizeUri(uri)
if (!fileUtil.isFileUri(uri)) {
return // We only accept `file:` scheme for client-managed URIs.
}
this.#clientManagedUris.delete(uri)
this.#clientManagedDocAndNodes.delete(uri)
this.tryClearingCache(uri)
}
@SingletonPromise()
async ensureClientManagedChecked(uri: string): Promise<DocAndNode | undefined> {
const result = this.#clientManagedDocAndNodes.get(uri)
if (result && this.#isReady) {
const { doc, node } = result
await this.bind(doc, node)
await this.check(doc, node)
this.emit('documentUpdated', { doc, node })
return { doc, node }
}
return undefined
}
getClientManaged(uri: string): DocAndNode | undefined {
return this.#clientManagedDocAndNodes.get(uri)
}
async showCacheRoot(): Promise<void> {
if (!this.#cacheRoot) {
return
}
try {
await this.externals.fs.showFile(this.#cacheRoot)
} catch (e) {
this.logger.error('[Service#showCacheRoot]', e)
}
}
private tryClearingCache(uri: string): void {
if (this.shouldRemove(uri)) {
this.removeCachedTextDocument(uri)
this.emit('documentRemoved', { uri })
}
}
private shouldRemove(uri: string): boolean {
return !this.#clientManagedUris.has(uri) && !this.#dependencyFiles.has(uri) && !this.#watchedFiles.has(uri)
}
private isOnlyWatched(uri: string): boolean {
return this.#watchedFiles.has(uri) && !this.#clientManagedUris.has(uri) && !this.#dependencyFiles.has(uri)
}
} | the_stack |
import * as crypto from "crypto";
import ICryptoKeyIV from "../../ICryptoKeyIV";
import CryptoTools from "../../CryptoTools";
const TAG_SIZE = 16;
const MIN_CHUNK_LEN = TAG_SIZE * 2 + 3;
const MIN_CHUNK_SPLIT_LEN = 0x0800;
const MAX_CHUNK_SPLIT_LEN = 0x3FFF;
const INFO_STR = "ss-subkey";
/**
* calculate the HMAC from key and message
* @param algorithm
* @param key
* @param buffer
* @returns {Buffer}
*/
function hmac(algorithm, key, buffer): Buffer {
// tslint:disable-next-line:no-shadowed-variable
const hmac = crypto.createHmac(algorithm, key);
return hmac.update(buffer).digest();
}
/**
* HMAC-based Extract-and-Expand Key Derivation Function
* @param hash, the message digest algorithm
* @param salt, a non-secret random value
* @param ikm, input keying material
* @param info, optional context and application specific information
* @param length, length of output keying material in octets
* @returns {Buffer}
*/
function HKDF(hash, salt, ikm, info: string, length): Buffer {
// Step 1: "extract" to fixed length pseudo-random key(prk)
const prk = hmac(hash, salt, ikm);
// Step 2: "expand" prk to several pseudo-random keys(okm)
let t = Buffer.alloc(0);
let okm = Buffer.alloc(0);
for (let i = 0; i < Math.ceil(length / prk.length); ++i) {
t = hmac(hash, prk, Buffer.concat([t, Buffer.from(info), Buffer.alloc(1, i + 1)]));
okm = Buffer.concat([okm, t]);
}
// Step 3: crop okm to desired length
return okm.slice(0, length);
}
/**
* returns a random integer in [min, max].
* @param min
* @param max
* @returns {Number}
*/
function getRandomInt(min: number, max: number): number {
min = Math.ceil(min);
max = Math.ceil(max);
const random = crypto.randomBytes(1)[0] / (0xff + 1e-13);
return Math.floor(random * (max - min + 1) + min);
}
/**
* split buffer into chunks, each chunk size is picked randomly from [min, max]
* @param buffer
* @param min
* @param max
* @returns {Array<Buffer>}
*/
function getRandomChunks(buffer: Buffer, min: number, max: number): Array<Buffer> {
const totalLen = buffer.length;
const bufs = [];
let ptr = 0;
while (ptr < totalLen - 1) {
const offset = getRandomInt(min, max);
bufs.push(buffer.slice(ptr, ptr + offset));
ptr += offset;
}
if (ptr < totalLen) {
bufs.push(buffer.slice(ptr));
}
return bufs;
}
/**
* convert a number to a buffer with specified length in specified byte order
* @param num
* @param len
* @param byteOrder
* @returns {Buffer}
*/
export function numberToBuffer(num: number, len: number = 2, bigEndian: boolean = true): Buffer {
if (len < 1) {
throw Error("len must be greater than 0");
}
// tslint:disable-next-line:radix
const isOutOfRange = num > parseInt(`0x${"ff".repeat(len)}`);
if (isOutOfRange) {
throw Error(`Number ${num} is too big to put into a ${len} byte(s) size buffer`);
}
const buf = Buffer.allocUnsafe(len);
bigEndian ? buf.writeUIntBE(num, 0, len) : buf.writeUIntLE(num, 0, len);
return buf;
}
export default class AEADCryotoProcess {
private readonly cryptoKeyIV: ICryptoKeyIV;
private readonly keyLength: number = -1;
private readonly saltLength: number = -1;
private readonly nonceLength: number = -1;
private readonly cryptoName: string = "";
private cipherKey: Buffer = null;
private cipherNonce: number = 0;
private decipherKey: Buffer = null;
private decipherNonce: number = 0;
private dataCache: Buffer = Buffer.allocUnsafe(0);
constructor(cryptoName: string, keyLength: number, saltLength: number, nonceLength: number, password: string) {
[this.cryptoName, this.keyLength, this.saltLength, this.nonceLength] = [cryptoName, keyLength, saltLength, nonceLength];
this.cryptoKeyIV = CryptoTools.generateKeyIVByPassword(password, this.keyLength, 16);
}
public encryptData(data: Buffer): Buffer {
let salt = null;
if (this.cipherKey === null) {
salt = crypto.randomBytes(this.saltLength);
this.cipherKey = HKDF("sha1", salt, this.cryptoKeyIV.key, INFO_STR, this.keyLength);
}
const chunks = getRandomChunks(data, MIN_CHUNK_SPLIT_LEN, MAX_CHUNK_SPLIT_LEN).map((chunk) => {
const dataLen = numberToBuffer(chunk.length);
const [encLen, lenTag] = this.encrypt(dataLen);
const [encData, dataTag] = this.encrypt(chunk);
return Buffer.concat([encLen, lenTag, encData, dataTag]);
});
if (salt) {
return Buffer.concat([salt, ...chunks]);
} else {
return Buffer.concat(chunks);
}
}
public decryptData(data?: Buffer): Buffer {
if (data) {
this.dataCache = Buffer.concat([this.dataCache, data]);
}
if (this.decipherKey === null) {
if (this.dataCache.length < this.saltLength) {
return null;
}
const salt = this.dataCache.slice(0, this.saltLength);
this.decipherKey = HKDF("sha1", salt, this.cryptoKeyIV.key, INFO_STR, this.keyLength);
this.dataCache = this.dataCache.slice(this.saltLength);
return this.decryptData();
}
let decryptedData: Buffer = Buffer.allocUnsafe(0);
while (true) {
if (this.dataCache.length < MIN_CHUNK_LEN) {
return (decryptedData.length === 0 ? null : decryptedData);
}
/**
*
* +---------+-------------+----------------+--------------+
* | DataLen | DataLen_TAG | Data | Data_TAG |
* +---------+-------------+----------------+--------------+
* | 2 | Fixed | Variable | Fixed |
* +---------+-------------+----------------+--------------+
*
*/
const dataLength: number = this.getDataLength(this.dataCache);
if (dataLength == null) {
return (decryptedData.length === 0 ? null : decryptedData);
}
const fullChunkSize: number = 2 + TAG_SIZE + dataLength + TAG_SIZE;
if (this.dataCache.length < fullChunkSize) {
this.rollbackDecipherNonce();
return (decryptedData.length === 0 ? null : decryptedData);
}
if (this.dataCache.length === fullChunkSize) {
decryptedData = Buffer.concat([decryptedData, this.decryptChunk(this.dataCache)]);
this.dataCache = Buffer.allocUnsafe(0);
return (decryptedData.length === 0 ? null : decryptedData);
}
if (this.dataCache.length > fullChunkSize) {
decryptedData = Buffer.concat([decryptedData, this.decryptChunk(this.dataCache.slice(0, fullChunkSize))]);
this.dataCache = this.dataCache.slice(fullChunkSize);
}
}
}
private decryptChunk(chunk: Buffer): Buffer {
// verify Data, Data_TAG
const [encData, dataTag] = [chunk.slice(2 + TAG_SIZE, -TAG_SIZE), chunk.slice(-TAG_SIZE)];
const data = this.decrypt(encData, dataTag);
return data;
}
private getDataLength(data: Buffer): number {
const encLen: Buffer = this.dataCache.slice(0, 2);
const lenTag: Buffer = this.dataCache.slice(2, 2 + TAG_SIZE);
const dataLengthBuffer: Buffer = this.decrypt(encLen, lenTag);
if (dataLengthBuffer === null) {
return null;
}
const dataLength = dataLengthBuffer.readUInt16BE(0);
if (dataLength > MAX_CHUNK_SPLIT_LEN) {
return null;
}
return dataLength;
}
private encrypt(data: Buffer): [Buffer, Buffer] {
const nonce = numberToBuffer(this.cipherNonce, this.nonceLength, false);
const cipher: crypto.Cipher = crypto.createCipheriv(this.cryptoName, this.cipherKey, nonce);
const ciphertext = Buffer.concat([cipher.update(data), cipher.final()]);
const tag = cipher.getAuthTag();
this.cipherNonce++;
return [ciphertext, tag];
}
private decrypt(data: Buffer, tag: any): Buffer {
const nonce = numberToBuffer(this.decipherNonce, this.nonceLength, false);
const decipher = crypto.createDecipheriv(this.cryptoName, this.decipherKey, nonce);
decipher.setAuthTag(tag);
const plaintext = Buffer.concat([decipher.update(data), decipher.final()]);
this.decipherNonce++;
return plaintext;
}
private rollbackDecipherNonce() {
if (this.decipherNonce > 0) {
this.decipherNonce--;
}
}
// tslint:disable-next-line:member-ordering
public encryptDataWithoutStream(data: Buffer): Buffer {
const salt: Buffer = crypto.randomBytes(this.saltLength);
const cipherKey: Buffer = HKDF("sha1", salt, this.cryptoKeyIV.key, INFO_STR, this.keyLength);
const nonce = numberToBuffer(0, this.nonceLength, false);
const cipher: crypto.Cipher = crypto.createCipheriv(this.cryptoName, cipherKey, nonce);
const ciphertext = Buffer.concat([cipher.update(data), cipher.final()]);
const tag = cipher.getAuthTag();
return Buffer.concat([salt, ciphertext, tag]);
}
// tslint:disable-next-line:member-ordering
public decryptDataWithoutStream(data: Buffer): Buffer {
if (data.length < this.saltLength) {
throw new Error("Too short salt.");
}
const salt = data.slice(0, this.saltLength);
const decipherKey = HKDF("sha1", salt, this.cryptoKeyIV.key, INFO_STR, this.keyLength);
if (data.length < this.saltLength + TAG_SIZE + 1) {
throw new Error("Too short verify data.");
}
const [encData, dataTag] = [data.slice(this.saltLength, -TAG_SIZE), data.slice(-TAG_SIZE)];
const nonce = numberToBuffer(0, this.nonceLength, false);
const decipher = crypto.createDecipheriv(this.cryptoName, decipherKey, nonce);
decipher.setAuthTag(dataTag);
return Buffer.concat([decipher.update(encData), decipher.final()]);
}
} | the_stack |
import { Component, Output, OnInit, EventEmitter, Input, ChangeDetectorRef, OnDestroy } from "@angular/core";
import { IslDataService } from "../services/isl-data.service";
import { DygraphService } from "../services/dygraph.service";
import * as _moment from 'moment';
declare var moment: any;
declare var Dygraph :any;
@Component({
selector: "app-dygraph",
templateUrl: "./dygraph.component.html",
styleUrls: ["./dygraph.component.css"]
})
export class DygraphComponent implements OnInit, OnDestroy {
@Output() zoomChange = new EventEmitter();
// @Input() dataObj: any;
// @Input() graphAPIFlag: boolean = false;
dataObj: any;
graphAPIFlag: boolean = false;
message: {};
data = [];
highestYaXis = null;
labels: any;
options : any = Object.assign({}, {
width: "auto",
chartHeight:"380",
legend: "onmouseover",
noDataLabel:"Please wait",
});
jsonResponse: any;
startDate: any;
endDate: any;
timezone: any;
frequency: any;
numOperator: number;
count: number = 0;
objectCount: number = 0;
optionsObject = {};
graphDataOptions: any;
dateMessage:string;
constructor(
private islDataService: IslDataService,
private dygraphService: DygraphService,
private cdr: ChangeDetectorRef
) {
}
constructGraphData(data, jsonResponse, startDate, endDate, timezone) {
this.numOperator = 0;
var metric1 = "";
var metric2 = "";
var direction1 = "";
var direction2 = "";
var labels = ["Time", "X", "Y"];
var graphData = [];
if (typeof startDate !== "undefined" && startDate != null) {
var dat = new Date(startDate);
var startTime = dat.getTime();
var usedDate = new Date();
if (typeof timezone !== "undefined" && timezone == "UTC") {
startTime = startTime - usedDate.getTimezoneOffset() * 60 * 1000;
}
var arr = [new Date(startTime), null, null];
graphData.push(arr);
}
if (!jsonResponse) {
var getValue = typeof data[0] !== "undefined" ? data[0].dps : {};
var fDps = [];
var rDps = [];
metric1 = typeof data[0] !== "undefined" ? data[0].metric : "";
if (data.length == 2) {
var getVal = typeof data[1] !== "undefined" ? data[1].dps : {};
rDps = Object.keys(getVal);
metric2 = data[1].metric;
if (data[1].tags.direction) {
metric2 = data[1].metric + "(" + data[1].tags.direction + ")";
}
if (data[0].tags.direction) {
metric1 = data[0].metric + "(" + data[0].tags.direction + ")";
}
}
fDps = Object.keys(getValue);
var graphDps = fDps.concat(rDps);
graphDps.sort();
graphDps = graphDps.filter((v, i, a) => a.indexOf(v) === i);
if (graphDps.length <= 0 ) {
metric1 = "F";
metric2 = "R";
} else {
for(var index=0;index < graphDps.length; index++){
let i = graphDps[index];
this.numOperator = parseInt(i);
if (getValue[i] == null || typeof getValue[i] == 'undefined') {
getValue[i] = null;
}else if(getValue[i] < 0){
getValue[i]=0;
}
var temparr = [];
temparr[0] = new Date(Number(this.numOperator * 1000));
temparr[1] = getValue[i];
if (data.length == 2) {
if (getVal[i] == null || typeof getVal[i] == 'undefined') {
getVal[i]= null;
}else if(getVal[i] < 0){
getVal[i]=0;
}
temparr[2] = getVal[i];
}
graphData.push(temparr);
this.numOperator++;
}
}
if (metric1 && metric2) {
labels = ["Time", metric1, metric2];
} else if (metric1) {
labels = ["Time", metric1];
} else {
labels = ["Time", metric2];
}
} else {
metric1 = "F";
metric2 = "R";
labels = ["Time", metric1, metric2];
}
if (typeof endDate !== "undefined" && endDate != null) {
var dat = new Date(endDate);
var lastTime = dat.getTime();
var usedDate =
graphData && graphData.length
? new Date(graphData[graphData.length - 1][0])
: new Date();
if (typeof timezone !== "undefined" && timezone == "UTC") {
lastTime = lastTime - usedDate.getTimezoneOffset() * 60 * 1000;
}
var arr = [new Date(lastTime), null, null];
graphData.push(arr);
//graphData.shift();
}
return { data: graphData, labels: labels };
}
ngOnInit() {
this.islDataService.currentMessage.subscribe(message => {
this.message = message;
if (this.count >= 1) {
this.options = Object.assign({}, {
width: "auto",
chartHeight:"380",
legend: "onmouseover",
noDataLabel:"Please wait",
});
this.drawGraphCall(message);
}
this.count++;
});
this.islDataService.currentOptionsObject.subscribe(message => {
this.optionsObject = message;
this.graphDataOptions = message;
if (this.objectCount >= 1) {
this.options = Object.assign({}, {
width: "auto",
chartHeight:"380",
legend: "onmouseover",
noDataLabel:"Please wait",
});
this.drawGraphCall(message);
}
this.objectCount++;
});
this.islDataService.IslFlowGraph.subscribe(message => {
this.message = message;
if (this.count >= 1) {
this.options = Object.assign({}, {
width: "auto",
chartHeight:"380",
legend: "onmouseover",
noDataLabel:"Please wait",
});
this.plotISLFlowGraph(message);
}
this.count++;
});
this.islDataService.IslFlowStackedGraph.subscribe(message => {
this.message = message;
if (this.count >= 1) {
this.options = Object.assign({}, {
width: "auto",
chartHeight:"380",
legend: "onmouseover",
noDataLabel:"Please wait",
});
this.plotISLStackedFlowGraph(message);
}
this.count++;
});
this.dygraphService.flowGraph.subscribe(data => {
this.options = Object.assign({}, {
width: "auto",
chartHeight:"380",
legend: "onmouseover",
noDataLabel:"Please wait",
});
this.plotFlowGraph(
data.data,
data.startDate,
data.endDate,
data.timezone
);
try {
this.cdr.detectChanges();
} catch (err) {}
});
this.dygraphService.meterGraph.subscribe(data => {
this.options = Object.assign({}, {
width: "auto",
chartHeight:"380",
legend: "onmouseover",
noDataLabel:"Please wait",
});
this.plotMeterGraph(
data.data,
data.startDate,
data.endDate,
data.timezone);
try {
this.cdr.detectChanges();
} catch (err) {}
})
}
drawGraphCall(dataObj) {
this.timezone = dataObj.timezone;
this.jsonResponse = undefined;
let processedResponse = this.dygraphService.constructGraphData(
dataObj.data,
this.jsonResponse,
dataObj.startDate,
dataObj.endDate,
dataObj.timezone
);
this.data = processedResponse.data;
this.labels = processedResponse.labels;
if (this.timezone == "UTC") {
this.options = Object.assign(this.options, {
labels: this.labels,
drawPoints: false,
animatedZooms: true,
labelsUTC: true,
colors: ["#1C227C","#A1CD24"] ,
legend: "onmouseover",
valueRange:[0,null],
connectSeparatedPoints:true,
legendFormatter:this.dygraphService.legendFormatter,
zoomCallback: this.zoomCallbackHandler
});
}else{
this.options = Object.assign(this.options, {
labels: this.labels,
drawPoints: false,
animatedZooms: true,
labelsUTC: false,
colors: ["#1C227C","#A1CD24"],
legend: "onmouseover",
valueRange:[0,null],
connectSeparatedPoints:true,
legendFormatter:this.dygraphService.legendFormatter,
zoomCallback: this.zoomCallbackHandler
});
}
}
plotISLFlowGraph(dataObj) {
this.timezone = dataObj.timezone;
this.jsonResponse = undefined;
this.labels = dataObj.labels;
this.data = dataObj.data;
if(this.timezone == "UTC") {
this.options = Object.assign(this.options, {
labels: this.labels,
drawPoints: false,
animatedZooms: true,
labelsUTC: true,
series: dataObj.series,
legend: "onmouseover",
valueRange:[0,null],
connectSeparatedPoints:true,
legendFormatter:this.dygraphService.legendFormatter,
zoomCallback: this.zoomCallbackHandler
});
}else{
this.options = Object.assign(this.options, {
labels: this.labels,
drawPoints: false,
animatedZooms: true,
labelsUTC: false,
series: dataObj.series,
legend: "onmouseover",
valueRange:[0,null],
connectSeparatedPoints:true,
legendFormatter:this.dygraphService.legendFormatter,
zoomCallback: this.zoomCallbackHandler
});
}
}
plotISLStackedFlowGraph(dataObj) {
this.timezone = dataObj.timezone;
this.jsonResponse = undefined;
this.labels = dataObj.labels;
this.data = dataObj.data;
if(this.timezone == "UTC") {
this.options = Object.assign(this.options, {
labels: this.labels,
drawPoints: false,
animatedZooms: true,
labelsUTC: true,
series: dataObj.series,
legend: "onmouseover",
stackedGraph: true,
valueRange:[0,null],
connectSeparatedPoints:true,
legendFormatter:this.dygraphService.legendFormatter,
zoomCallback: this.zoomCallbackHandler,
axes: {
x: {
drawGrid: false
}
}
});
}else{
this.options = Object.assign(this.options, {
labels: this.labels,
drawPoints: false,
animatedZooms: true,
labelsUTC: false,
series: dataObj.series,
legend: "onmouseover",
stackedGraph: true,
valueRange:[0,null],
connectSeparatedPoints:true,
legendFormatter:this.dygraphService.legendFormatter,
zoomCallback: this.zoomCallbackHandler,
axes: {
x: {
drawGrid: false
}
}
});
}
}
zoomCallbackHandler = (minX, maxX, yRanges) =>{
this.zoomChange.emit({ minX:minX, maxX:maxX, yRanges:yRanges});
}
/** Start : Flow Graphs */
plotMeterGraph(data, startDate, endDate, timezone){
var graph_data = this.dygraphService.computeMeterGraphData(
data,
startDate,
endDate,
timezone,
);
var graphData = graph_data["data"];
var labels = graph_data["labels"];
var series = {};
var colors = graph_data["color"];
if (labels && labels.length) {
for (var k = 0; k < labels.length; k++) {
if (k != 0) {
series[labels[k]] = { color: colors[k - 1] };
}
}
}
this.data = graphData;
if (timezone == "UTC") {
this.options = Object.assign(this.options,{
labels: labels,
labelsUTC: true,
series: series,
legend: "onmouseover",
connectSeparatedPoints:true,
legendFormatter:this.dygraphService.legendFormatter,
zoomCallback: this.zoomCallbackHandler
});
} else {
this.options = Object.assign(this.options,{
labels: labels,
series: series,
labelsUTC: false,
legend: "onmouseover",
connectSeparatedPoints:true,
legendFormatter:this.dygraphService.legendFormatter,
zoomCallback: this.zoomCallbackHandler
});
}
}
plotFlowGraph(data, startDate, endDate, timezone) {
let graphData = this.dygraphService.constructGraphData(
data,
undefined,
startDate,
endDate,
timezone
);
try{
this.data = graphData["data"];
this.labels = graphData["labels"];
if (timezone == "UTC") {
this.options = Object.assign(this.options,{
labels: this.labels,
animatedZooms: true,
labelsUTC: true,
colors: ["#1C227C", "#A1CD24"],
connectSeparatedPoints:true,
legendFormatter:this.dygraphService.legendFormatter,
zoomCallback: this.zoomCallbackHandler
});
} else {
this.options = Object.assign(this.options,{
labels: this.labels,
animatedZooms: true,
labelsUTC: false,
colors: ["#1C227C", "#A1CD24"],
connectSeparatedPoints:true,
legendFormatter:this.dygraphService.legendFormatter,
zoomCallback: this.zoomCallbackHandler
});
}
}catch(err){}
}
/** End : Flow Graph Path */
ngOnDestroy(){
this.cdr.detach();
}
} | the_stack |
import {
_,
IsServerSideGroupOpenByDefaultParams,
RowBounds,
Autowired,
Bean,
BeanStub,
Column,
ColumnModel,
PostConstruct,
RowNode,
ValueService,
NumberSequence,
Beans
} from "@ag-grid-community/core";
import { NodeManager } from "../nodeManager";
@Bean('ssrmBlockUtils')
export class BlockUtils extends BeanStub {
@Autowired('valueService') private valueService: ValueService;
@Autowired('columnModel') private columnModel: ColumnModel;
@Autowired('ssrmNodeManager') private nodeManager: NodeManager;
@Autowired('beans') private beans: Beans;
private rowHeight: number;
private usingTreeData: boolean;
private usingMasterDetail: boolean;
@PostConstruct
private postConstruct(): void {
this.rowHeight = this.gridOptionsWrapper.getRowHeightAsNumber();
this.usingTreeData = this.gridOptionsWrapper.isTreeData();
this.usingMasterDetail = this.gridOptionsWrapper.isMasterDetail();
}
public createRowNode(params: {group: boolean, leafGroup: boolean, level: number,
parent: RowNode, field: string, rowGroupColumn: Column}): RowNode {
const rowNode = new RowNode(this.beans);
rowNode.setRowHeight(this.rowHeight);
rowNode.group = params.group;
rowNode.leafGroup = params.leafGroup;
rowNode.level = params.level;
rowNode.uiLevel = params.level;
rowNode.parent = params.parent;
// stub gets set to true here, and then false when this rowNode gets it's data
rowNode.stub = true;
if (rowNode.group) {
rowNode.expanded = false;
rowNode.field = params.field;
rowNode.rowGroupColumn = params.rowGroupColumn;
}
return rowNode;
}
public destroyRowNodes(rowNodes: RowNode[]): void {
if (rowNodes) {
rowNodes.forEach(this.destroyRowNode.bind(this));
}
}
public destroyRowNode(rowNode: RowNode): void {
if (rowNode.childStore) {
this.destroyBean(rowNode.childStore);
rowNode.childStore = null;
}
// this is needed, so row render knows to fade out the row, otherwise it
// sees row top is present, and thinks the row should be shown. maybe
// rowNode should have a flag on whether it is visible???
rowNode.clearRowTopAndRowIndex();
if (rowNode.id != null) {
this.nodeManager.removeNode(rowNode);
}
}
public setDataIntoRowNode(rowNode: RowNode, data: any, defaultId: string): void {
rowNode.stub = false;
if (_.exists(data)) {
rowNode.setDataAndId(data, defaultId);
if (this.usingTreeData) {
const isGroupFunc = this.gridOptionsWrapper.getIsServerSideGroupFunc();
const getKeyFunc = this.gridOptionsWrapper.getServerSideGroupKeyFunc();
if (isGroupFunc != null) {
rowNode.group = isGroupFunc(rowNode.data);
if (rowNode.group && getKeyFunc != null) {
rowNode.key = getKeyFunc(rowNode.data);
}
}
} else if (rowNode.group) {
rowNode.key = this.valueService.getValue(rowNode.rowGroupColumn!, rowNode);
if (rowNode.key === null || rowNode.key === undefined) {
_.doOnce(() => {
console.warn(`null and undefined values are not allowed for server side row model keys`);
if (rowNode.rowGroupColumn) {
console.warn(`column = ${rowNode.rowGroupColumn.getId()}`);
}
console.warn(`data is `, rowNode.data);
}, 'ServerSideBlock-CannotHaveNullOrUndefinedForKey');
}
} else if (this.usingMasterDetail) {
const isMasterFunc = this.gridOptionsWrapper.getIsRowMasterFunc();
if (isMasterFunc != null) {
rowNode.master = isMasterFunc(rowNode.data);
} else {
rowNode.master = true;
}
}
} else {
rowNode.setDataAndId(undefined, undefined);
rowNode.key = null;
}
if (this.usingTreeData || rowNode.group) {
this.setGroupDataIntoRowNode(rowNode);
this.setChildCountIntoRowNode(rowNode);
}
// this needs to be done AFTER setGroupDataIntoRowNode(), as the height can depend on the group data
// getting set, if it's a group node and colDef.autoHeight=true
if (_.exists(data)) {
rowNode.setRowHeight(this.gridOptionsWrapper.getRowHeightForNode(rowNode).height);
}
}
private setChildCountIntoRowNode(rowNode: RowNode): void {
const getChildCount = this.gridOptionsWrapper.getChildCountFunc();
if (getChildCount) {
rowNode.allChildrenCount = getChildCount(rowNode.data);
}
}
private setGroupDataIntoRowNode(rowNode: RowNode): void {
const groupDisplayCols: Column[] = this.columnModel.getGroupDisplayColumns();
const usingTreeData = this.gridOptionsWrapper.isTreeData();
groupDisplayCols.forEach(col => {
if (rowNode.groupData == null) {
rowNode.groupData = {};
}
if (usingTreeData) {
rowNode.groupData[col.getColId()] = rowNode.key;
} else if (col.isRowGroupDisplayed(rowNode.rowGroupColumn!.getId())) {
const groupValue = this.valueService.getValue(rowNode.rowGroupColumn!, rowNode);
rowNode.groupData[col.getColId()] = groupValue;
}
});
}
public clearDisplayIndex(rowNode: RowNode): void {
rowNode.clearRowTopAndRowIndex();
const hasChildStore = rowNode.group && _.exists(rowNode.childStore);
if (hasChildStore) {
const childStore = rowNode.childStore;
childStore!.clearDisplayIndexes();
}
const hasDetailNode = rowNode.master && rowNode.detailNode;
if (hasDetailNode) {
rowNode.detailNode.clearRowTopAndRowIndex();
}
}
public setDisplayIndex(rowNode: RowNode, displayIndexSeq: NumberSequence, nextRowTop: { value: number }): void {
// set this row
rowNode.setRowIndex(displayIndexSeq.next());
rowNode.setRowTop(nextRowTop.value);
nextRowTop.value += rowNode.rowHeight!;
// set child for master / detail
const hasDetailRow = rowNode.master;
if (hasDetailRow) {
if (rowNode.expanded && rowNode.detailNode) {
rowNode.detailNode.setRowIndex(displayIndexSeq.next());
rowNode.detailNode.setRowTop(nextRowTop.value);
nextRowTop.value += rowNode.detailNode.rowHeight!;
} else if (rowNode.detailNode) {
rowNode.detailNode.clearRowTopAndRowIndex();
}
}
// set children for SSRM child rows
const hasChildStore = rowNode.group && _.exists(rowNode.childStore);
if (hasChildStore) {
const childStore = rowNode.childStore;
if (rowNode.expanded) {
childStore!.setDisplayIndexes(displayIndexSeq, nextRowTop);
} else {
// we need to clear the row tops, as the row renderer depends on
// this to know if the row should be faded out
childStore!.clearDisplayIndexes();
}
}
}
public binarySearchForDisplayIndex(displayRowIndex: number, rowNodes: RowNode[]): RowNode | undefined {
let bottomPointer = 0;
let topPointer = rowNodes.length - 1;
if (_.missing(topPointer) || _.missing(bottomPointer)) {
console.warn(`ag-grid: error: topPointer = ${topPointer}, bottomPointer = ${bottomPointer}`);
return undefined;
}
while (true) {
const midPointer = Math.floor((bottomPointer + topPointer) / 2);
const currentRowNode = rowNodes[midPointer];
// first check current row for index
if (currentRowNode.rowIndex === displayRowIndex) {
return currentRowNode;
}
// then check if current row contains a detail row with the index
const expandedMasterRow = currentRowNode.master && currentRowNode.expanded;
if (expandedMasterRow && currentRowNode.detailNode.rowIndex === displayRowIndex) {
return currentRowNode.detailNode;
}
// then check if child cache contains index
const childStore = currentRowNode.childStore;
if (currentRowNode.expanded && childStore && childStore.isDisplayIndexInStore(displayRowIndex)) {
return childStore.getRowUsingDisplayIndex(displayRowIndex);
}
// otherwise adjust pointers to continue searching for index
if (currentRowNode.rowIndex! < displayRowIndex) {
bottomPointer = midPointer + 1;
} else if (currentRowNode.rowIndex! > displayRowIndex) {
topPointer = midPointer - 1;
} else {
console.warn(`AG Grid: error: unable to locate rowIndex = ${displayRowIndex} in cache`);
return undefined;
}
}
}
public extractRowBounds(rowNode: RowNode, index: number): RowBounds | undefined {
const extractRowBounds = (currentRowNode: RowNode): RowBounds => ({
rowHeight: currentRowNode.rowHeight!,
rowTop: currentRowNode.rowTop!
});
if (rowNode.rowIndex === index) {
return extractRowBounds(rowNode);
}
if (rowNode.group && rowNode.expanded && _.exists(rowNode.childStore)) {
const childStore = rowNode.childStore;
if (childStore.isDisplayIndexInStore(index)) {
return childStore.getRowBounds(index)!;
}
} else if (rowNode.master && rowNode.expanded && _.exists(rowNode.detailNode)) {
if (rowNode.detailNode.rowIndex === index) {
return extractRowBounds(rowNode.detailNode);
}
}
}
public getIndexAtPixel(rowNode: RowNode, pixel: number): number | null {
// first check if pixel is in range of current row
if (rowNode.isPixelInRange(pixel)) {
return rowNode.rowIndex;
}
// then check if current row contains a detail row with pixel in range
const expandedMasterRow = rowNode.master && rowNode.expanded;
if (expandedMasterRow && rowNode.detailNode.isPixelInRange(pixel)) {
return rowNode.detailNode.rowIndex;
}
// then check if it's a group row with a child cache with pixel in range
if (rowNode.group && rowNode.expanded && _.exists(rowNode.childStore)) {
const childStore = rowNode.childStore;
if (childStore.isPixelInRange(pixel)) {
return childStore.getRowIndexAtPixel(pixel);
}
}
return null
// pixel is not within this row node or it's children / detail, so return undefined
}
public createNodeIdPrefix(parentRowNode: RowNode): string | undefined {
const parts: string[] = [];
let rowNode : RowNode | null = parentRowNode;
// pull keys from all parent nodes, but do not include the root node
while (rowNode && rowNode.level >= 0) {
parts.push(rowNode.key!);
rowNode = rowNode.parent;
}
if (parts.length > 0) {
return parts.reverse().join('-');
}
// no prefix, so node id's are left as they are
return undefined;
}
public checkOpenByDefault(rowNode: RowNode): void {
if (!rowNode.isExpandable()) { return; }
const userFunc = this.gridOptionsWrapper.getIsServerSideGroupOpenByDefaultFunc();
if (!userFunc) { return; }
const params: IsServerSideGroupOpenByDefaultParams = {
data: rowNode.data,
rowNode
};
const userFuncRes = userFunc(params);
if (userFuncRes) {
// we do this in a timeout, so that we don't expand a row node while in the middle
// of setting up rows, setting up rows is complex enough without another chunk of work
// getting added to the call stack. this is also helpful as openByDefault may or may
// not happen (so makes setting up rows more deterministic by expands never happening)
// and also checkOpenByDefault is shard with both store types, so easier control how it
// impacts things by keeping it in new VM turn.
window.setTimeout(() => rowNode.setExpanded(true), 0);
}
}
} | the_stack |
import { formatAndWriteItem, formatAndWriteList } from '../format'
import { IOFormat } from '../io-util'
import * as output from '../output'
import * as outputBuilder from '../output-builder'
import { buildMockCommand } from './test-lib/mock-command'
import { SimpleType } from './test-lib/simple-type'
describe('format', () => {
const item = { str: 'string', num: 5 }
const list = [item]
const command = {
...buildMockCommand(),
flags: {
output: 'output.yaml',
},
}
const outputFormatter: jest.Mock<string, [data: unknown]> = jest.fn().mockReturnValue('output')
const buildOutputFormatterSpy = jest.spyOn(outputBuilder, 'buildOutputFormatter').mockReturnValue(outputFormatter)
const writeOutputSpy = jest.spyOn(output, 'writeOutput').mockResolvedValue()
afterEach(() => {
jest.clearAllMocks()
})
describe('formatAndWriteItem', () => {
const itemTableFormatterSpy = jest.spyOn(output, 'itemTableFormatter')
it('uses tableFieldDefinitions when specified', async () => {
const config = {
tableFieldDefinitions: [],
}
const commonFormatter = jest.fn()
itemTableFormatterSpy.mockReturnValue(commonFormatter)
await formatAndWriteItem(command, config, item, IOFormat.COMMON)
expect(itemTableFormatterSpy).toHaveBeenCalledTimes(1)
expect(itemTableFormatterSpy).toHaveBeenCalledWith(command.tableGenerator, config.tableFieldDefinitions)
expect(buildOutputFormatterSpy).toHaveBeenCalledTimes(1)
expect(buildOutputFormatterSpy).toHaveBeenCalledWith(command, IOFormat.COMMON, commonFormatter)
expect(outputFormatter).toHaveBeenCalledTimes(1)
expect(outputFormatter).toHaveBeenCalledWith(item)
expect(writeOutputSpy).toHaveBeenCalledTimes(1)
expect(writeOutputSpy).toHaveBeenCalledWith('output', 'output.yaml')
})
it('uses buildTableOutput when specified', async () => {
const config = {
buildTableOutput: jest.fn(),
}
await formatAndWriteItem<SimpleType>(command, config, item, IOFormat.JSON)
expect(itemTableFormatterSpy).toHaveBeenCalledTimes(0)
expect(buildOutputFormatterSpy).toHaveBeenCalledTimes(1)
expect(buildOutputFormatterSpy).toHaveBeenCalledWith(command, IOFormat.JSON, expect.anything())
expect(outputFormatter).toHaveBeenCalledTimes(1)
expect(outputFormatter).toHaveBeenCalledWith(item)
expect(writeOutputSpy).toHaveBeenCalledTimes(1)
expect(writeOutputSpy).toHaveBeenCalledWith('output', 'output.yaml')
// Call the OutputFormatter that was build to ensure it uses `buildTableOutput`
const commonFormatter: output.OutputFormatter<SimpleType> = buildOutputFormatterSpy.mock.calls[0][2] as never
config.buildTableOutput.mockReturnValue('common output')
expect(commonFormatter(item)).toBe('common output')
expect(config.buildTableOutput).toHaveBeenCalledTimes(1)
})
it('uses buildTableOutput when both specified', async () => {
const config = {
tableFieldDefinitions: [],
buildTableOutput: jest.fn(),
}
await formatAndWriteItem<SimpleType>(command, config, item, IOFormat.JSON)
expect(itemTableFormatterSpy).toHaveBeenCalledTimes(0)
expect(buildOutputFormatterSpy).toHaveBeenCalledTimes(1)
expect(buildOutputFormatterSpy).toHaveBeenCalledWith(command, IOFormat.JSON, expect.anything())
expect(outputFormatter).toHaveBeenCalledTimes(1)
expect(outputFormatter).toHaveBeenCalledWith(item)
expect(writeOutputSpy).toHaveBeenCalledTimes(1)
expect(writeOutputSpy).toHaveBeenCalledWith('output', 'output.yaml')
// Call the OutputFormatter that was build to ensure it uses `buildTableOutput`
const commonFormatter: output.OutputFormatter<SimpleType> = buildOutputFormatterSpy.mock.calls[0][2] as never
config.buildTableOutput.mockReturnValue('common output')
expect(commonFormatter(item)).toBe('common output')
expect(config.buildTableOutput).toHaveBeenCalledTimes(1)
})
})
describe('formatAndWriteList', () => {
const listTableFormatterSpy= jest.spyOn(output, 'listTableFormatter')
it('returns no items found when none found', async () => {
const config = {
buildListTableOutput: jest.fn(),
}
await formatAndWriteList<SimpleType>(command, config, [], true)
expect(listTableFormatterSpy).toHaveBeenCalledTimes(0)
expect(buildOutputFormatterSpy).toHaveBeenCalledTimes(1)
expect(buildOutputFormatterSpy).toHaveBeenCalledWith(command, undefined, expect.anything())
expect(outputFormatter).toHaveBeenCalledTimes(1)
expect(outputFormatter).toHaveBeenCalledWith([])
expect(writeOutputSpy).toHaveBeenCalledTimes(1)
expect(writeOutputSpy).toHaveBeenCalledWith('output', 'output.yaml')
// Call the OutputFormatter that was build to ensure it uses `buildTableOutput`
const commonFormatter: output.OutputFormatter<SimpleType[]> = buildOutputFormatterSpy.mock.calls[0][2] as never
expect(commonFormatter(list)).toBe('no items found')
})
it('returns no items found when none found; name specified', async () => {
const config = {
buildListTableOutput: jest.fn(),
itemName: 'thing',
}
await formatAndWriteList<SimpleType>(command, config, [], true)
expect(listTableFormatterSpy).toHaveBeenCalledTimes(0)
expect(buildOutputFormatterSpy).toHaveBeenCalledTimes(1)
expect(buildOutputFormatterSpy).toHaveBeenCalledWith(command, undefined, expect.anything())
expect(outputFormatter).toHaveBeenCalledTimes(1)
expect(outputFormatter).toHaveBeenCalledWith([])
expect(writeOutputSpy).toHaveBeenCalledTimes(1)
expect(writeOutputSpy).toHaveBeenCalledWith('output', 'output.yaml')
// Call the OutputFormatter that was build to ensure it uses `buildTableOutput`
const commonFormatter: output.OutputFormatter<SimpleType[]> = buildOutputFormatterSpy.mock.calls[0][2] as never
expect(commonFormatter(list)).toBe('no things found')
})
it('returns no items found when none found; plural name specified', async () => {
const config = {
buildListTableOutput: jest.fn(),
pluralItemName: 'candies',
}
await formatAndWriteList<SimpleType>(command, config, [], true)
expect(listTableFormatterSpy).toHaveBeenCalledTimes(0)
expect(buildOutputFormatterSpy).toHaveBeenCalledTimes(1)
expect(buildOutputFormatterSpy).toHaveBeenCalledWith(command, undefined, expect.anything())
expect(outputFormatter).toHaveBeenCalledTimes(1)
expect(outputFormatter).toHaveBeenCalledWith([])
expect(writeOutputSpy).toHaveBeenCalledTimes(1)
expect(writeOutputSpy).toHaveBeenCalledWith('output', 'output.yaml')
// Call the OutputFormatter that was build to ensure it uses `buildTableOutput`
const commonFormatter: output.OutputFormatter<SimpleType[]> = buildOutputFormatterSpy.mock.calls[0][2] as never
expect(commonFormatter(list)).toBe('no candies found')
})
it('uses listTableFieldDefinitions when specified', async () => {
const config = {
listTableFieldDefinitions: [],
}
const commonFormatter = jest.fn()
listTableFormatterSpy.mockReturnValue(commonFormatter)
await formatAndWriteList(command, config, list)
expect(listTableFormatterSpy).toHaveBeenCalledTimes(1)
expect(listTableFormatterSpy).toHaveBeenCalledWith(command.tableGenerator, config.listTableFieldDefinitions, false)
expect(buildOutputFormatterSpy).toHaveBeenCalledTimes(1)
expect(buildOutputFormatterSpy).toHaveBeenCalledWith(command, undefined, commonFormatter)
expect(outputFormatter).toHaveBeenCalledTimes(1)
expect(outputFormatter).toHaveBeenCalledWith(list)
expect(writeOutputSpy).toHaveBeenCalledTimes(1)
expect(writeOutputSpy).toHaveBeenCalledWith('output', 'output.yaml')
})
it('uses buildListTableOutput when specified', async () => {
const config = {
buildListTableOutput: jest.fn(),
}
await formatAndWriteList<SimpleType>(command, config, list, true)
expect(listTableFormatterSpy).toHaveBeenCalledTimes(0)
expect(buildOutputFormatterSpy).toHaveBeenCalledTimes(1)
expect(buildOutputFormatterSpy).toHaveBeenCalledWith(command, undefined, expect.anything())
expect(outputFormatter).toHaveBeenCalledTimes(1)
expect(outputFormatter).toHaveBeenCalledWith(list)
expect(writeOutputSpy).toHaveBeenCalledTimes(1)
expect(writeOutputSpy).toHaveBeenCalledWith('output', 'output.yaml')
// Call the OutputFormatter that was build to ensure it uses `buildTableOutput`
const commonFormatter: output.OutputFormatter<SimpleType[]> = buildOutputFormatterSpy.mock.calls[0][2] as never
config.buildListTableOutput.mockReturnValue('common output')
expect(commonFormatter(list)).toBe('common output')
expect(config.buildListTableOutput).toHaveBeenCalledTimes(1)
})
it('uses buildListTableOutput when both specified', async () => {
const config = {
listTableFieldDefinitions: [],
buildListTableOutput: jest.fn(),
}
await formatAndWriteList<SimpleType>(command, config, list, true)
expect(listTableFormatterSpy).toHaveBeenCalledTimes(0)
expect(buildOutputFormatterSpy).toHaveBeenCalledTimes(1)
expect(buildOutputFormatterSpy).toHaveBeenCalledWith(command, undefined, expect.anything())
expect(outputFormatter).toHaveBeenCalledTimes(1)
expect(outputFormatter).toHaveBeenCalledWith(list)
expect(writeOutputSpy).toHaveBeenCalledTimes(1)
expect(writeOutputSpy).toHaveBeenCalledWith('output', 'output.yaml')
// Call the OutputFormatter that was build to ensure it uses `buildTableOutput`
const commonFormatter: output.OutputFormatter<SimpleType[]> = buildOutputFormatterSpy.mock.calls[0][2] as never
config.buildListTableOutput.mockReturnValue('common output')
expect(commonFormatter(list)).toBe('common output')
expect(config.buildListTableOutput).toHaveBeenCalledTimes(1)
})
it('uses Sorting fields as a fallback', async () => {
const config = {
primaryKeyName: 'num',
sortKeyName: 'str',
}
const commonFormatter = jest.fn()
listTableFormatterSpy.mockReturnValue(commonFormatter)
await formatAndWriteList(command, config, list)
expect(listTableFormatterSpy).toHaveBeenCalledTimes(1)
expect(listTableFormatterSpy).toHaveBeenCalledWith(command.tableGenerator, ['str', 'num'], false)
expect(buildOutputFormatterSpy).toHaveBeenCalledTimes(1)
expect(buildOutputFormatterSpy).toHaveBeenCalledWith(command, undefined, commonFormatter)
expect(outputFormatter).toHaveBeenCalledTimes(1)
expect(outputFormatter).toHaveBeenCalledWith(list)
expect(writeOutputSpy).toHaveBeenCalledTimes(1)
expect(writeOutputSpy).toHaveBeenCalledWith('output', 'output.yaml')
})
it('writes common formatted output to stdout when forUserQuery specified', async () => {
const config = {
listTableFieldDefinitions: [],
}
const commonFormatter = jest.fn().mockReturnValue('common output')
listTableFormatterSpy.mockReturnValue(commonFormatter)
await formatAndWriteList(command, config, list, false, true)
expect(listTableFormatterSpy).toHaveBeenCalledTimes(1)
expect(listTableFormatterSpy).toHaveBeenCalledWith(command.tableGenerator, config.listTableFieldDefinitions, false)
expect(buildOutputFormatterSpy).toHaveBeenCalledTimes(0)
expect(outputFormatter).toHaveBeenCalledTimes(0)
expect(commonFormatter).toHaveBeenCalledTimes(1)
expect(commonFormatter).toHaveBeenCalledWith(list)
expect(writeOutputSpy).toHaveBeenCalledTimes(1)
expect(writeOutputSpy).toHaveBeenCalledWith('common output', undefined)
})
})
}) | the_stack |
module RongIMLib {
/**
* 消息基类
*/
export class BaseMessage {
_name = "BaseMessage";
_header: Header;
_headerCode: any;
lengthSize: any = 0;
constructor(arg: any) {
if (arg instanceof Header) {
this._header = arg;
} else {
this._header = new Header(arg, false, Qos.AT_MOST_ONCE, false);
}
}
read(In: any, length: number) {
this.readMessage(In, length);
}
write(Out: any): any {
var binaryHelper = new BinaryHelper();
var out = binaryHelper.convertStream(Out);
this._headerCode = this.getHeaderFlag();
out.write(this._headerCode);
this.writeMessage(out);
return out;
}
getHeaderFlag(): any {
return this._header.encode();
}
getLengthSize() {
return this.lengthSize;
}
toBytes() {
return this.write([]).getBytesArray();
}
isRetained() {
return this._header.retain;
}
setRetained(retain: any) {
this._header.retain = retain;
}
setQos(qos: any) {
this._header.qos = Object.prototype.toString.call(qos) == "[object Object]" ? qos : Qos[qos];
}
setDup(dup: boolean) {
this._header.dup = dup;
}
isDup() {
return this._header.dup;
}
getType() {
return this._header.type;
}
getQos() {
return this._header.qos;
}
messageLength() {
return 0;
}
writeMessage(out: any) { }
readMessage(In: any, length: number) { }
init(args: any) {
var valName: any, nana: any, me: { [s: string]: any; } = this;
for (nana in args) {
if (!args.hasOwnProperty(nana)) {
continue;
}
valName = nana.replace(/^\w/, function(x: any) {
var tt = x.charCodeAt(0);
return "set" + (tt >= 0x61 ? String.fromCharCode(tt & ~32) : x);
});
if (valName in me) {
if (nana == "status") {
me[valName](disconnectStatus[args[nana]] ? disconnectStatus[args[nana]] : args[nana]);
} else {
me[valName](args[nana]);
}
}
}
}
}
/**
*连接消息类型
*/
export class ConnectMessage extends BaseMessage {
_name: string = "ConnectMessage";
CONNECT_HEADER_SIZE = 12;
protocolId = "RCloud";
binaryHelper: BinaryHelper = new BinaryHelper();
protocolVersion = 3;
clientId: any;
keepAlive: any;
appId: any;
token: any;
cleanSession: any;
willTopic: any;
will: any;
willQos: any;
retainWill: any;
hasAppId: any;
hasToken: any;
hasWill: any;
constructor(header: RongIMLib.Header) {
super(arguments.length == 0 || arguments.length == 3 ? Type.CONNECT : arguments[0]);
switch (arguments.length) {
case 0:
case 1:
case 3:
if (!arguments[0] || arguments[0].length > 64) {
throw new Error("ConnectMessage:Client Id cannot be null and must be at most 64 characters long: " + arguments[0]);
}
this.clientId = arguments[0];
this.cleanSession = arguments[1];
this.keepAlive = arguments[2];
break;
}
}
messageLength(): number {
var payloadSize = this.binaryHelper.toMQttString(this.clientId).length;
payloadSize += this.binaryHelper.toMQttString(this.willTopic).length;
payloadSize += this.binaryHelper.toMQttString(this.will).length;
payloadSize += this.binaryHelper.toMQttString(this.appId).length;
payloadSize += this.binaryHelper.toMQttString(this.token).length;
return payloadSize + this.CONNECT_HEADER_SIZE;
}
readMessage(stream: any) {
this.protocolId = stream.readUTF();
this.protocolVersion = stream.readByte();
var cFlags = stream.readByte();
this.hasAppId = (cFlags & 128) > 0;
this.hasToken = (cFlags & 64) > 0;
this.retainWill = (cFlags & 32) > 0;
this.willQos = cFlags >> 3 & 3;
this.hasWill = (cFlags & 4) > 0;
this.cleanSession = (cFlags & 32) > 0;
this.keepAlive = stream.read() * 256 + stream.read();
this.clientId = stream.readUTF();
if (this.hasWill) {
this.willTopic = stream.readUTF();
this.will = stream.readUTF();
}
if (this.hasAppId) {
try {
this.appId = stream.readUTF();
} catch (ex) {
throw new Error(ex);
}
}
if (this.hasToken) {
try {
this.token = stream.readUTF();
} catch (ex) {
throw new Error(ex);
}
}
return stream;
}
writeMessage(out: any) {
var stream = this.binaryHelper.convertStream(out);
stream.writeUTF(this.protocolId);
stream.write(this.protocolVersion);
var flags = this.cleanSession ? 2 : 0;
flags |= this.hasWill ? 4 : 0;
flags |= this.willQos ? this.willQos >> 3 : 0;
flags |= this.retainWill ? 32 : 0;
flags |= this.hasToken ? 64 : 0;
flags |= this.hasAppId ? 128 : 0;
stream.write(flags);
stream.writeChar(this.keepAlive);
stream.writeUTF(this.clientId);
if (this.hasWill) {
stream.writeUTF(this.willTopic);
stream.writeUTF(this.will);
}
if (this.hasAppId) {
stream.writeUTF(this.appId);
}
if (this.hasToken) {
stream.writeUTF(this.token);
}
return stream;
}
}
/**
*连接应答类型
*/
export class ConnAckMessage extends BaseMessage {
_name: string = "ConnAckMessage";
status: any;
userId: string;
MESSAGE_LENGTH = 2;
timestrap: number;
binaryHelper: BinaryHelper = new BinaryHelper();
constructor(header: any) {
super(arguments.length == 0 ? Type.CONNACK : arguments.length == 1 ? arguments[0] instanceof Header ? arguments[0] : Type.CONNACK : null);
var me = this;
switch (arguments.length) {
case 0:
case 1:
if (!(arguments[0] instanceof Header)) {
if (arguments[0] in ConnectionState) {
if (arguments[0] == null) {
throw new Error("ConnAckMessage:The status of ConnAskMessage can't be null");
}
me.setStatus(arguments[0]);
}
}
break;
}
};
messageLength(): number {
var length = this.MESSAGE_LENGTH;
if (this.userId) {
length += this.binaryHelper.toMQttString(this.userId).length;
}
return length;
};
readMessage(_in: RongIMStream, msglength: number) {
_in.read();
var result = +_in.read();
if (result >= 0 && result <= 12) {
this.setStatus(result);
} else {
throw new Error("Unsupported CONNACK code:" + result);
}
if (msglength > this.MESSAGE_LENGTH) {
this.setUserId(_in.readUTF());
var sessionId = _in.readUTF();
var timestamp = _in.readLong();
this.setTimestamp(timestamp);
}
};
writeMessage(out: any) {
var stream = this.binaryHelper.convertStream(out);
stream.write(128);
switch (+status) {
case 0:
case 1:
case 2:
case 5:
case 6:
stream.write(+status);
break;
case 3:
case 4:
stream.write(3);
break;
default:
throw new Error("Unsupported CONNACK code:" + status);
}
if (this.userId) {
stream.writeUTF(this.userId);
}
return stream;
};
setStatus(x: any) {
this.status = x;
};
setUserId(_userId: string) {
this.userId = _userId;
};
getStatus() {
return this.status;
};
getUserId() {
return this.userId;
};
setTimestamp(x: number) {
this.timestrap = x;
};
getTimestamp(): number {
return this.timestrap;
}
}
/**
*断开消息类型
*/
export class DisconnectMessage extends BaseMessage {
_name: string = "DisconnectMessage";
status: any;
MESSAGE_LENGTH: number = 2;
binaryHelper: BinaryHelper = new BinaryHelper();
constructor(header: any) {
super(header instanceof Header ? header : Type.DISCONNECT);
if (!(header instanceof Header)) {
if (header in RongIMLib.ConnectionStatus) {
this.status = header;
}
}
}
messageLength(): number {
return this.MESSAGE_LENGTH;
}
readMessage(_in: any) {
_in.read();
var result = +_in.read();
if (result >= 0 && result <= 5) {
this.setStatus(disconnectStatus[result] ? disconnectStatus[result] : result);
} else {
throw new Error("Unsupported CONNACK code:" + result);
}
}
writeMessage(Out: any) {
var out = this.binaryHelper.convertStream(Out);
out.write(0);
if (+status >= 1 && +status <= 3) {
out.write((+status) - 1);
} else {
throw new Error("Unsupported CONNACK code:" + status);
}
}
setStatus(x: any) {
this.status = x;
};
getStatus() {
return this.status;
};
}
/**
*请求消息信令
*/
export class PingReqMessage extends BaseMessage {
_name: string = "PingReqMessage";
constructor(header?: RongIMLib.Header) {
super((header && header instanceof Header) ? header : Type.PINGREQ);
}
}
/**
*响应消息信令
*/
export class PingRespMessage extends BaseMessage {
_name: string = "PingRespMessage";
constructor(header: RongIMLib.Header) {
super((header && header instanceof Header) ? header : Type.PINGRESP);
}
}
/**
*封装MesssageId
*/
export class RetryableMessage extends BaseMessage {
_name: string = "RetryableMessage";
messageId: any;
binaryHelper: BinaryHelper = new BinaryHelper();
constructor(argu: any) {
super(argu);
}
messageLength(): number {
return 2;
}
writeMessage(Out: any): any {
var out = this.binaryHelper.convertStream(Out),
Id = this.getMessageId(),
lsb = Id & 255,
msb = (Id & 65280) >> 8;
out.write(msb);
out.write(lsb);
return out;
}
readMessage(_in: any, msgLength?: number) {
var msgId = _in.read() * 256 + _in.read();
this.setMessageId(parseInt(msgId, 10));
}
setMessageId(_messageId: number) {
this.messageId = _messageId;
}
getMessageId(): any {
return this.messageId;
}
}
/**
*发送消息应答(双向)
*qos为1必须给出应答(所有消息类型一样)
*/
export class PubAckMessage extends RetryableMessage {
status: any;
msgLen: number = 2;
date: number = 0;
millisecond: number = 0;
messageUId: string;
timestamp: number = 0;
binaryHelper: BinaryHelper = new BinaryHelper();
_name: string = "PubAckMessage";
constructor(header: any) {
super((header instanceof Header) ? header : Type.PUBACK);
if (!(header instanceof Header)) {
super.setMessageId(header);
}
}
messageLength(): number {
return this.msgLen;
}
writeMessage(Out: any) {
var out = this.binaryHelper.convertStream(Out);
RetryableMessage.prototype.writeMessage.call(this, out);
}
readMessage(_in: any, msgLength: number) {
RetryableMessage.prototype.readMessage.call(this, _in);
this.date = _in.readInt();
this.status = _in.read() * 256 + _in.read();
this.millisecond = _in.read() * 256 + _in.read();
this.timestamp = this.date * 1000 + this.millisecond;
this.messageUId = _in.readUTF();
}
setStatus(x: any) {
this.status = x;
}
setTimestamp(timestamp: number) {
this.timestamp = timestamp;
}
setMessageUId(messageUId: string) {
this.messageUId = messageUId;
}
getStatus(): any {
return this.status;
}
getDate(): number {
return this.date;
}
getTimestamp(): number {
return this.timestamp;
}
getMessageUId(): string {
return this.messageUId;
}
}
/**
*发布消息
*/
export class PublishMessage extends RetryableMessage {
_name = "PublishMessage";
topic: any;
data: any;
targetId: string;
date: any;
binaryHelper: BinaryHelper = new BinaryHelper();
syncMsg: boolean = false;
constructor(header: any, two?: any, three?: any) {
super((arguments.length == 1 && header instanceof Header) ? header : arguments.length == 3 ? Type.PUBLISH : 0);
if (arguments.length == 3) {
this.topic = header;
this.targetId = three;
this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two;
}
}
messageLength(): number {
var length = 10;
length += this.binaryHelper.toMQttString(this.topic).length;
length += this.binaryHelper.toMQttString(this.targetId).length;
length += this.data.length;
return length;
}
writeMessage(Out: any) {
var out = this.binaryHelper.convertStream(Out);
out.writeUTF(this.topic);
out.writeUTF(this.targetId);
RetryableMessage.prototype.writeMessage.apply(this, arguments);
out.write(this.data);
};
readMessage(_in: any, msgLength: number) {
var pos = 6;
this.date = _in.readInt();
this.topic = _in.readUTF();
pos += this.binaryHelper.toMQttString(this.topic).length;
this.targetId = _in.readUTF();
pos += this.binaryHelper.toMQttString(this.targetId).length;
RetryableMessage.prototype.readMessage.apply(this, arguments);
this.data = new Array(msgLength - pos);
this.data = _in.read(this.data);
};
setTopic(x: any) {
this.topic = x;
}
setData(x: any) {
this.data = x;
}
setTargetId(x: any) {
this.targetId = x;
}
setDate(x: any) {
this.date = x;
}
setSyncMsg(x: boolean) {
this.syncMsg = x;
}
//是否是其他端同步过来的消息
getSyncMsg() {
return this.syncMsg;
}
getTopic() {
return this.topic;
}
getData() {
return this.data;
}
getTargetId() {
return this.targetId;
}
getDate() {
return this.date;
}
}
/**
*请求查询
*/
export class QueryMessage extends RetryableMessage {
topic: any;
data: any;
targetId: any;
binaryHelper: BinaryHelper = new BinaryHelper();
_name = "QueryMessage";
constructor(header: any, two?: any, three?: any) {
super(header instanceof Header ? header : arguments.length == 3 ? Type.QUERY : null);
if (arguments.length == 3) {
this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two;
this.topic = header;
this.targetId = three;
}
}
messageLength(): number {
var length = 0;
length += this.binaryHelper.toMQttString(this.topic).length;
length += this.binaryHelper.toMQttString(this.targetId).length;
length += 2;
length += this.data.length;
return length;
}
writeMessage(Out: any) {
var out = this.binaryHelper.convertStream(Out);
out.writeUTF(this.topic);
out.writeUTF(this.targetId);
RetryableMessage.prototype.writeMessage.call(this, out);
out.write(this.data);
}
readMessage(_in: any, msgLength: number) {
var pos = 0;
this.topic = _in.readUTF();
this.targetId = _in.readUTF();
pos += this.binaryHelper.toMQttString(this.topic).length;
pos += this.binaryHelper.toMQttString(this.targetId).length;
this.readMessage.apply(this, arguments);
pos += 2;
this.data = new Array(msgLength - pos);
_in.read(this.data);
}
setTopic(x: any) {
this.topic = x;
}
setData(x: any) {
this.data = x;
}
setTargetId(x: any) {
this.targetId = x;
}
getTopic() {
return this.topic;
}
getData() {
return this.data;
}
getTargetId() {
return this.targetId;
}
}
/**
*请求查询确认
*/
export class QueryConMessage extends RetryableMessage {
_name: string = "QueryConMessage";
constructor(messageId: any) {
super((messageId instanceof Header) ? messageId : Type.QUERYCON);
if (!(messageId instanceof Header)) {
super.setMessageId(messageId);
}
}
}
/**
*请求查询应答
*/
export class QueryAckMessage extends RetryableMessage {
_name: string = "QueryAckMessage";
data: any;
status: any;
date: any;
binaryHelper: BinaryHelper = new BinaryHelper();
constructor(header: RongIMLib.Header) {
super(header);
}
readMessage(In: any, msgLength: number) {
RetryableMessage.prototype.readMessage.call(this, In);
this.date = In.readInt();
this.setStatus(In.read() * 256 + In.read());
if (msgLength > 0) {
this.data = new Array(msgLength - 8);
this.data = In.read(this.data);
}
}
getData(): any {
return this.data;
}
getStatus(): any {
return this.status;
}
getDate(): any {
return this.date;
}
setDate(x: any) {
this.date = x;
}
setStatus(x: any) {
this.status = x;
}
setData(x: any) {
this.data = x;
}
}
} | the_stack |
import type { MapLike } from 'typescript'
import {
ControlDescription,
ObjectControlDescription,
Vector2ControlDescription,
Vector3ControlDescription,
PropertyControls,
expression,
importStar,
} from 'utopia-api'
const Vector3: Vector3ControlDescription = {
control: 'vector3',
}
const Vector2: Vector2ControlDescription = {
control: 'vector2',
}
const Euler: ObjectControlDescription = {
control: 'object',
object: {
x: {
control: 'number-input',
label: 'x',
},
y: {
control: 'number-input',
label: 'y',
},
z: {
control: 'number-input',
label: 'z',
},
order: {
control: 'string-input',
label: 'order',
},
},
}
const nodePropsControls: PropertyControls = {
attach: {
control: 'string-input',
label: 'attach',
},
attachArray: {
control: 'string-input',
label: 'attachArray',
},
}
const object3DNodePropsControls: PropertyControls = {
...nodePropsControls,
position: Vector3,
up: Vector3,
scale: Vector3,
rotation: Euler,
// matrix,
// quarternion,
// layers,
}
const colorControls: PropertyControls = {
...nodePropsControls,
args: {
control: 'color',
},
attach: {
control: 'string-input',
label: 'attach',
},
}
const fogControls: PropertyControls = {
...nodePropsControls,
color: {
control: 'color',
},
near: {
control: 'number-input',
},
far: {
control: 'number-input',
},
}
/* LIGHTS */
const lightControls: PropertyControls = {
...object3DNodePropsControls,
color: {
control: 'string-input',
label: 'color',
},
intensity: {
control: 'number-input',
label: 'intensity',
},
}
const pointLightControls: PropertyControls = {
...lightControls,
decay: {
control: 'number-input',
},
distance: {
control: 'number-input',
},
power: {
control: 'number-input',
},
// shadow,
}
const ambientLightControls: PropertyControls = {
...lightControls,
}
const directionalLightControls: PropertyControls = {
...lightControls,
castShadow: {
control: 'checkbox',
},
target: Vector3,
}
const spotLightControls: PropertyControls = {
...lightControls,
angle: {
control: 'number-input',
},
castShadow: {
control: 'checkbox',
},
decay: {
control: 'number-input',
},
distance: {
control: 'number-input',
},
penumbra: {
control: 'number-input',
},
power: {
control: 'number-input',
},
// shadow,
// target,
}
/* GEOMETRY */
const bufferGeometryControls: PropertyControls = {
...nodePropsControls,
// attributes,
// boundingBox,
// boundingSphere,
// drawRange,
// groups,
// id,
// index,
// morphAttributes,
morphTargetsRelative: {
control: 'checkbox',
},
name: {
control: 'string-input',
},
// userData,
// uuid
}
const planeGeometryControls: PropertyControls = {
...bufferGeometryControls,
args: {
control: 'object',
object: {
0: {
control: 'number-input',
label: 'width',
},
1: {
control: 'number-input',
label: 'height',
},
2: {
control: 'number-input',
label: 'widthSegments',
},
3: {
control: 'number-input',
label: 'heightSegments',
},
},
},
}
const sphereGeometryControls: PropertyControls = {
...bufferGeometryControls,
args: {
control: 'object',
object: {
0: {
control: 'number-input',
label: 'radius',
},
1: {
control: 'number-input',
label: 'widthSegments',
},
2: {
control: 'number-input',
label: 'heightSegments',
},
3: {
control: 'number-input',
label: 'phiStart',
},
4: {
control: 'number-input',
label: 'phiLength',
},
5: {
control: 'number-input',
label: 'thetaStart',
},
6: {
control: 'number-input',
label: 'thetaLength',
},
},
},
}
const boxGeometryControls: PropertyControls = {
...bufferGeometryControls,
args: Vector3,
}
/* MATERIALS */
const stencilOperations: ControlDescription = {
control: 'expression-popuplist',
options: [
expression(0, 'THREE.ZeroStencilOp', importStar('three', 'THREE')),
expression(7680, 'THREE.KeepStencilOp', importStar('three', 'THREE')),
expression(7681, 'THREE.ReplaceStencilOp', importStar('three', 'THREE')),
expression(7682, 'THREE.IncrementStencilOp', importStar('three', 'THREE')),
expression(7683, 'THREE.DecrementStencilOp', importStar('three', 'THREE')),
expression(34055, 'THREE.IncrementWrapStencilOp', importStar('three', 'THREE')),
expression(34056, 'THREE.DecrementWrapStencilOp', importStar('three', 'THREE')),
expression(5386, 'THREE.InvertStencilOp', importStar('three', 'THREE')),
],
}
const materialControls: PropertyControls = {
...nodePropsControls,
alphaTest: {
control: 'number-input',
},
alphaToCoverage: {
control: 'number-input',
},
Blending: {
control: 'folder',
controls: {
blendDst: {
control: 'expression-popuplist',
options: [
expression(200, 'THREE.ZeroFactor', importStar('three', 'THREE')),
expression(201, 'THREE.OneFactor', importStar('three', 'THREE')),
expression(202, 'THREE.SrcColorFactor', importStar('three', 'THREE')),
expression(203, 'THREE.OneMinusSrcColorFactor', importStar('three', 'THREE')),
expression(204, 'THREE.SrcAlphaFactor', importStar('three', 'THREE')),
expression(205, 'THREE.OneMinusSrcAlphaFactor', importStar('three', 'THREE')),
expression(206, 'THREE.DstAlphaFactor', importStar('three', 'THREE')),
expression(207, 'THREE.OneMinusDstAlphaFactor', importStar('three', 'THREE')),
expression(208, 'THREE.DstColorFactor', importStar('three', 'THREE')),
expression(209, 'THREE.OneMinusDstColorFactor', importStar('three', 'THREE')),
],
},
blendDstAlpha: {
control: 'number-input',
},
blendEquation: {
control: 'expression-popuplist',
options: [
expression(100, 'THREE.AddEquation', importStar('three', 'THREE')),
expression(101, 'THREE.SubtractEquation', importStar('three', 'THREE')),
expression(102, 'THREE.ReverseSubtractEquation', importStar('three', 'THREE')),
expression(103, 'THREE.MinEquation', importStar('three', 'THREE')),
expression(104, 'THREE.MaxEquation', importStar('three', 'THREE')),
],
},
blendEquationAlpha: {
control: 'number-input',
},
blending: {
control: 'expression-popuplist',
options: [
expression(0, 'THREE.NoBlending', importStar('three', 'THREE')),
expression(1, 'THREE.NormalBlending', importStar('three', 'THREE')),
expression(2, 'THREE.AdditiveBlending', importStar('three', 'THREE')),
expression(3, 'THREE.SubtractiveBlending', importStar('three', 'THREE')),
expression(4, 'THREE.MultiplyBlending', importStar('three', 'THREE')),
expression(5, 'THREE.CustomBlending', importStar('three', 'THREE')),
],
},
blendSrc: {
control: 'expression-popuplist',
options: [
expression(200, 'THREE.ZeroFactor', importStar('three', 'THREE')),
expression(201, 'THREE.OneFactor', importStar('three', 'THREE')),
expression(202, 'THREE.SrcColorFactor', importStar('three', 'THREE')),
expression(203, 'THREE.OneMinusSrcColorFactor', importStar('three', 'THREE')),
expression(204, 'THREE.SrcAlphaFactor', importStar('three', 'THREE')),
expression(205, 'THREE.OneMinusSrcAlphaFactor', importStar('three', 'THREE')),
expression(206, 'THREE.DstAlphaFactor', importStar('three', 'THREE')),
expression(207, 'THREE.OneMinusDstAlphaFactor', importStar('three', 'THREE')),
expression(208, 'THREE.DstColorFactor', importStar('three', 'THREE')),
expression(209, 'THREE.OneMinusDstColorFactor', importStar('three', 'THREE')),
expression(210, 'THREE.SrcAlphaSaturateFactor', importStar('three', 'THREE')),
],
},
blendSrcAlpha: {
control: 'number-input',
},
},
},
clipIntersection: {
control: 'checkbox',
},
// clippingPlanes,
clipShadows: {
control: 'checkbox',
},
colorWrite: {
control: 'checkbox',
},
// defines,
depthFunc: {
control: 'expression-popuplist',
options: [
expression(0, 'THREE.NeverDepth', importStar('three', 'THREE')),
expression(1, 'THREE.AlwaysDepth', importStar('three', 'THREE')),
expression(4, 'THREE.EqualDepth', importStar('three', 'THREE')),
expression(2, 'THREE.LessDepth', importStar('three', 'THREE')),
expression(3, 'THREE.LessEqualDepth', importStar('three', 'THREE')),
expression(5, 'THREE.GreaterEqualDepth', importStar('three', 'THREE')),
expression(6, 'THREE.GreaterDepth', importStar('three', 'THREE')),
expression(7, 'THREE.NotEqualDepth', importStar('three', 'THREE')),
],
},
depthTest: {
control: 'checkbox',
},
depthWrite: {
control: 'checkbox',
},
stencilWrite: {
control: 'checkbox',
},
stencilWriteMask: {
control: 'number-input',
},
stencilRef: {
control: 'number-input',
},
stencilFuncMask: {
control: 'number-input',
},
stencilFail: stencilOperations,
stencilZFail: stencilOperations,
stencilZPass: stencilOperations,
fog: {
control: 'checkbox',
},
opacity: {
control: 'number-input',
min: 0.0,
max: 1.0,
step: 0.1,
},
polygonOffset: {
control: 'checkbox',
},
polygonOffsetFactor: {
control: 'number-input',
},
polygonOffsetUnits: {
control: 'number-input',
},
precision: {
control: 'popuplist',
options: ['highp', 'mediump', 'lowp'],
},
preMultipliedAlpha: {
control: 'checkbox',
},
dithering: {
control: 'checkbox',
},
shadowSide: {
control: 'expression-popuplist',
options: [
expression(0, 'THREE.FrontSide', importStar('three', 'THREE')),
expression(1, 'THREE.BackSide', importStar('three', 'THREE')),
expression(2, 'THREE.DoubleSide', importStar('three', 'THREE')),
],
},
side: {
control: 'expression-popuplist',
options: [
expression(0, 'THREE.FrontSide', importStar('three', 'THREE')),
expression(1, 'THREE.BackSide', importStar('three', 'THREE')),
expression(2, 'THREE.DoubleSide', importStar('three', 'THREE')),
],
},
toneMapped: {
control: 'checkbox',
},
transparent: {
control: 'checkbox',
},
vertexColors: {
control: 'checkbox',
},
visible: {
control: 'checkbox',
},
}
const meshBasicMaterialControls: PropertyControls = {
...materialControls,
// alphaMap,
// aoMap,
aoMapIntensity: {
control: 'number-input',
},
color: {
control: 'color',
},
combine: {
control: 'expression-popuplist',
options: [
expression(0, 'THREE.Multiply', importStar('three', 'THREE')),
expression(1, 'THREE.MixOperation', importStar('three', 'THREE')),
expression(2, 'THREE.AddOperation', importStar('three', 'THREE')),
],
},
// envMap,
// lightMap,
lightMapIntensity: {
control: 'number-input',
},
// map,
reflectivity: {
control: 'number-input',
min: 0,
max: 1,
step: 0.05,
},
refractionRatio: {
control: 'number-input',
min: 0,
max: 1,
step: 0.05,
},
// specularMap,
wireframe: {
control: 'checkbox',
},
wireframeLinecap: {
control: 'popuplist',
options: ['butt', 'round', 'square'],
},
wireframeLinejoin: {
control: 'popuplist',
options: ['round', 'bevel', 'miter'],
},
wireframeLinewidth: {
control: 'number-input',
},
}
const meshStandardMaterialControls: PropertyControls = {
...materialControls,
// alphaMap,
// aoMap,
aoMapIntensity: {
control: 'number-input',
},
// bumpMap,
bumpScale: {
control: 'number-input',
min: 0,
max: 1,
step: 0.05,
},
color: {
control: 'color',
},
// defines,
// displacementMap,
displacementScale: {
control: 'number-input',
},
displacementBias: {
control: 'number-input',
},
emissive: {
control: 'color',
},
// emissiveMap,
emissiveIntensity: {
control: 'number-input',
},
// envMap,
envMapIntensity: {
control: 'number-input',
},
flatShading: {
control: 'checkbox',
},
// lightMap,
lightMapIntensity: {
control: 'number-input',
},
// map,
metalness: {
control: 'number-input',
min: 0,
max: 1,
step: 0.05,
},
// metalnessMap,
// normalMap,
// normalMapType,
// normalScale,
refractionRatio: {
control: 'number-input',
min: 0,
max: 1,
step: 0.05,
},
roughness: {
control: 'number-input',
min: 0,
max: 1,
step: 0.05,
},
// roughnessMap,
wireframe: {
control: 'checkbox',
},
wireframeLinecap: {
control: 'popuplist',
options: ['butt', 'round', 'square'],
},
wireframeLinejoin: {
control: 'popuplist',
options: ['round', 'bevel', 'miter'],
},
wireframeLinewidth: {
control: 'number-input',
},
}
const shadowMaterialControls: PropertyControls = {
...materialControls,
transparent: {
control: 'checkbox',
},
}
export const ReactThreeFiberControls = {
color: colorControls,
fog: fogControls,
ambientLight: ambientLightControls,
directionalLight: directionalLightControls,
pointLight: pointLightControls,
spotLight: spotLightControls,
boxGeometry: boxGeometryControls,
planeGeometry: planeGeometryControls,
sphereGeometry: sphereGeometryControls,
meshBasicMaterial: meshBasicMaterialControls,
meshStandardMaterial: meshStandardMaterialControls,
shadowMaterial: shadowMaterialControls,
} | the_stack |
import { Message } from "@keplr-wallet/router";
import { ChainInfo, KeplrSignOptions, Key } from "@keplr-wallet/types";
import { AminoSignResponse, StdSignature, StdSignDoc } from "@cosmjs/launchpad";
export class EnableAccessMsg extends Message<void> {
public static type() {
return "enable-access";
}
constructor(public readonly chainIds: string[]) {
super();
}
validateBasic(): void {
if (!this.chainIds || this.chainIds.length === 0) {
throw new Error("chain id not set");
}
}
route(): string {
return "permission";
}
type(): string {
return EnableAccessMsg.type();
}
}
export class GetKeyMsg extends Message<Key> {
public static type() {
return "get-key";
}
constructor(public readonly chainId: string) {
super();
}
validateBasic(): void {
if (!this.chainId) {
throw new Error("chain id not set");
}
}
route(): string {
return "keyring";
}
type(): string {
return GetKeyMsg.type();
}
}
export class SuggestChainInfoMsg extends Message<void> {
public static type() {
return "suggest-chain-info";
}
constructor(public readonly chainInfo: ChainInfo) {
super();
}
validateBasic(): void {
if (!this.chainInfo) {
throw new Error("chain info not set");
}
}
route(): string {
return "chains";
}
type(): string {
return SuggestChainInfoMsg.type();
}
}
export class SuggestTokenMsg extends Message<void> {
public static type() {
return "suggest-token";
}
constructor(
public readonly chainId: string,
public readonly contractAddress: string,
public readonly viewingKey?: string
) {
super();
}
validateBasic(): void {
if (!this.chainId) {
throw new Error("Chain id is empty");
}
if (!this.contractAddress) {
throw new Error("Contract address is empty");
}
}
route(): string {
return "tokens";
}
type(): string {
return SuggestTokenMsg.type();
}
}
// Return the tx hash
export class SendTxMsg extends Message<Uint8Array> {
public static type() {
return "send-tx-to-background";
}
constructor(
public readonly chainId: string,
public readonly tx: unknown,
public readonly mode: "async" | "sync" | "block"
) {
super();
}
validateBasic(): void {
if (!this.chainId) {
throw new Error("chain id is empty");
}
if (!this.tx) {
throw new Error("tx is empty");
}
if (
!this.mode ||
(this.mode !== "sync" && this.mode !== "async" && this.mode !== "block")
) {
throw new Error("invalid mode");
}
}
route(): string {
return "background-tx";
}
type(): string {
return SendTxMsg.type();
}
}
export class GetSecret20ViewingKey extends Message<string> {
public static type() {
return "get-secret20-viewing-key";
}
constructor(
public readonly chainId: string,
public readonly contractAddress: string
) {
super();
}
validateBasic(): void {
if (!this.chainId) {
throw new Error("Chain id is empty");
}
if (!this.contractAddress) {
throw new Error("Contract address is empty");
}
}
route(): string {
return "tokens";
}
type(): string {
return GetSecret20ViewingKey.type();
}
}
export class RequestSignAminoMsg extends Message<AminoSignResponse> {
public static type() {
return "request-sign-amino";
}
constructor(
public readonly chainId: string,
public readonly signer: string,
public readonly signDoc: StdSignDoc,
public readonly signOptions: KeplrSignOptions & {
// Hack option field to detect the sign arbitrary for string
isADR36WithString?: boolean;
} = {}
) {
super();
}
validateBasic(): void {
if (!this.chainId) {
throw new Error("chain id not set");
}
if (!this.signer) {
throw new Error("signer not set");
}
// It is not important to check this on the client side as opposed to increasing the bundle size.
// Validate bech32 address.
// Bech32Address.validate(this.signer);
const signDoc = this.signDoc;
// Check that the sign doc is for ADR-36,
// the validation should be performed on the background.
const hasOnlyMsgSignData = (() => {
if (
signDoc &&
signDoc.msgs &&
Array.isArray(signDoc.msgs) &&
signDoc.msgs.length === 1
) {
const msg = signDoc.msgs[0];
return msg.type === "sign/MsgSignData";
} else {
return false;
}
})();
// If the sign doc is expected to be for ADR-36,
// it doesn't have to have the chain id in the sign doc.
if (!hasOnlyMsgSignData && signDoc.chain_id !== this.chainId) {
throw new Error(
"Chain id in the message is not matched with the requested chain id"
);
}
if (!this.signOptions) {
throw new Error("Sign options are null");
}
}
route(): string {
return "keyring";
}
type(): string {
return RequestSignAminoMsg.type();
}
}
export class RequestVerifyADR36AminoSignDoc extends Message<boolean> {
public static type() {
return "request-verify-adr-36-amino-doc";
}
constructor(
public readonly chainId: string,
public readonly signer: string,
public readonly data: Uint8Array,
public readonly signature: StdSignature
) {
super();
}
validateBasic(): void {
if (!this.chainId) {
throw new Error("chain id not set");
}
if (!this.signer) {
throw new Error("signer not set");
}
if (!this.signature) {
throw new Error("Signature not set");
}
// It is not important to check this on the client side as opposed to increasing the bundle size.
// Validate bech32 address.
// Bech32Address.validate(this.signer);
}
route(): string {
return "keyring";
}
type(): string {
return RequestVerifyADR36AminoSignDoc.type();
}
}
export class RequestSignDirectMsg extends Message<{
readonly signed: {
bodyBytes: Uint8Array;
authInfoBytes: Uint8Array;
chainId: string;
accountNumber: string;
};
readonly signature: StdSignature;
}> {
public static type() {
return "request-sign-direct";
}
constructor(
public readonly chainId: string,
public readonly signer: string,
public readonly signDoc: {
bodyBytes?: Uint8Array | null;
authInfoBytes?: Uint8Array | null;
chainId?: string | null;
accountNumber?: string | null;
},
public readonly signOptions: KeplrSignOptions = {}
) {
super();
}
validateBasic(): void {
if (!this.chainId) {
throw new Error("chain id not set");
}
if (!this.signer) {
throw new Error("signer not set");
}
// It is not important to check this on the client side as opposed to increasing the bundle size.
// Validate bech32 address.
// Bech32Address.validate(this.signer);
// const signDoc = cosmos.tx.v1beta1.SignDoc.create({
// bodyBytes: this.signDoc.bodyBytes,
// authInfoBytes: this.signDoc.authInfoBytes,
// chainId: this.signDoc.chainId,
// accountNumber: this.signDoc.accountNumber
// ? Long.fromString(this.signDoc.accountNumber)
// : undefined,
// });
//
// if (signDoc.chainId !== this.chainId) {
// throw new Error(
// "Chain id in the message is not matched with the requested chain id"
// );
// }
if (!this.signOptions) {
throw new Error("Sign options are null");
}
}
route(): string {
return "keyring";
}
type(): string {
return RequestSignDirectMsg.type();
}
}
export class GetPubkeyMsg extends Message<Uint8Array> {
public static type() {
return "get-pubkey-msg";
}
constructor(public readonly chainId: string) {
super();
}
validateBasic(): void {
if (!this.chainId) {
throw new Error("chain id not set");
}
}
route(): string {
return "secret-wasm";
}
type(): string {
return GetPubkeyMsg.type();
}
}
export class ReqeustEncryptMsg extends Message<Uint8Array> {
public static type() {
return "request-encrypt-msg";
}
constructor(
public readonly chainId: string,
public readonly contractCodeHash: string,
// eslint-disable-next-line @typescript-eslint/ban-types
public readonly msg: object
) {
super();
}
validateBasic(): void {
if (!this.chainId) {
throw new Error("chain id not set");
}
if (!this.contractCodeHash) {
throw new Error("contract code hash not set");
}
if (!this.msg) {
throw new Error("msg not set");
}
}
route(): string {
return "secret-wasm";
}
type(): string {
return ReqeustEncryptMsg.type();
}
}
export class RequestDecryptMsg extends Message<Uint8Array> {
public static type() {
return "request-decrypt-msg";
}
constructor(
public readonly chainId: string,
public readonly cipherText: Uint8Array,
public readonly nonce: Uint8Array
) {
super();
}
validateBasic(): void {
if (!this.chainId) {
throw new Error("chain id not set");
}
if (!this.cipherText || this.cipherText.length === 0) {
throw new Error("ciphertext not set");
}
if (!this.nonce || this.nonce.length === 0) {
throw new Error("nonce not set");
}
}
route(): string {
return "secret-wasm";
}
type(): string {
return RequestDecryptMsg.type();
}
}
export class GetTxEncryptionKeyMsg extends Message<Uint8Array> {
public static type() {
return "get-tx-encryption-key-msg";
}
constructor(
public readonly chainId: string,
public readonly nonce: Uint8Array
) {
super();
}
validateBasic(): void {
if (!this.chainId) {
throw new Error("chain id not set");
}
if (!this.nonce) {
// Nonce of zero length is permitted.
throw new Error("nonce is null");
}
}
route(): string {
return "secret-wasm";
}
type(): string {
return GetTxEncryptionKeyMsg.type();
}
} | the_stack |
import * as React from 'react';
import { useMemo, useState } from 'react';
import * as TestRenderer from 'react-test-renderer';
import {
useFragment as useFragmentNodeOriginal,
useFragmentSubscription,
ReactRelayContext,
} from '../src';
import {
FRAGMENT_OWNER_KEY,
FRAGMENTS_KEY,
ID_KEY,
createOperationDescriptor,
} from 'relay-runtime';
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails oncall+relay
* @flow
* @format
*/
/*
("use strict");
const React = require("react");
const { useMemo, useRef, useState } = React;
const TestRenderer = require("react-test-renderer");
const useFragmentNodeOriginal = require("../useFragmentNode");
const ReactRelayContext = require("react-relay/ReactRelayContext");
const {
FRAGMENT_OWNER_KEY,
FRAGMENTS_KEY,
ID_KEY,
createOperationDescriptor
} = require("relay-runtime");
*/
function assertYieldsWereCleared(_scheduler) {
const actualYields = _scheduler.unstable_clearYields();
if (actualYields.length !== 0) {
throw new Error(
'Log of yielded values is not empty. ' +
'Call expect(Scheduler).toHaveYielded(...) first.',
);
}
}
function expectSchedulerToFlushAndYield(expectedYields) {
TestRenderer.act(() => {
const Scheduler = require('scheduler');
assertYieldsWereCleared(Scheduler);
Scheduler.unstable_flushAllWithoutAsserting();
const actualYields = Scheduler.unstable_clearYields();
expect(actualYields).toEqual(expectedYields);
});
}
function expectSchedulerToFlushAndYieldThrough(expectedYields) {
TestRenderer.act(() => {
const Scheduler = require('scheduler');
assertYieldsWereCleared(Scheduler);
Scheduler.unstable_flushNumberOfYields(expectedYields.length);
const actualYields = Scheduler.unstable_clearYields();
expect(actualYields).toEqual(expectedYields);
});
}
let environment;
let createMockEnvironment;
let disableStoreUpdates;
let enableStoreUpdates;
let generateAndCompile;
let gqlSingularQuery;
let gqlSingularFragment;
let gqlPluralQuery;
let gqlPluralFragment;
let singularQuery;
let pluralQuery;
let singularVariables;
let pluralVariables;
let setEnvironment;
let setSingularOwner;
let renderSingularFragment;
let subscribeSingularFragment;
let renderPluralFragment;
let forceSingularUpdate;
let renderSpy;
let SingularRenderer;
let PluralRenderer;
function resetRenderMock() {
renderSpy.mockClear();
}
function useFragmentNode(fragmentNode, fragmentRef) {
const data = useFragmentNodeOriginal(fragmentNode, fragmentRef);
/*const { data, shouldUpdateGeneration } = result;
disableStoreUpdates = result.disableStoreUpdates;
enableStoreUpdates = result.enableStoreUpdates;
const prevShouldUpdateGeneration = useRef(null);
let shouldUpdate = false;
if (prevShouldUpdateGeneration.current !== shouldUpdateGeneration) {
shouldUpdate = true;
prevShouldUpdateGeneration.current = shouldUpdateGeneration;
}*/
renderSpy(data, true);
return [data, true];
}
function assertFragmentResults(expectedCalls) {
// This ensures that useEffect runs
TestRenderer.act(() => jest.runAllImmediates());
expect(renderSpy).toBeCalledTimes(expectedCalls.length);
expectedCalls.forEach((expected, idx) => {
const [actualData, actualShouldUpdate] = renderSpy.mock.calls[idx];
expect(actualData).toEqual(expected.data);
expect(actualShouldUpdate).toEqual(expected.shouldUpdate);
});
renderSpy.mockClear();
}
function createFragmentRef(id, owner) {
return {
[ID_KEY]: id,
[FRAGMENTS_KEY]: {
NestedUserFragment: {},
},
[FRAGMENT_OWNER_KEY]: owner.request,
};
}
beforeEach(() => {
// Set up mocks
jest.resetModules();
jest.spyOn(console, 'warn').mockImplementationOnce(() => {});
jest.mock('scheduler', () => {
return jest.requireActual('scheduler/unstable_mock');
});
jest.mock('fbjs/lib/ExecutionEnvironment', () => ({
canUseDOM: () => true,
}));
renderSpy = jest.fn();
({ generateAndCompile } = require('./TestCompiler'));
({ createMockEnvironment } = require('relay-test-utils-internal'));
// Set up environment and base data
environment = createMockEnvironment();
const generated = generateAndCompile(`
fragment NestedUserFragment on User {
username
}
fragment UserFragment on User {
id
name
profile_picture(scale: $scale) {
uri
}
...NestedUserFragment
}
fragment UsersFragment on User @relay(plural: true) {
id
name
profile_picture(scale: $scale) {
uri
}
...NestedUserFragment
}
query UsersQuery($ids: [ID!]!, $scale: Int!) {
nodes(ids: $ids) {
...UsersFragment
}
}
query UserQuery($id: ID!, $scale: Int!) {
node(id: $id) {
...UserFragment
}
}
`);
singularVariables = { id: '1', scale: 16 };
pluralVariables = { ids: ['1', '2'], scale: 16 };
gqlSingularQuery = generated.UserQuery;
gqlSingularFragment = generated.UserFragment;
gqlPluralQuery = generated.UsersQuery;
gqlPluralFragment = generated.UsersFragment;
singularQuery = createOperationDescriptor(gqlSingularQuery, singularVariables);
pluralQuery = createOperationDescriptor(gqlPluralQuery, pluralVariables);
environment.commitPayload(singularQuery, {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
username: 'useralice',
profile_picture: null,
},
});
environment.commitPayload(pluralQuery, {
nodes: [
{
__typename: 'User',
id: '1',
name: 'Alice',
username: 'useralice',
profile_picture: null,
},
{
__typename: 'User',
id: '2',
name: 'Bob',
username: 'userbob',
profile_picture: null,
},
],
});
// Set up renderers
SingularRenderer = (props) => null;
PluralRenderer = (props) => null;
const SingularContainer = (props) => {
// We need a render a component to run a Hook
const [owner, _setOwner] = useState(props.owner);
const [, _setCount] = useState(0);
const userRef = props.hasOwnProperty('userRef')
? props.userRef
: {
[ID_KEY]: owner.request.variables.id,
[FRAGMENTS_KEY]: {
UserFragment: {},
},
[FRAGMENT_OWNER_KEY]: owner.request,
};
setSingularOwner = _setOwner;
forceSingularUpdate = () => _setCount((count) => count + 1);
const [userData] = useFragmentNode(gqlSingularFragment, userRef);
return <SingularRenderer user={userData} />;
};
const SingularSubscribeContainer = (props) => {
const [owner, _setOwner] = useState(props.owner);
const [, _setCount] = useState(0);
const userRef = props.hasOwnProperty('userRef')
? props.userRef
: {
[ID_KEY]: owner.request.variables.id,
[FRAGMENTS_KEY]: {
UserFragment: {},
},
[FRAGMENT_OWNER_KEY]: owner.request,
};
setSingularOwner = _setOwner;
useFragmentSubscription(gqlSingularFragment, userRef, props.onData);
return null;
};
const PluralContainer = (props) => {
// We need a render a component to run a Hook
const owner = props.owner;
const usersRef = props.hasOwnProperty('usersRef')
? props.usersRef
: owner.request.variables.ids.map((id) => ({
[ID_KEY]: id,
[FRAGMENTS_KEY]: {
UsersFragment: {},
},
[FRAGMENT_OWNER_KEY]: owner.request,
}));
const [usersData] = useFragmentNode(gqlPluralFragment, usersRef);
return <PluralRenderer users={usersData} />;
};
const ContextProvider = ({ children }) => {
const [env, _setEnv] = useState(environment);
const relayContext = useMemo(() => ({ environment: env }), [env]);
setEnvironment = _setEnv;
return (
<ReactRelayContext.Provider value={relayContext}>{children}</ReactRelayContext.Provider>
);
};
renderSingularFragment = (args) => {
const { isConcurrent = false, ...props } = args ? args : {};
return TestRenderer.create(
<React.Suspense fallback="Singular Fallback">
<ContextProvider>
<SingularContainer owner={singularQuery} {...props} />
</ContextProvider>
</React.Suspense>,
{ unstable_isConcurrent: isConcurrent },
);
};
renderPluralFragment = (args) => {
const { isConcurrent = false, ...props } = args ? args : {};
return TestRenderer.create(
<React.Suspense fallback="Plural Fallback">
<ContextProvider>
<PluralContainer owner={pluralQuery} {...props} />
</ContextProvider>
</React.Suspense>,
{ unstable_isConcurrent: isConcurrent },
);
};
subscribeSingularFragment = (props) => {
return TestRenderer.create(
<React.Suspense fallback="Singular Fallback">
<ContextProvider>
<SingularSubscribeContainer owner={singularQuery} {...props} />
</ContextProvider>
</React.Suspense>,
{ unstable_isConcurrent: false },
);
};
});
afterEach(() => {
environment.mockClear();
renderSpy.mockClear();
});
it('should render singular fragment without error when data is available', () => {
renderSingularFragment();
assertFragmentResults([
{
data: {
id: '1',
name: 'Alice',
profile_picture: null,
...createFragmentRef('1', singularQuery),
},
shouldUpdate: true,
},
]);
});
it('should render singular fragment without error when ref is null', () => {
renderSingularFragment({ userRef: null });
assertFragmentResults([
{
data: null,
shouldUpdate: true,
},
]);
});
it('should render singular fragment without error when ref is undefined', () => {
renderSingularFragment({ userRef: undefined });
assertFragmentResults([
{
data: null,
shouldUpdate: true,
},
]);
});
it('should render plural fragment without error when data is available', () => {
renderPluralFragment();
assertFragmentResults([
{
data: [
{
id: '1',
name: 'Alice',
profile_picture: null,
...createFragmentRef('1', pluralQuery),
},
{
id: '2',
name: 'Bob',
profile_picture: null,
...createFragmentRef('2', pluralQuery),
},
],
shouldUpdate: true,
},
]);
});
it('should render plural fragment without error when plural field is empty', () => {
renderPluralFragment({ usersRef: [] });
assertFragmentResults([
{
data: [],
shouldUpdate: true,
},
]);
});
it('should update when fragment data changes', () => {
renderSingularFragment();
assertFragmentResults([
{
data: {
id: '1',
name: 'Alice',
profile_picture: null,
...createFragmentRef('1', singularQuery),
},
shouldUpdate: true,
},
]);
TestRenderer.act(() => {
environment.commitPayload(singularQuery, {
node: {
__typename: 'User',
id: '1',
// Update name
name: 'Alice in Wonderland',
},
});
});
assertFragmentResults([
{
data: {
id: '1',
// Assert that name is updated
name: 'Alice in Wonderland',
profile_picture: null,
...createFragmentRef('1', singularQuery),
},
shouldUpdate: true,
},
]);
});
it('should re-read and resubscribe to fragment when environment changes', () => {
renderSingularFragment();
assertFragmentResults([
{
data: {
id: '1',
name: 'Alice',
profile_picture: null,
...createFragmentRef('1', singularQuery),
},
shouldUpdate: true,
},
]);
const newEnvironment = createMockEnvironment();
newEnvironment.commitPayload(singularQuery, {
node: {
__typename: 'User',
id: '1',
name: 'Alice in a different env',
profile_picture: null,
},
});
TestRenderer.act(() => {
setEnvironment(newEnvironment);
});
const expectedUser = {
id: '1',
name: 'Alice in a different env',
profile_picture: null,
...createFragmentRef('1', singularQuery),
};
assertFragmentResults([
{ data: expectedUser, shouldUpdate: true },
// { data: expectedUser, shouldUpdate: false }
]);
TestRenderer.act(() => {
newEnvironment.commitPayload(singularQuery, {
node: {
__typename: 'User',
id: '1',
// Update name
name: 'Alice in Wonderland',
},
});
});
assertFragmentResults([
{
data: {
id: '1',
// Assert that name is updated
name: 'Alice in Wonderland',
profile_picture: null,
...createFragmentRef('1', singularQuery),
},
shouldUpdate: true,
},
]);
});
it('should re-read and resubscribe to fragment when fragment pointers change', () => {
renderSingularFragment();
assertFragmentResults([
{
data: {
id: '1',
name: 'Alice',
profile_picture: null,
...createFragmentRef('1', singularQuery),
},
shouldUpdate: true,
},
]);
const newVariables = { ...singularVariables, id: '200' };
const newQuery = createOperationDescriptor(gqlSingularQuery, newVariables);
environment.commitPayload(newQuery, {
node: {
__typename: 'User',
id: '200',
name: 'Foo',
profile_picture: null,
username: 'userfoo',
},
});
TestRenderer.act(() => {
setSingularOwner(newQuery);
});
const expectedUser = {
// Assert updated data
id: '200',
name: 'Foo',
profile_picture: null,
// Assert that ref now points to newQuery owner
...createFragmentRef('200', newQuery),
};
assertFragmentResults([
{ data: expectedUser, shouldUpdate: true },
//{ data: expectedUser, shouldUpdate: false }
]);
TestRenderer.act(() => {
environment.commitPayload(newQuery, {
node: {
__typename: 'User',
id: '200',
// Update name
name: 'Foo Updated',
},
});
});
assertFragmentResults([
{
data: {
id: '200',
// Assert that name is updated
name: 'Foo Updated',
profile_picture: null,
...createFragmentRef('200', newQuery),
},
shouldUpdate: true,
},
]);
});
it('should render correct data when changing fragment refs multiple times', () => {
// Render component with data for ID 1
renderSingularFragment();
assertFragmentResults([
{
data: {
id: '1',
name: 'Alice',
profile_picture: null,
...createFragmentRef('1', singularQuery),
},
shouldUpdate: true,
},
]);
// Update fragment refs to render data for ID 200
const newVariables = { ...singularVariables, id: '200' };
const newQuery = createOperationDescriptor(gqlSingularQuery, newVariables);
environment.commitPayload(newQuery, {
node: {
__typename: 'User',
id: '200',
name: 'Foo',
username: 'userfoo',
profile_picture: null,
},
});
TestRenderer.act(() => {
setSingularOwner(newQuery);
});
let expectedUser = {
// Assert updated data
id: '200',
name: 'Foo',
profile_picture: null,
// Assert that ref now points to newQuery owner
...createFragmentRef('200', newQuery),
};
assertFragmentResults([
{ data: expectedUser, shouldUpdate: true },
//{ data: expectedUser, shouldUpdate: false }
]);
// Udpate data for ID 1
environment.commitPayload(singularQuery, {
node: {
__typename: 'User',
id: '1',
// Update name
name: 'Alice in Wonderland',
},
});
// Switch back to rendering data for ID 1
TestRenderer.act(() => {
setSingularOwner(singularQuery);
});
// We expect to see the latest data
expectedUser = {
// Assert updated data
id: '1',
name: 'Alice in Wonderland',
profile_picture: null,
// Assert that ref points to original singularQuery owner
...createFragmentRef('1', singularQuery),
};
assertFragmentResults([
{ data: expectedUser, shouldUpdate: true },
// { data: expectedUser, shouldUpdate: false }
]);
// Assert it correctly subscribes to new data
TestRenderer.act(() => {
environment.commitPayload(singularQuery, {
node: {
__typename: 'User',
id: '1',
// Update name
name: 'Alice Updated',
},
});
});
assertFragmentResults([
{
data: {
id: '1',
// Assert anme is updated
name: 'Alice Updated',
profile_picture: null,
...createFragmentRef('1', singularQuery),
},
shouldUpdate: true,
},
]);
});
/* removed, useFragmnet don't have shouldUpdate
it("should ignore updates to initially rendered data when fragment pointers change", () => {
const Scheduler = require("scheduler");
const YieldChild = props => {
// NOTE the unstable_yield method will move to the static renderer.
// When React sync runs we need to update this.
Scheduler.unstable_yieldValue(props.children);
return props.children;
};
const YieldyUserComponent = ({ user }) => (
<>
<YieldChild>Hey user,</YieldChild>
<YieldChild>{user.name}</YieldChild>
<YieldChild>with id {user.id}!</YieldChild>
</>
);
// Assert initial render
SingularRenderer = YieldyUserComponent;
renderSingularFragment({ isConcurrent: true });
expectSchedulerToFlushAndYield([
"Hey user,",
"Alice",
["with id ", "1", "!"]
]);
assertFragmentResults([
{
data: {
id: "1",
name: "Alice",
profile_picture: null,
...createFragmentRef("1", singularQuery)
},
shouldUpdate: true
}
]);
const newVariables = { ...singularVariables, id: "200" };
const newQuery = createOperationDescriptor(gqlSingularQuery, newVariables);
TestRenderer.act(() => {
environment.commitPayload(newQuery, {
node: {
__typename: "User",
id: "200",
name: "Foo",
username: "userfoo",
profile_picture: null
}
});
});
TestRenderer.act(() => {
// Pass new fragment ref that points to new ID 200
setSingularOwner(newQuery);
// Flush some of the changes, but don't commit
expectSchedulerToFlushAndYieldThrough(["Hey user,", "Foo"]);
// In Concurrent mode component gets rendered even if not committed
// so we reset our mock here
resetRenderMock();
// Trigger an update for initially rendered data while second
// render is in progress
environment.commitPayload(singularQuery, {
node: {
__typename: "User",
id: "1",
name: "Alice in Wonderland"
}
});
// Assert the component renders the data from newQuery/newVariables,
// ignoring any updates triggered while render was in progress
expectSchedulerToFlushAndYield([
["with id ", "200", "!"],
"Hey user,",
"Foo",
["with id ", "200", "!"]
]);
assertFragmentResults([
{
data: {
id: "200",
name: "Foo",
profile_picture: null,
...createFragmentRef("200", newQuery)
},
shouldUpdate: true
}
]);
// Update latest rendered data
environment.commitPayload(newQuery, {
node: {
__typename: "User",
id: "200",
// Update name
name: "Foo Updated"
}
});
expectSchedulerToFlushAndYield([
"Hey user,",
"Foo Updated",
["with id ", "200", "!"]
]);
assertFragmentResults([
{
data: {
id: "200",
// Assert name is updated
name: "Foo Updated",
profile_picture: null,
...createFragmentRef("200", newQuery)
},
shouldUpdate: true
}
]);
});
});
*/
it('should re-read and resubscribe to fragment when variables change', () => {
renderSingularFragment();
assertFragmentResults([
{
data: {
id: '1',
name: 'Alice',
profile_picture: null,
...createFragmentRef('1', singularQuery),
},
shouldUpdate: true,
},
]);
const newVariables = { ...singularVariables, id: '1', scale: 32 };
const newQuery = createOperationDescriptor(gqlSingularQuery, newVariables);
environment.commitPayload(newQuery, {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
profile_picture: {
uri: 'uri32',
},
username: 'useralice',
},
});
TestRenderer.act(() => {
setSingularOwner(newQuery);
});
const expectedUser = {
id: '1',
name: 'Alice',
profile_picture: {
// Asset updated uri
uri: 'uri32',
},
// Assert that ref now points to newQuery owner
...createFragmentRef('1', newQuery),
};
assertFragmentResults([
{ data: expectedUser, shouldUpdate: true },
//{ data: expectedUser, shouldUpdate: false }
]);
TestRenderer.act(() => {
environment.commitPayload(newQuery, {
node: {
__typename: 'User',
id: '1',
// Update name
name: 'Alice in Wonderland',
},
});
});
assertFragmentResults([
{
data: {
id: '1',
// Assert that name is updated
name: 'Alice in Wonderland',
profile_picture: {
uri: 'uri32',
},
...createFragmentRef('1', newQuery),
},
shouldUpdate: true,
},
]);
});
/* removed, useFragmnet don't have shouldUpdate
it("should ignore updates to initially rendered data when variables change", () => {
const Scheduler = require("scheduler");
const YieldChild = props => {
Scheduler.unstable_yieldValue(props.children);
return props.children;
};
const YieldyUserComponent = ({ user }) => (
<>
<YieldChild>Hey user,</YieldChild>
<YieldChild>
{user.profile_picture && user.profile_picture.uri
? user.profile_picture.uri
: "no uri"}
</YieldChild>
<YieldChild>with id {user.id}!</YieldChild>
</>
);
// Assert initial render
SingularRenderer = YieldyUserComponent;
renderSingularFragment({ isConcurrent: true });
expectSchedulerToFlushAndYield([
"Hey user,",
"no uri",
["with id ", "1", "!"]
]);
assertFragmentResults([
{
data: {
id: "1",
name: "Alice",
profile_picture: null,
...createFragmentRef("1", singularQuery)
},
shouldUpdate: true
}
]);
const newVariables = { ...singularVariables, id: "1", scale: 32 };
const newQuery = createOperationDescriptor(gqlSingularQuery, newVariables);
TestRenderer.act(() => {
environment.commitPayload(newQuery, {
node: {
__typename: "User",
id: "1",
name: "Alice",
username: "useralice",
profile_picture: {
uri: "uri32"
}
}
});
});
TestRenderer.act(() => {
// Pass new fragment ref which contains newVariables
setSingularOwner(newQuery);
// Flush some of the changes, but don't commit
expectSchedulerToFlushAndYieldThrough(["Hey user,", "uri32"]);
// In Concurrent mode component gets rendered even if not committed
// so we reset our mock here
resetRenderMock();
// Trigger an update for initially rendered data while second
// render is in progress
environment.commitPayload(singularQuery, {
node: {
__typename: "User",
id: "1",
// Update name
name: "Alice",
// Update profile_picture value
profile_picture: {
uri: "uri16"
}
}
});
// Assert the component renders the data from newQuery/newVariables,
// ignoring any updates triggered while render was in progress
expectSchedulerToFlushAndYield([
["with id ", "1", "!"],
"Hey user,",
"uri32",
["with id ", "1", "!"]
]);
assertFragmentResults([
{
data: {
id: "1",
name: "Alice",
profile_picture: {
uri: "uri32"
},
...createFragmentRef("1", newQuery)
},
shouldUpdate: true
}
]);
// Update latest rendered data
environment.commitPayload(newQuery, {
node: {
__typename: "User",
id: "1",
// Update name
name: "Alice latest update"
}
});
expectSchedulerToFlushAndYield([
"Hey user,",
"uri32",
["with id ", "1", "!"]
]);
assertFragmentResults([
{
data: {
id: "1",
// Assert name is updated
name: "Alice latest update",
profile_picture: {
uri: "uri32"
},
...createFragmentRef("1", newQuery)
},
shouldUpdate: true
}
]);
});
});
*/
it('should NOT update if fragment refs dont change', () => {
renderSingularFragment();
assertFragmentResults([
{
data: {
id: '1',
name: 'Alice',
profile_picture: null,
...createFragmentRef('1', singularQuery),
},
shouldUpdate: true, // changed in true, useFragmnet don't have shouldUpdate
},
]);
// Force a re-render with the exact same fragment refs
TestRenderer.act(() => {
forceSingularUpdate();
});
assertFragmentResults([
{
data: {
id: '1',
name: 'Alice',
profile_picture: null,
...createFragmentRef('1', singularQuery),
},
// Assert that update to consuming component wont be triggered
shouldUpdate: true, // changed,
},
]);
});
it('should NOT update even if fragment ref changes but doesnt point to a different ID', () => {
renderSingularFragment();
assertFragmentResults([
{
data: {
id: '1',
name: 'Alice',
profile_picture: null,
...createFragmentRef('1', singularQuery),
},
shouldUpdate: true,
},
]);
// Setting a new owner with the same query/variables will cause new
// fragment refs that point to the same IDs to be passed
const newOwner = createOperationDescriptor(gqlSingularQuery, singularVariables);
TestRenderer.act(() => {
setSingularOwner(newOwner);
});
assertFragmentResults([
{
data: {
id: '1',
name: 'Alice',
profile_picture: null,
...createFragmentRef('1', singularQuery),
},
// Assert that update to consuming component wont be triggered
shouldUpdate: true, // changed in true, useFragmnet don't have shouldUpdate
},
]);
});
/* removed suspense test
it("should throw a promise if if data is missing for fragment and request is in flight", () => {
// This prevents console.error output in the test, which is expected
jest.spyOn(console, "error").mockImplementationOnce(() => {});
jest
.spyOn(require("relay-runtime").__internal, "getPromiseForRequestInFlight")
.mockImplementationOnce(() => Promise.resolve());
const missingDataVariables = { ...singularVariables, id: "4" };
const missingDataQuery = createOperationDescriptor(
gqlSingularQuery,
missingDataVariables
);
// Commit a payload with name and profile_picture are missing
environment.commitPayload(missingDataQuery, {
node: {
__typename: "User",
id: "4"
}
});
const renderer = renderSingularFragment({ owner: missingDataQuery });
expect(renderer.toJSON()).toEqual("Singular Fallback");
});
removed, no warning message
it("should throw an error if fragment reference is non-null but read-out data is null", () => {
// Clearing the data in the environment will make it so the fragment ref
// we pass to useFragmentNode points to data that does not exist; we expect
// an error to be thrown in this case.
environment
.getStore()
.getSource()
.clear();
const warning = require("warning");
// $FlowFixMe
warning.mockClear();
renderSingularFragment();
expect(warning).toBeCalledTimes(2);
// $FlowFixMe
const [, warningMessage] = warning.mock.calls[1];
expect(
warningMessage.startsWith(
"Relay: Expected to have been able to read non-null data for fragment `%s`"
)
).toEqual(true);
// $FlowFixMe
warning.mockClear();
});
/* removed, suspense test
it("should warn if data is missing and there are no pending requests", () => {
// This prevents console.error output in the test, which is expected
jest.spyOn(console, "error").mockImplementationOnce(() => {});
const warning = require("warning");
const missingDataVariables = { ...singularVariables, id: "4" };
const missingDataQuery = createOperationDescriptor(
gqlSingularQuery,
missingDataVariables
);
// Commit a payload where name is missing.
environment.commitPayload(missingDataQuery, {
node: {
__typename: "User",
id: "4"
}
});
// $FlowFixMe
warning.mockClear();
TestRenderer.act(() => {
renderSingularFragment({ owner: missingDataQuery });
});
// Assert warning message
expect(warning).toHaveBeenCalledTimes(1);
// $FlowFixMe
const [, warningMessage, ...warningArgs] = warning.mock.calls[0];
expect(
warningMessage.startsWith(
"Relay: Tried reading fragment `%s` " +
"declared in `%s`, but it has " +
"missing data and its parent query `%s` is not being fetched."
)
).toEqual(true);
expect(warningArgs).toEqual([
"UserFragment",
"TestDisplayName",
"UserQuery",
"UserQuery"
]);
// Assert render output with missing data
assertFragmentResults([
{
data: {
id: "4",
name: undefined,
profile_picture: undefined,
...createFragmentRef("4", missingDataQuery)
},
shouldUpdate: true
}
]);
});
*/
it('should subscribe for updates even if there is missing data', () => {
// This prevents console.error output in the test, which is expected
jest.spyOn(console, 'error').mockImplementationOnce(() => {});
const missingDataVariables = { ...singularVariables, id: '4' };
const missingDataQuery = createOperationDescriptor(gqlSingularQuery, missingDataVariables);
// Commit a payload where name is missing.
environment.commitPayload(missingDataQuery, {
node: {
__typename: 'User',
id: '4',
},
});
renderSingularFragment({ owner: missingDataQuery });
// Assert render output with missing data
assertFragmentResults([
{
data: {
id: '4',
name: undefined,
profile_picture: undefined,
...createFragmentRef('4', missingDataQuery),
},
shouldUpdate: true,
},
]);
// Commit a payload with updated name.
environment.commitPayload(missingDataQuery, {
node: {
__typename: 'User',
id: '4',
name: 'Mark',
},
});
// Assert render output with updated data
assertFragmentResults([
{
data: {
id: '4',
name: 'Mark',
profile_picture: undefined,
...createFragmentRef('4', missingDataQuery),
},
shouldUpdate: true,
},
]);
});
/*
describe("disableStoreUpdates", () => {
it("does not listen to store updates after disableStoreUpdates is called", () => {
renderSingularFragment();
assertFragmentResults([
{
data: {
id: "1",
name: "Alice",
profile_picture: null,
...createFragmentRef("1", singularQuery)
},
shouldUpdate: true
}
]);
disableStoreUpdates();
// Update data in the store
environment.commitPayload(singularQuery, {
node: {
__typename: "User",
id: "1",
name: "Alice updated"
}
});
// Assert that component did not re-render
TestRenderer.act(() => jest.runAllImmediates());
expect(renderSpy).toBeCalledTimes(0);
});
it("re-renders with latest data after re-enabling updates, if any updates were missed", () => {
renderSingularFragment();
assertFragmentResults([
{
data: {
id: "1",
name: "Alice",
profile_picture: null,
...createFragmentRef("1", singularQuery)
},
shouldUpdate: true
}
]);
disableStoreUpdates();
// Update data in the store
environment.commitPayload(singularQuery, {
node: {
__typename: "User",
id: "1",
name: "Alice updated"
}
});
// Assert that component did not re-render while updates are disabled
TestRenderer.act(() => {
jest.runAllImmediates();
});
expect(renderSpy).toBeCalledTimes(0);
TestRenderer.act(() => {
enableStoreUpdates();
});
// Assert that component re-renders with latest updated data
assertFragmentResults([
{
data: {
id: "1",
name: "Alice updated",
profile_picture: null,
...createFragmentRef("1", singularQuery)
},
shouldUpdate: true
}
]);
});
it("does not re-render after re-enabling updates, if no updates were missed", () => {
renderSingularFragment();
assertFragmentResults([
{
data: {
id: "1",
name: "Alice",
profile_picture: null,
...createFragmentRef("1", singularQuery)
},
shouldUpdate: true
}
]);
disableStoreUpdates();
expect(renderSpy).toBeCalledTimes(0);
enableStoreUpdates();
// Assert that component did not re-render after enabling updates
TestRenderer.act(() => jest.runAllImmediates());
expect(renderSpy).toBeCalledTimes(0);
});
it("does not re-render after re-enabling updates, if data did not change", () => {
renderSingularFragment();
assertFragmentResults([
{
data: {
id: "1",
name: "Alice",
profile_picture: null,
...createFragmentRef("1", singularQuery)
},
shouldUpdate: true
}
]);
disableStoreUpdates();
environment.commitPayload(singularQuery, {
node: {
__typename: "User",
id: "1",
name: "Alice"
}
});
TestRenderer.act(() => jest.runAllImmediates());
expect(renderSpy).toBeCalledTimes(0);
enableStoreUpdates();
// Assert that component did not re-render after enabling updates
TestRenderer.act(() => jest.runAllImmediates());
expect(renderSpy).toBeCalledTimes(0);
});
});
*/
it('should invoke singular subscribe handler without error when data is available', (done) => {
subscribeSingularFragment({
onData: (data) => {
expect(data).toEqual({
id: '1',
name: 'Alice',
profile_picture: null,
...createFragmentRef('1', singularQuery),
});
done();
},
});
assertFragmentResults([]);
});
it('should invoke singular subscribe handler when fragment data changes again', (done) => {
let counter = 0;
subscribeSingularFragment({
onData: (data) => {
counter = counter + 1;
if (counter === 1) {
expect(data).toEqual({
id: '1',
name: 'Alice',
profile_picture: null,
...createFragmentRef('1', singularQuery),
});
} else if (counter === 2) {
expect(data).toEqual({
id: '1',
// Assert that name is updated
name: 'Alice in Wonderland',
profile_picture: null,
...createFragmentRef('1', singularQuery),
});
done();
} else {
done.fail('More invocations that expected');
}
},
});
assertFragmentResults([]);
TestRenderer.act(() => {
environment.commitPayload(singularQuery, {
node: {
__typename: 'User',
id: '1',
// Update name
name: 'Alice in Wonderland',
},
});
});
assertFragmentResults([]);
});
it('should invoke singular subscribe handler when fragment params changes', (done) => {
let counter = 0;
const newOwner = createOperationDescriptor(gqlSingularQuery, { ...singularVariables, id: '2' });
subscribeSingularFragment({
onData: (data) => {
counter = counter + 1;
if (counter === 1) {
expect(data).toEqual({
id: '1',
name: 'Alice',
profile_picture: null,
...createFragmentRef('1', singularQuery),
});
} else if (counter === 2) {
expect(data).toEqual({
id: '2',
// Assert that name is updated
name: 'Bob',
profile_picture: null,
...createFragmentRef('2', newOwner),
});
done();
} else {
done.fail('More invocations that expected');
}
},
});
assertFragmentResults([]);
TestRenderer.act(() => {
setSingularOwner(newOwner);
});
assertFragmentResults([]);
}); | the_stack |
import type * as Database from 'better-sqlite3';
import {Utils, FS, ProcessManager, Repl} from '../lib';
import {Config} from './config-loader';
import * as path from 'path';
/** Max friends per user */
export const MAX_FRIENDS = 100;
/** Max friend requests. */
export const MAX_REQUESTS = 6;
export const DEFAULT_FILE = `${__dirname}/../databases/friends.db`;
const REQUEST_EXPIRY_TIME = 30 * 24 * 60 * 60 * 1000;
const PM_TIMEOUT = 30 * 60 * 1000;
export interface DatabaseRequest {
statement: string;
type: 'all' | 'get' | 'run' | 'transaction';
data: AnyObject | any[];
}
export interface DatabaseResult {
/** Specify this to return an error message to the user */
error?: string;
result?: any;
}
export interface Friend {
/** Always the same as Friend#friend. Use whichever you want. */
userid: ID;
/** Always the same as Friend#userid. Use whichever you want. */
friend: ID;
send_login_data: number;
last_login: number;
public_list: number;
allowing_login: number;
}
/** Like Chat.ErrorMessage, but made for the subprocess so we can throw errors to the user not using errorMessage
* because errorMessage crashes when imported (plus we have to spawn dex, etc, all unnecessary - this is easier)
*/
export class FailureMessage extends Error {
constructor(message: string) {
super(message);
this.name = 'FailureMessage';
Error.captureStackTrace(this, FailureMessage);
}
}
export function sendPM(message: string, to: string, from = '&') {
const senderID = toID(to);
const receiverID = toID(from);
const sendingUser = Users.get(senderID);
const receivingUser = Users.get(receiverID);
const fromIdentity = sendingUser ? sendingUser.getIdentity() : ` ${senderID}`;
const toIdentity = receivingUser ? receivingUser.getIdentity() : ` ${receiverID}`;
if (from === '&') {
return sendingUser?.send(`|pm|&|${toIdentity}|${message}`);
}
if (sendingUser) {
sendingUser.send(`|pm|${fromIdentity}|${toIdentity}|${message}`);
}
if (receivingUser) {
receivingUser.send(`|pm|${fromIdentity}|${toIdentity}|${message}`);
}
}
function canPM(sender: User, receiver: User | null) {
if (!receiver || !receiver.settings.blockPMs) return true;
if (receiver.settings.blockPMs === true) return sender.can('lock');
if (receiver.settings.blockPMs === 'friends') return false;
return Users.globalAuth.atLeast(sender, receiver.settings.blockPMs);
}
export class FriendsDatabase {
file: string;
constructor(file: string = DEFAULT_FILE) {
this.file = file === ':memory:' ? file : path.resolve(file);
}
async updateUserCache(user: User) {
user.friends = new Set(); // we clear to account for users who may have been deleted
const friends = await this.getFriends(user.id);
for (const friend of friends) {
user.friends.add(friend.userid);
}
return user.friends;
}
static setupDatabase(fileName?: string) {
const file = fileName || process.env.filename || DEFAULT_FILE;
const exists = FS(file).existsSync() || file === ':memory:';
const database: Database.Database = new (require('better-sqlite3'))(file);
if (!exists) {
database.exec(FS('databases/schemas/friends.sql').readSync());
} else {
let val;
try {
val = database.prepare(`SELECT val FROM database_settings WHERE name = 'version'`).get().val;
} catch {}
const actualVersion = FS(`databases/migrations/friends`).readdirIfExistsSync().length;
if (val === undefined) {
// hasn't been set up before, write new version.
database.exec(FS('databases/schemas/friends.sql').readSync());
}
if (typeof val === 'number' && val !== actualVersion) {
throw new Error(`Friends DB is out of date, please migrate to latest version.`);
}
}
database.exec(FS(`databases/schemas/friends-startup.sql`).readSync());
for (const k in FUNCTIONS) {
database.function(k, FUNCTIONS[k]);
}
for (const k in ACTIONS) {
try {
statements[k] = database.prepare(ACTIONS[k as keyof typeof ACTIONS]);
} catch (e: any) {
throw new Error(`Friends DB statement crashed: ${ACTIONS[k as keyof typeof ACTIONS]} (${e.message})`);
}
}
for (const k in TRANSACTIONS) {
transactions[k] = database.transaction(TRANSACTIONS[k]);
}
statements.expire.run();
return database;
}
async getFriends(userid: ID): Promise<Friend[]> {
return (await this.all('get', [userid, MAX_FRIENDS])) || [];
}
async getRequests(user: User) {
const sent: Set<string> = new Set();
const received: Set<string> = new Set();
if (user.settings.blockFriendRequests) {
// delete any pending requests that may have been sent to them while offline
// we used to return but we will not since you can send requests while blocking
await this.run('deleteReceivedRequests', [user.id]);
}
const sentResults = await this.all('getSent', [user.id]);
if (sentResults === null) return {sent, received};
for (const request of sentResults) {
sent.add(request.receiver);
}
const receivedResults = await this.all('getReceived', [user.id]) || [];
if (!Array.isArray(receivedResults)) {
Monitor.crashlog(new Error("Malformed results received"), 'A friends process', {
user: user.id,
result: JSON.stringify(receivedResults),
});
return {received, sent};
}
for (const request of receivedResults) {
received.add(request.sender);
}
return {sent, received};
}
all(statement: string, data: any[] | AnyObject) {
return this.query({type: 'all', data, statement});
}
transaction(statement: string, data: any[] | AnyObject) {
return this.query({data, statement, type: 'transaction'});
}
run(statement: string, data: any[] | AnyObject) {
return this.query({statement, data, type: 'run'});
}
get(statement: string, data: any[] | AnyObject) {
return this.query({statement, data, type: 'get'});
}
private async query(input: DatabaseRequest) {
const process = PM.acquire();
if (!process || !Config.usesqlite) {
return {result: null};
}
const result = await process.query(input);
if (result.error) {
throw new Chat.ErrorMessage(result.error);
}
return result.result;
}
async request(user: User, receiverID: ID) {
const receiver = Users.getExact(receiverID);
if (receiverID === user.id || receiver?.previousIDs.includes(user.id)) {
throw new Chat.ErrorMessage(`You can't friend yourself.`);
}
if (receiver?.settings.blockFriendRequests) {
throw new Chat.ErrorMessage(`${receiver.name} is blocking friend requests.`);
}
let buf = Utils.html`/uhtml sent-${user.id},<button class="button" name="send" value="/friends accept ${user.id}">Accept</button> | `;
buf += Utils.html`<button class="button" name="send" value="/friends reject ${user.id}">Deny</button><br /> `;
buf += `<small>(You can also stop this user from sending you friend requests with <code>/ignore</code>)</small>`;
const disclaimer = (
`/raw <small>Note: If this request is accepted, your friend will be notified when you come online, ` +
`and you will be notified when they do, unless you opt out of receiving them.</small>`
);
if (receiver?.settings.blockFriendRequests) {
throw new Chat.ErrorMessage(`This user is blocking friend requests.`);
}
if (!canPM(user, receiver)) {
throw new Chat.ErrorMessage(`This user is blocking PMs, and cannot be friended right now.`);
}
const result = await this.transaction('send', [user.id, receiverID]);
if (receiver) {
sendPM(`/raw <span class="username">${user.name}</span> sent you a friend request!`, receiver.id);
sendPM(buf, receiver.id);
sendPM(disclaimer, receiver.id);
}
sendPM(
`/nonotify You sent a friend request to ${receiver?.connected ? receiver.name : receiverID}!`,
user.name
);
sendPM(
`/uhtml undo-${receiverID},<button class="button" name="send" value="/friends undorequest ${Utils.escapeHTML(receiverID)}">` +
`<i class="fa fa-undo"></i> Undo</button>`, user.name
);
sendPM(disclaimer, user.id);
return result;
}
async removeRequest(receiverID: ID, senderID: ID) {
if (!senderID) throw new Chat.ErrorMessage(`Invalid sender username.`);
if (!receiverID) throw new Chat.ErrorMessage(`Invalid receiver username.`);
return this.run('deleteRequest', [senderID, receiverID]);
}
async approveRequest(receiverID: ID, senderID: ID) {
return this.transaction('accept', [senderID, receiverID]);
}
async removeFriend(userid: ID, friendID: ID) {
if (!friendID || !userid) throw new Chat.ErrorMessage(`Invalid usernames supplied.`);
const result = await this.run('delete', {user1: userid, user2: friendID});
if (result.changes < 1) {
throw new Chat.ErrorMessage(`You do not have ${friendID} friended.`);
}
}
writeLogin(user: ID) {
return this.run('login', [user, Date.now(), Date.now()]);
}
hideLoginData(id: ID) {
return this.run('hideLogin', [id, Date.now()]);
}
allowLoginData(id: ID) {
return this.run('showLogin', [id]);
}
async getLastLogin(userid: ID) {
const result = await this.get('checkLastLogin', [userid]);
return parseInt(result?.['last_login']) || null;
}
async getSettings(userid: ID) {
return (await this.get('getSettings', [userid])) || {};
}
setHideList(userid: ID, setting: boolean) {
const num = setting ? 1 : 0;
// name, send_login_data, last_login, public_list
return this.run('toggleList', [userid, num, num]);
}
}
const statements: {[k: string]: Database.Statement} = {};
const transactions: {[k: string]: Database.Transaction} = {};
const ACTIONS = {
add: (
`REPLACE INTO friends (user1, user2) VALUES ($user1, $user2) ON CONFLICT (user1, user2) ` +
`DO UPDATE SET user1 = $user1, user2 = $user2`
),
get: (
`SELECT * FROM friends_simplified f LEFT JOIN friend_settings fs ON f.friend = fs.userid WHERE f.userid = ? LIMIT ?`
),
delete: `DELETE FROM friends WHERE (user1 = $user1 AND user2 = $user2) OR (user1 = $user2 AND user2 = $user1)`,
getSent: `SELECT receiver, sender FROM friend_requests WHERE sender = ?`,
getReceived: `SELECT receiver, sender FROM friend_requests WHERE receiver = ?`,
insertRequest: `INSERT INTO friend_requests(sender, receiver, sent_at) VALUES (?, ?, ?)`,
deleteRequest: `DELETE FROM friend_requests WHERE sender = ? AND receiver = ?`,
deleteReceivedRequests: `DELETE FROM friend_requests WHERE receiver = ?`,
findFriendship: `SELECT * FROM friends WHERE (user1 = $user1 AND user2 = $user2) OR (user2 = $user1 AND user1 = $user2)`,
findRequest: (
`SELECT count(*) as num FROM friend_requests WHERE ` +
`(sender = $user1 AND receiver = $user2) OR (sender = $user2 AND receiver = $user1)`
),
countRequests: `SELECT count(*) as num FROM friend_requests WHERE (sender = ? OR receiver = ?)`,
login: (
`INSERT INTO friend_settings (userid, send_login_data, last_login, public_list) VALUES (?, 0, ?, 0) ` +
`ON CONFLICT (userid) DO UPDATE SET last_login = ?`
),
checkLastLogin: `SELECT last_login FROM friend_settings WHERE userid = ?`,
deleteLogin: `UPDATE friend_settings SET last_login = 0 WHERE userid = ?`,
expire: (
`DELETE FROM friend_requests WHERE EXISTS` +
`(SELECT sent_at FROM friend_requests WHERE should_expire(sent_at) = 1)`
),
hideLogin: ( // this works since if the insert works, they have no data, which means no public_list
`INSERT INTO friend_settings (userid, send_login_data, last_login, public_list) VALUES (?, 1, ?, 0) ` +
`ON CONFLICT (userid) DO UPDATE SET send_login_data = 1`
),
showLogin: `DELETE FROM friend_settings WHERE userid = ? AND send_login_data = 1`,
countFriends: `SELECT count(*) as num FROM friends WHERE (user1 = ? OR user2 = ?)`,
getSettings: `SELECT * FROM friend_settings WHERE userid = ?`,
toggleList: (
`INSERT INTO friend_settings (userid, send_login_data, last_login, public_list) VALUES (?, 0, 0, ?) ` +
`ON CONFLICT (userid) DO UPDATE SET public_list = ?`
),
};
const FUNCTIONS: {[k: string]: (...input: any[]) => any} = {
'should_expire': (sentTime: number) => {
if (Date.now() - sentTime > REQUEST_EXPIRY_TIME) return 1;
return 0;
},
};
const TRANSACTIONS: {[k: string]: (input: any[]) => DatabaseResult} = {
send: requests => {
for (const request of requests) {
const [senderID, receiverID] = request;
const hasSentRequest = statements.findRequest.get({user1: senderID, user2: receiverID})['num'];
const friends = statements.countFriends.get(senderID, senderID)['num'];
const totalRequests = statements.countRequests.get(senderID, senderID)['num'];
if (friends >= MAX_FRIENDS) {
throw new FailureMessage(`You are at the maximum number of friends.`);
}
const existingFriendship = statements.findFriendship.all({user1: senderID, user2: receiverID});
if (existingFriendship.length) {
throw new FailureMessage(`You are already friends with '${receiverID}'.`);
}
if (hasSentRequest) {
throw new FailureMessage(`You have already sent a friend request to '${receiverID}'.`);
}
if (totalRequests >= MAX_REQUESTS) {
throw new FailureMessage(
`You already have ${MAX_REQUESTS} outgoing friend requests. Use "/friends view sent" to see your outgoing requests.`
);
}
statements.insertRequest.run(senderID, receiverID, Date.now());
}
return {result: []};
},
add: requests => {
for (const request of requests) {
const [senderID, receiverID] = request;
statements.add.run({user1: senderID, user2: receiverID});
}
return {result: []};
},
accept: requests => {
for (const request of requests) {
const [senderID, receiverID] = request;
const friends = statements.get.all(receiverID, 101);
if (friends?.length >= MAX_FRIENDS) {
throw new FailureMessage(`You are at the maximum number of friends.`);
}
const {result} = TRANSACTIONS.removeRequest([request]);
if (!result.length) throw new FailureMessage(`You have no request pending from ${senderID}.`);
TRANSACTIONS.add([request]);
}
return {result: []};
},
removeRequest: requests => {
const result = [];
for (const request of requests) {
const [to, from] = request;
const {changes} = statements.deleteRequest.run(to, from);
if (changes) result.push(changes);
}
return {result};
},
};
export const PM = new ProcessManager.QueryProcessManager<DatabaseRequest, DatabaseResult>(module, query => {
const {type, statement, data} = query;
const start = Date.now();
const result: DatabaseResult = {};
try {
switch (type) {
case 'run':
result.result = statements[statement].run(data);
break;
case 'get':
result.result = statements[statement].get(data);
break;
case 'transaction':
result.result = transactions[statement]([data]);
break;
case 'all':
result.result = statements[statement].all(data);
break;
}
} catch (e: any) {
if (!e.name.endsWith('FailureMessage')) {
result.error = "Sorry! The database process crashed. We've been notified and will fix this.";
Monitor.crashlog(e, "A friends database process", query);
} else {
result.error = e.message;
}
return result;
}
const delta = Date.now() - start;
if (delta > 1000) {
Monitor.slow(`[Slow friends list query] ${JSON.stringify(query)}`);
}
return result;
}, PM_TIMEOUT, message => {
if (message.startsWith('SLOW\n')) {
Monitor.slow(message.slice(5));
}
});
if (require.main === module) {
global.Config = (require as any)('./config-loader').Config;
if (Config.usesqlite) {
FriendsDatabase.setupDatabase();
}
global.Monitor = {
crashlog(error: Error, source = 'A friends database process', details: AnyObject | null = null) {
const repr = JSON.stringify([error.name, error.message, source, details]);
process.send!(`THROW\n@!!@${repr}\n${error.stack}`);
},
slow(message: string) {
process.send!(`CALLBACK\nSLOW\n${message}`);
},
};
process.on('uncaughtException', err => {
if (Config.crashguard) {
Monitor.crashlog(err, 'A friends child process');
}
});
// eslint-disable-next-line no-eval
Repl.start(`friends-${process.pid}`, cmd => eval(cmd));
} else if (!process.send) {
PM.spawn(Config.friendsprocesses || 1);
} | the_stack |
import * as TKUnit from '../../tk-unit';
import * as helper from '../../ui-helper';
import { Builder } from '@nativescript/core/ui/builder';
import { Label } from '@nativescript/core/ui/label';
import { Button } from '@nativescript/core/ui/button';
import { Page } from '@nativescript/core/ui/page';
import { View, isIOS } from '@nativescript/core';
import { fromObject } from '@nativescript/core/data/observable';
import { Frame } from '@nativescript/core/ui/frame';
// >> actionbar-common-require
import * as actionBarModule from '@nativescript/core/ui/action-bar';
// << actionbar-common-require
export function test_actionItem_inherit_bindingContext() {
let page: Page;
let label: Label;
const context = { text: 'item' };
const pageFactory = function (): Page {
page = new Page();
page.bindingContext = context;
const actionItem = new actionBarModule.ActionItem();
actionItem.bind({
sourceProperty: 'text',
targetProperty: 'text',
});
page.actionBar.actionItems.addItem(actionItem);
label = new Label();
label.text = 'Text';
page.content = label;
return page;
};
helper.navigate(pageFactory);
TKUnit.assertEqual(page.actionBar.actionItems.getItemAt(0).text, 'item', 'actionItem.text');
}
export function test_actionBar_inherit_bindingContext_inXML() {
const p = <Page>Builder.parse('<Page> <Page.actionBar> <ActionBar title="{{ myProp }} " /> </Page.actionBar> </Page>');
p.bindingContext = { myProp: 'success' };
TKUnit.assertEqual(p.actionBar.title, 'success', 'actionBar.title');
}
export function test_actionItem_inherit_bindingContext_inXML() {
const p = <Page>Builder.parse('<Page> <Page.actionBar> <ActionBar> <ActionBar.actionItems>' + '<ActionItem text="{{ myProp }} " />' + '</ActionBar.actionItems> </ActionBar> </Page.actionBar> </Page>');
p.bindingContext = { myProp: 'success' };
const actionItem = p.actionBar.actionItems.getItemAt(0);
TKUnit.assertEqual(actionItem.text, 'success', 'actionItem.text');
}
export function test_actionItem_page_property_inXML() {
const p = <Page>Builder.parse('<Page> <Page.actionBar> <ActionBar> <ActionBar.actionItems>' + '<ActionItem text="test" />' + '</ActionBar.actionItems> </ActionBar> </Page.actionBar> </Page>');
const actionItem = p.actionBar.actionItems.getItemAt(0);
TKUnit.assertEqual(actionItem.page, p, 'actionItem.page');
}
export function test_actionItem_actionView_inXML() {
const p = <Page>Builder.parse('<Page> <Page.actionBar> <ActionBar> <ActionItem> <ActionItem.actionView>' + '<Label/>' + '</ActionItem.actionView> </ActionItem> </ActionBar> </Page.actionBar> </Page>');
const label = <Label>p.actionBar.actionItems.getItemAt(0).actionView;
TKUnit.assert(label instanceof Label, 'ActionItem.actionView not loaded correctly');
}
export function test_actionItem_actionView_inherit_bindingContext_inXML() {
const p = <Page>Builder.parse('<Page> <Page.actionBar> <ActionBar> <ActionItem> <ActionItem.actionView>' + '<Label text="{{ myProp }} " />' + '</ActionItem.actionView> </ActionItem> </ActionBar> </Page.actionBar> </Page>');
p.bindingContext = { myProp: 'success' };
const label = <Label>p.actionBar.actionItems.getItemAt(0).actionView;
TKUnit.assert(label instanceof Label, 'ActionItem.actionView not loaded correctly');
TKUnit.assertEqual(label.text, 'success', 'ActionItem.actionView');
}
export function test_ActionBar_is_not_empty_when_actionItem_actionView_is_set() {
const p = <Page>Builder.parse('<Page> <Page.actionBar> <ActionBar> <ActionItem> <ActionItem.actionView>' + '<Label text="test" />' + '</ActionItem.actionView> </ActionItem> </ActionBar> </Page.actionBar> </Page>');
TKUnit.assertFalse(p.actionBar._isEmpty(), 'ActionItem.actionView is set but ActionBar reports empty');
}
export function test_navigationButton_inherit_bindingContext_inXML() {
const p = <Page>Builder.parse('<Page> <Page.actionBar> <ActionBar>' + '<NavigationButton text="{{ myProp }} " />' + '</ActionBar> </Page.actionBar> </Page>');
p.bindingContext = { myProp: 'success' };
const navButton = p.actionBar.navigationButton;
TKUnit.assertEqual(navButton.text, 'success', 'actionItem.text');
}
export function test_titleView_inherit_bindingContext_inXML() {
const p = <Page>Builder.parse('<Page> <Page.actionBar> <ActionBar> <ActionBar.titleView>' + '<Button text="{{ myProp }} " />' + '</ActionBar.titleView> </ActionBar> </Page.actionBar> </Page>');
p.bindingContext = { myProp: 'success' };
const centerBtn = <Button>p.actionBar.titleView;
TKUnit.assert(centerBtn instanceof Button, 'titleView not loaded correctly');
TKUnit.assertEqual(centerBtn.text, 'success', 'actionItem.text');
}
export function test_titleView_inXML() {
const p = <Page>Builder.parse('<Page> <Page.actionBar> <ActionBar> <ActionBar.titleView>' + '<Button/>' + '</ActionBar.titleView> </ActionBar> </Page.actionBar> </Page>');
const centerBtn = <Button>p.actionBar.titleView;
TKUnit.assert(centerBtn instanceof Button, 'titleView not loaded correctly');
}
export function test_titleView_inXML_short_definition() {
const p = <Page>Builder.parse('<Page> <Page.actionBar> <ActionBar>' + '<Button/>' + '</ActionBar> </Page.actionBar> </Page>');
const centerBtn = <Button>p.actionBar.titleView;
TKUnit.assert(centerBtn instanceof Button, 'titleView not loaded correctly');
}
export function test_ActionBar_is_not_empty_when_titleView_is_set() {
const p = <Page>Builder.parse('<Page> <Page.actionBar> <ActionBar> <ActionBar.titleView>' + '<Button text="test" />' + '</ActionBar.titleView> </ActionBar> </Page.actionBar> </Page>');
TKUnit.assertFalse(p.actionBar._isEmpty(), 'titleView is set but ActionBar reports empty');
}
export function test_ActionBarItemBindingToEvent() {
const p = <Page>Builder.parse('<Page><Page.actionBar><ActionBar><ActionBar.actionItems><ActionItem tap="{{ test }}"/></ActionBar.actionItems></ActionBar></Page.actionBar></Page>');
const testAction = function (views: Array<View>) {
const page = <Page>views[0];
let firstHandlerCallCounter = 0;
let secondHandlerCallCounter = 0;
const firstHandler = function () {
firstHandlerCallCounter++;
};
const secondHandler = function () {
secondHandlerCallCounter++;
};
page.bindingContext = fromObject({ test: firstHandler });
const actionBarItem = page.actionBar.actionItems.getItemAt(0);
TKUnit.assertEqual((<any>actionBarItem)._observers['tap'].length, 1, 'There should be only one listener');
TKUnit.assertEqual((<any>actionBarItem)._observers['tap'][0].callback + '', firstHandler.toString(), 'First handler is not equal');
p.bindingContext.set('test', secondHandler);
TKUnit.assertEqual((<any>actionBarItem)._observers['tap'].length, 1, 'There should be only one listener');
TKUnit.assertEqual((<any>actionBarItem)._observers['tap'][0].callback + '', secondHandler.toString(), 'Second handler is not equal');
};
helper.navigate(function () {
return p;
});
testAction([p]);
}
export function test_Setting_ActionItems_doesnt_thrown() {
let page: Page;
let label: Label;
let gotException = false;
const pageFactory = function (): Page {
page = new Page();
const actionItem = new actionBarModule.ActionItem();
actionItem.text = 'Item';
page.actionBar.actionItems.addItem(actionItem);
label = new Label();
label.text = 'Text';
page.content = label;
return page;
};
try {
helper.navigate(pageFactory);
} catch (e) {
gotException = true;
}
TKUnit.assert(!gotException, 'Expected: false, Actual: ' + gotException);
}
export function test_Setting_ActionItemsWithNumberAsText_doesnt_thrown() {
let gotException = false;
try {
helper.navigateToModule('ui/action-bar/ActionBar_NumberAsText');
} catch (e) {
gotException = true;
}
TKUnit.assert(!gotException, 'Expected: false, Actual: ' + gotException);
}
export function test_ActionBar_set_title_as_number_doesnt_thrown() {
let gotException = false;
try {
helper.navigateToModule('ui/action-bar/ActionBar_NumberAsTitle');
} catch (e) {
gotException = true;
}
TKUnit.assert(!gotException, 'Expected: false, Actual: ' + gotException);
}
export function test_CanDefineEverythingAsContentBetweenTheTwoTags() {
helper.navigateToModuleAndRunTest('ui/action-bar/ActionBar_BetweenTags', undefined, (page: Page) => {
TKUnit.assertNotNull(page.actionBar.navigationButton);
TKUnit.assertEqual(page.actionBar.navigationButton.text, 'nb');
TKUnit.assertNull(page.actionBar.title);
TKUnit.assertNotNull(page.actionBar.titleView);
TKUnit.assertTrue(page.actionBar.titleView instanceof Label);
TKUnit.assertEqual((<Label>page.actionBar.titleView).text, 'tv');
TKUnit.assertNotNull(page.actionBar.actionItems);
const items = page.actionBar.actionItems.getItems();
TKUnit.assertEqual(items.length, 3);
TKUnit.assertEqual(items[0].text, 'i1');
TKUnit.assertEqual(items[1].text, 'i2');
TKUnit.assertEqual(items[2].text, 'i3');
});
}
export function test_LoadedEventsOrder() {
const loadedEvents = new Array<string>();
const pageFactory = function (): Page {
const page = new Page();
page.on(View.loadedEvent, () => {
loadedEvents.push('page');
});
page.actionBar.on(View.loadedEvent, () => {
loadedEvents.push('action-bar');
});
const content = new Label();
content.on(View.loadedEvent, () => {
loadedEvents.push('content');
});
page.content = content;
return page;
};
helper.navigate(pageFactory);
TKUnit.arrayAssert(loadedEvents, new Array<string>('content', 'action-bar', 'page'));
}
export function test_LoadedEventsOrder_WithoutPageContent() {
const loadedEvents = new Array<string>();
const pageFactory = function (): Page {
const page = new Page();
page.on(View.loadedEvent, () => {
loadedEvents.push('page');
});
page.actionBar.on(View.loadedEvent, () => {
loadedEvents.push('action-bar');
});
return page;
};
helper.navigate(pageFactory);
TKUnit.arrayAssert(loadedEvents, new Array<string>('action-bar', 'page'));
}
export function test_ActionBarVisibility_Never_ShouldNotShowDeclaredActionBar() {
const frame = Frame.topmost();
frame.actionBarVisibility = 'never';
const page = <Page>Builder.parse(
`<Page>
<ActionBar>
<ActionBar.titleView>
<Button text="test" />
</ActionBar.titleView>
</ActionBar>
</Page>
`
);
helper.navigate(() => page);
let actionBarHidden = false;
if (isIOS) {
actionBarHidden = page.actionBar.nativeView.hidden;
} else {
actionBarHidden = !page.actionBar.nativeView.isShown();
}
TKUnit.assertTrue(actionBarHidden, `ActionBar hidden: expected true, actual ${actionBarHidden}`);
// restore default actionBarVisibility
frame.actionBarVisibility = 'auto';
}
export function test_ActionBarVisibility_Always_ShouldShownHiddenActionBar() {
const frame = Frame.topmost();
frame.actionBarVisibility = 'always';
const page = <Page>Builder.parse(
`<Page actionBarHidden="true">
<ActionBar>
<ActionBar.titleView>
<Button text="test" />
</ActionBar.titleView>
</ActionBar>
</Page>
`
);
helper.navigate(() => page);
let actionBarHidden = false;
if (isIOS) {
actionBarHidden = page.actionBar.nativeView.hidden;
} else {
actionBarHidden = !page.actionBar.nativeView.isShown();
}
TKUnit.assertFalse(actionBarHidden, `ActionBar hidden: expected false, actual ${actionBarHidden}`);
// restore default actionBarVisibility
frame.actionBarVisibility = 'auto';
}
export function test_ActionBarVisibility_Auto_ShouldRespectPageActionBarHiddenProperty() {
const frame = Frame.topmost();
frame.actionBarVisibility = 'auto';
const page = <Page>Builder.parse(
`<Page actionBarHidden="true">
<ActionBar>
<ActionBar.titleView>
<Button text="test" />
</ActionBar.titleView>
</ActionBar>
</Page>
`
);
helper.navigate(() => page);
let actionBarHidden = false;
if (isIOS) {
actionBarHidden = page.actionBar.nativeView.hidden;
} else {
actionBarHidden = !page.actionBar.nativeView.isShown();
}
TKUnit.assertTrue(actionBarHidden, `ActionBar hidden: expected true, actual ${actionBarHidden}`);
// restore default actionBarVisibility
frame.actionBarVisibility = 'auto';
}
export function test_setId() {
const pageFactory = function (): Page {
const page = new Page();
page.actionBar.id = 'myId';
return page;
};
try {
helper.navigate(pageFactory);
} catch (e) {
TKUnit.assert(false, "Failed to apply property 'id' to actionBar before its nativeView is ready.");
}
}
export function createPageAndNavigate() {
let page: Page;
const pageFactory = function (): Page {
page = new Page();
const label = new Label();
label.text = 'Text';
page.content = label;
return page;
};
helper.navigate(pageFactory);
return page;
}
export function test_recycling() {
helper.nativeView_recycling_test(() => new actionBarModule.ActionBar());
} | the_stack |
import {
AfterViewChecked,
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ComponentFactoryResolver,
ComponentRef,
ContentChildren,
Directive,
ElementRef,
EmbeddedViewRef,
EventEmitter,
HostListener,
Injector,
Input,
Output,
QueryList,
TemplateRef,
Type,
ViewChild,
ViewChildren,
ViewContainerRef
} from '@angular/core';
import {JigsawTabPane} from "./tab-pane";
import {JigsawTabContent, JigsawTabLabel, TabTitleInfo} from "./tab-item";
import {AbstractJigsawComponent, IDynamicInstantiatable} from "../../common/common";
import {Subscription} from "rxjs";
import {RequireMarkForCheck} from "../../common/decorator/mark-for-check";
import {IJigsawTabTitleRenderer} from "./tab-renderer";
export type TabBarData = {
/**
* 字符串类型的标题
*/
label?: string,
/**
* 支持包含简单标签的HTML片段
*/
html?: string,
/**
* 当配置了HTML内容时,搭配该属性,可以指定HTML运行的上下文
*/
htmlContext?: any,
disabled?: boolean,
hidden?: boolean,
/**
* 显示在文本前面的图标
*/
icon?: string,
renderer?: IJigsawTabTitleRenderer
}
@Directive()
export abstract class JigsawTabBase extends AbstractJigsawComponent implements AfterViewInit, AfterViewChecked {
protected constructor(protected _changeDetector: ChangeDetectorRef,
// @RequireMarkForCheck 需要用到,勿删
protected _injector: Injector) {
super();
}
/**
* @internal
*/
public _$selectedIndex: number;
/**
* 当前选中的tab页编号,在双绑模式下,改变这个值可以实现选中tab页的切换。
*
* @NoMarkForCheckRequired
*/
@Input()
public get selectedIndex(): number {
return this._$selectedIndex;
}
public set selectedIndex(value: number) {
if (this._$selectedIndex !== value && typeof value == 'number') {
this._$selectedIndex = value;
if (this.initialized) {
this._handleSelectChange(value)
}
this._changeDetector.detectChanges();
}
}
/**
* @internal
*/
public _$headless: boolean = false;
/**
* 控制tab头部是否显示
*
* $demo = tab/headless
*/
@Input()
@RequireMarkForCheck()
public get headless(): boolean {
return this._$headless;
}
public set headless(value: boolean) {
if (this._$headless == value) {
return;
}
this._$headless = value;
}
public _$tabPanes: TabBarData[] | QueryList<JigsawTabPane> = [];
@Input()
@RequireMarkForCheck()
public get data(): any[] {
return this._$tabPanes instanceof QueryList ? this._$tabPanes.toArray() : this._$tabPanes;
}
public set data(value: any[]) {
if (this._$tabPanes == value) {
return;
}
this._$tabPanes = value;
}
/**
* 控制tab显示添加和删除按钮
*
* @NoMarkForCheckRequired
*
* $demo = tab/editable
*/
@Input()
public editable: boolean;
/**
* 当所选的tab页发生变化时发出此事件,事件携带的是被选中的tab页实例,
* 如果需要索引值,请使用`selectedIndexChange`事件。
*/
@Output()
public selectChange = new EventEmitter<JigsawTabPane | TabBarData>();
/**
* 当前选中的tab页编号发生变化时,发出此事件。
* 事件携带的是索引值,如果需要获取更多信息,请参考`selectChange`事件。
*/
@Output()
public selectedIndexChange = new EventEmitter<number>();
/**
* 删除tab时,发出事件,携带删除的tab索引值
*
* $demo = tab/editable
*
*/
@Output()
public remove = new EventEmitter<number>();
/**
* 发送add事件,携带tabs的实例
*
* $demo = tab/editable
*
*/
@Output()
public add = new EventEmitter<JigsawTab>();
/**
* 改变tab标题时发送此事件,事件携带一个`TabTitleInfo`类型的数据。
*/
@Output()
public titleChange = new EventEmitter<TabTitleInfo>();
/**
* 控制tab显示为标签式 or 页签式
*
* @NoMarkForCheckRequired
*
* $demo = tab-bar/type
*/
@Input()
public tabType: 'label' | 'page' = 'label';
/**
* @internal
*/
public _$selectTabStyle: object = {};
/**
* @internal
*/
public _$inkBarStyle: object = {};
/**
* @internal
*/
public _$tabList = [];
/**
* @internal
*/
public _$showOverflowButton: boolean = false;
protected _tabLeftMap: Map<number, number> = new Map<number, number>();
/**
* 在tab中需要通过tab-bar实例获取,这里要定义成public
* @internal
*/
@ViewChildren(JigsawTabLabel)
public _tabLabels: QueryList<JigsawTabLabel>;
/**
* 在tab中需要通过tab-bar实例获取,这里要定义成public
* @internal
*/
@ViewChild('tabsInkBar')
public _tabsInkBar: ElementRef;
/**
* 在tab中需要通过tab-bar实例获取,这里要定义成public
* @internal
*/
@ViewChild('tabsNavWrap')
public _tabsNavWrap: ElementRef;
/**
* 在tab中需要通过tab-bar实例获取,这里要定义成public
* @internal
*/
@ViewChild('tabsNav')
public _tabsNav: ElementRef;
protected abstract get tabsInkBar(): ElementRef;
protected abstract get tabsNavWrap(): ElementRef;
protected abstract get tabsNav(): ElementRef;
protected abstract get tabLabels(): QueryList<JigsawTabLabel>;
protected _handleSelectChange(index) {
this.selectChange.emit(this._getTabPaneByIndex(index));
this.selectedIndexChange.emit(index);
this._asyncSetStyle(index);
}
protected _getTabPaneByIndex(key): JigsawTabPane | TabBarData {
return this._$tabPanes ? this._$tabPanes.find((item, index) => index === key) : undefined;
}
protected _asyncSetStyle(index: number): void {
this.runMicrotask(() => this._setInkBarStyle(index));
}
// 将有纵向切换的封装.
protected _getLabelOffsetByKey(key: number): any {
let currentLabel = this.tabLabels.find(item => item.key === key);
if (currentLabel) {
return {
offSet: currentLabel.getOffsetLeft(),
width: currentLabel.getOffsetWidth()
}
} else {
return null;
}
}
protected _createTabList() {
if (this._$headless || !this.tabsNavWrap) {
return;
}
this._$tabList = [];
this._tabLeftMap.clear();
this.tabLabels.forEach((label: JigsawTabLabel, index) => {
let title = "";
let rootNodes = label._tabItemRef ? (<EmbeddedViewRef<any>>label._tabItemRef).rootNodes : null;
if (rootNodes) {
// 模板类型
for (let i = 0; i < rootNodes.length; i++) {
if (rootNodes[i] instanceof HTMLElement) {
title += " " + rootNodes[i].outerHTML;
} else {
title += " " + rootNodes[i].textContent.trim();
}
}
} else if (label._tabItemRef && label._tabItemRef instanceof ComponentRef) {
// 动态加载的自定义类型:渲染器
title = (<IJigsawTabTitleRenderer>label._tabItemRef.instance).title;
} else if (typeof label.tabItem == 'string') {
title = label.tabItem;
}
this._$tabList.push(title.trim());
let distance = label.getOffsetLeft() + label.getOffsetWidth() - this.tabsNavWrap.nativeElement.offsetWidth;
this._tabLeftMap.set(index, distance > 0 ? (0 - distance) : 0);
});
this._updateOverflowButton();
this._updateTitlePosition(this.selectedIndex);
}
protected _updateTitlePosition(index) {
this._$selectTabStyle = {
"left": this._tabLeftMap.get(index) + "px"
};
}
protected _autoSelect() {
this.selectedIndex = this.data.findIndex(tabPane => !tabPane.disabled && !tabPane.hidden);
}
private _setInkBarStyle(index: number) {
if (!this.tabsInkBar || this.tabLabels.length == 0) return;
let labelPos = this._getLabelOffsetByKey(index);
if (!labelPos) {
return;
}
this._$inkBarStyle = {
'transform': 'translate3d(' + (labelPos.offSet + this._tabLeftMap.get(this.selectedIndex)) + 'px, 0px, 0px)',
'width': labelPos.width + 'px'
};
this._changeDetector.markForCheck();
}
private _updateOverflowButton() {
if (!this.tabsNav || !this.tabsNavWrap) return;
this._$showOverflowButton = this.tabsNavWrap.nativeElement.offsetWidth < this.tabsNav.nativeElement.offsetWidth;
this._changeDetector.detectChanges();
}
/**
* 当前的tab页数量,包含被隐藏的tab页
*/
public length: number;
private _tabLabelsChangeHandler: Subscription;
ngAfterViewInit() {
this._createTabList();
this._tabLabelsChangeHandler = this.tabLabels.changes.subscribe(() => this._createTabList());
if (this.selectedIndex != null) {
this._handleSelectChange(this.selectedIndex)
} else {
this._autoSelect();
}
this.length = this._$tabPanes.length;
}
ngOnDestroy() {
if (this._tabLabelsChangeHandler) {
this._tabLabelsChangeHandler.unsubscribe();
}
}
// 注意此方法会被频繁调用,性能要求高
ngAfterViewChecked() {
if (!this.tabsInkBar || this.tabLabels.length == 0) {
// ngFor的数据更新了需要markForCheck
this._changeDetector.markForCheck();
return;
}
this._createTabList();
const labelPos = this._getLabelOffsetByKey(this.selectedIndex);
if (!labelPos) {
return;
}
const tabElem = this.tabsInkBar.nativeElement;
if (tabElem.offsetWidth != labelPos.width) {
this._asyncSetStyle(this.selectedIndex);
} else {
const match = (tabElem.style.transform + '').match(/\btranslate3d\s*\((\d+)px\s*,/);
const styleOffset = match ? match[1] : -1;
const labelOffset = labelPos.offSet + this._tabLeftMap.get(this.selectedIndex);
// 当tab的宽度缩放到小于标题头的宽度时,这里会出现两个负值的偏移量,且不相等
// 这里会一直重复计算,从而导致页面卡死
if ((styleOffset >= 0 || labelOffset >= 0) && styleOffset != labelOffset) {
this._asyncSetStyle(this.selectedIndex);
}
}
}
@HostListener('window:resize')
onResize() {
this._createTabList();
}
}
@Component({
selector: 'jigsaw-tab-bar, j-tab-bar, jigsaw-tabs-bar, j-tabs-bar',
templateUrl: 'tab-bar.html',
host: {
'[class.jigsaw-tabs]': 'true',
'[class.jigsaw-tabs-host]': 'true',
'[style.width]': 'width',
'[style.height]': 'height',
'[class.jigsaw-tabs-page]': 'tabType == "page"',
'[class.jigsaw-tabs-editable]': 'editable'
},
changeDetection: ChangeDetectionStrategy.OnPush
})
export class JigsawTabBar extends JigsawTabBase {
constructor(private _cfr: ComponentFactoryResolver,
protected _changeDetector: ChangeDetectorRef,
private _viewContainer: ViewContainerRef,
// @RequireMarkForCheck 需要用到,勿删
protected _injector: Injector,
/**
* @internal
*/
public _elementRef: ElementRef) {
super(_changeDetector, _injector);
}
/**
* tab页点击
* @internal
*/
public _$tabClick(index) {
this.selectedIndex = index;
this._updateTitlePosition(index);
}
/**
* @internal
*/
public _$handleAdd() {
this.add.emit();
}
/**
* @internal
*/
public _$handleRemove(index) {
this.remove.emit(index);
}
/**
* @internal
*/
public _$listOptionClick(index) {
if (this.data[index].disabled) return;
this.selectedIndex = index;
}
protected get tabsInkBar(): ElementRef {
return this._tabsInkBar;
}
protected get tabsNavWrap(): ElementRef {
return this._tabsNavWrap;
}
protected get tabsNav(): ElementRef {
return this._tabsNav;
}
protected get tabLabels(): QueryList<JigsawTabLabel> {
return this._tabLabels;
}
}
/**
* 使用`JigsawTab`来将一组视图叠加在同一个区域使用,并以页签的方式来切换这些视图。
* `JigsawTab`提供了多个api用于动态创建、销毁、隐藏tab页,
* 这些是利用`JigsawTab`实现复杂、交互密集的视图的有力工具。
*
* 如果需要动态增减的视图内容形式比较单一,也可以通过`ng-for`来实现tab动态化,
* 参考[这个demo]($demo=tab/with-ngfor)。
*
* $demo = tab/basic
* $demo = tab/update-title
* $demo = tab/with-input
*/
@Component({
selector: 'jigsaw-tab, j-tab, jigsaw-tabs, j-tabs',
templateUrl: 'tab.html',
host: {
'[class.jigsaw-tabs-host]': 'true',
'[style.width]': 'width',
'[style.height]': 'height'
},
changeDetection: ChangeDetectionStrategy.OnPush
})
export class JigsawTab extends JigsawTabBase {
constructor(private _cfr: ComponentFactoryResolver,
protected _changeDetector: ChangeDetectorRef,
private _viewContainer: ViewContainerRef,
// @RequireMarkForCheck 需要用到,勿删
protected _injector: Injector) {
super(_changeDetector, _injector);
}
/**
* @internal
*/
@ContentChildren(JigsawTabPane)
public _$tabPanes: QueryList<JigsawTabPane>;
/**
* @internal
*/
@ViewChildren(JigsawTabContent)
public _tabContents: QueryList<JigsawTabContent>;
@ViewChild('tabBar')
private _tabBar: JigsawTabBar;
/**
* @NoMarkForCheckRequired
*/
@Input()
public enableAnimation: boolean = true;
/**
* @internal
*/
public _$handleAdd() {
this.add.emit(this);
}
/**
* @internal
*/
public _$handleRemove(index) {
this.removeTab(index);
this.remove.emit(index);
}
ngOnInit() {
super.ngOnInit();
}
/**
* 隐藏对应的Tab页,使用户在界面上看不到它,页无法对它做操作。
* 注意这个方法不会销毁tab页内的组件,如果需要销毁tab页,请使用`removeTab`。
* 被隐藏的tab页可以通过`showTab`方法让他们再次显示出来。
*
* $demo = tab/api
* $demo = tab/hide-tab
*
* @param index tab页的编号,从0开始
*/
public hideTab(index: number): void {
let tabPane = this._getTabPaneByIndex(index);
if (!this._isTabPane(tabPane)) return;
tabPane.hidden = true;
this._handleSelect();
}
/**
* 将对应的Tab页切换为激活状态,当指定的tab页是隐藏状态时,它将被设置为正常状态并被激活。
*
* $demo = tab/api
* $demo = tab/show-tab
*
* @param index tab页的编号,从0开始
*/
public showTab(index: number) {
let tabPane = this._getTabPaneByIndex(index);
if (!this._isTabPane(tabPane)) return;
tabPane.hidden = false;
this.selectedIndex = index;
}
private _isTabPane(tabPane: any): boolean {
if (!tabPane) {
console.info("no tab-pane found...");
return false;
} else {
return true;
}
}
/**
* 通过编程的方式添加一个新的tab页
*
* $demo = tab/api
*
* @param titleString 以一个简单的字符串作为标题
* @param contentTemplate 以一个`ng-template`标签包围起来的模板作为tab页的内容,
* 当tab页的内容比较简单时,建议采用此方式。
* @param initData 提供给`contentTemplate`的初始化数据
* @param activateImmediately 是否立即激活新增的Tab页,默认值是`true`
*/
public addTab(titleString: string, contentTemplate: TemplateRef<any>,
initData?: Object, activateImmediately?: boolean);
/**
* @param titleTemplate 以一个`ng-template`标签包围起来的模板作为标题,
* 这样可以彻底定制化新增的tab的标题部分,例如加图标,甚至添加按钮、进度条等复杂视图。
* @param contentTemplate
* @param initData
* @param activateImmediately
*/
public addTab(titleTemplate: TemplateRef<any>, contentTemplate: TemplateRef<any>,
initData?: Object, activateImmediately?: boolean);
/**
* @param titleComponent 以一个组件作为标题,这样可以彻底定制化新增的tab的标题部分,
* 例如加图标,甚至添加按钮、进度条等复杂视图。
* @param contentTemplate
* @param initData
* @param activateImmediately
*/
public addTab(titleComponent: Type<IJigsawTabTitleRenderer>, contentTemplate: TemplateRef<any>,
initData?: Object, activateImmediately?: boolean);
/**
* @param titleString
* @param contentComponent 以一个组件作为tab页的内容,
* 如果新增的tab页内容比较复杂,建议采用此方式添加,以让各部分代码的耦合解开。
* @param initData
* @param activateImmediately
*/
public addTab(titleString: string, contentComponent: Type<IDynamicInstantiatable>,
initData?: Object, activateImmediately?: boolean);
/**
* @param titleTemplate
* @param contentComponent
* @param initData
* @param activateImmediately
*/
public addTab(titleTemplate: TemplateRef<any>, contentComponent: Type<IDynamicInstantiatable>,
initData?: Object, activateImmediately?: boolean);
/**
* @param titleComponent
* @param contentComponent
* @param initData
* @param activateImmediately
*/
public addTab(titleComponent: Type<IJigsawTabTitleRenderer>, contentComponent: Type<IDynamicInstantiatable>,
initData?: Object, activateImmediately?: boolean);
/**
* @internal
*/
public addTab(title: string | TemplateRef<any> | Type<IJigsawTabTitleRenderer>,
content: TemplateRef<any> | Type<IDynamicInstantiatable>,
initData?: Object, activateImmediately: boolean = true) {
const factory = this._cfr.resolveComponentFactory(JigsawTabPane);
let tabPane: JigsawTabPane = this._viewContainer.createComponent(factory).instance;
if (typeof title == 'string') {
tabPane.title = title
} else {
tabPane.label = title;
}
tabPane.content = content;
tabPane.initData = initData;
let tabTemp = this._$tabPanes.toArray();
tabTemp.push(tabPane);
this._$tabPanes.reset(tabTemp);
this.length = this._$tabPanes.length;
if (activateImmediately) {
this.selectedIndex = this._$tabPanes.length - 1;
}
//router link
this.runMicrotask(() => {
const label = this.tabLabels.find(item => item.key === this.selectedIndex);
if (!label) {
return;
}
const link = label.elementRef.nativeElement.querySelector('[routerLink]');
if (!link) {
return;
}
link.click();
});
}
/**
* 销毁指定的Tab页,注意此操作不可恢复,可以使用`hideTab`来隐藏一个tab页,而非销毁它。
*
* $demo = tab/destroy-tab
* $demo = tab/api
*
* @param index 目标tab页的编号,从0开始计数。
*/
public removeTab(index) {
if (this._$tabPanes.length - index < 1) {
console.info("没有对应tab-pane 供删除");
return;
}
let tabTemp = this._$tabPanes.toArray();
tabTemp.splice(index, 1); // 去掉要删除的元素;
// 重新修改queryList. 不确定这么做有没有什么隐患.
this._$tabPanes.reset(tabTemp);
this._changeDetector.markForCheck();
this.length = this._$tabPanes.length;
if (this.selectedIndex == index) {
this._handleSelect()
} else if (this.selectedIndex > index) {
this.selectedIndex = this.selectedIndex - 1
}
}
/**
* 当 没有指定选择哪个tab时自动处理选中的函数:
* 使用场景:
* 1. 隐藏了当前选中的tab-pane
* 2. 删除了当前的tab-pane
* 规则: 1. 最后一个非disabled的tabPane
* 2. 否则隐藏tab 条.
*
*/
private _handleSelect() {
let tabPane = this._getTabPaneByIndex(this.selectedIndex);
if (!tabPane || tabPane.hidden || tabPane.disabled) {
this._autoSelect()
} else {
this._asyncSetStyle(this.selectedIndex);
}
}
protected get tabsInkBar(): ElementRef {
return this._tabBar ? this._tabBar._tabsInkBar : this._tabsInkBar;
}
protected get tabsNavWrap(): ElementRef {
return this._tabBar ? this._tabBar._tabsNavWrap : this._tabsNavWrap;
}
protected get tabsNav(): ElementRef {
return this._tabBar ? this._tabBar._tabsNav : this._tabsNav;
}
protected get tabLabels(): QueryList<JigsawTabLabel> {
return this._tabBar ? this._tabBar._tabLabels : this._tabLabels;
}
} | the_stack |
import { TokenType } from './lexer'
import { ExpressionNode, Parser, TemplateParser } from './parser'
describe('Parser', () => {
const TESTS: { [expr: string]: ExpressionNode } = {
'!a': {
Unary: {
operator: '!',
expression: { Identifier: 'a' },
},
},
'"a"': {
Literal: {
type: TokenType.String,
value: 'a',
},
},
'`a`': {
Literal: {
type: TokenType.String,
value: 'a',
},
},
// eslint-disable-next-line no-template-curly-in-string
'`${x}`': {
Template: {
parts: [{ Identifier: 'x' }],
},
},
// eslint-disable-next-line no-template-curly-in-string
'`${x}${y}`': {
Template: {
parts: [{ Identifier: 'x' }, { Identifier: 'y' }],
},
},
// eslint-disable-next-line no-template-curly-in-string
'`${x+y}`': {
Template: {
parts: [
{
Binary: {
left: { Identifier: 'x' },
operator: '+',
right: { Identifier: 'y' },
},
},
],
},
},
// eslint-disable-next-line no-template-curly-in-string
'`a${x}`': {
Template: {
parts: [{ Literal: { type: TokenType.String, value: 'a' } }, { Identifier: 'x' }],
},
},
// eslint-disable-next-line no-template-curly-in-string
'`${x}b`': {
Template: {
parts: [{ Identifier: 'x' }, { Literal: { type: TokenType.String, value: 'b' } }],
},
},
// eslint-disable-next-line no-template-curly-in-string
'`a${x}b`': {
Template: {
parts: [
{ Literal: { type: TokenType.String, value: 'a' } },
{ Identifier: 'x' },
{ Literal: { type: TokenType.String, value: 'b' } },
],
},
},
// eslint-disable-next-line no-template-curly-in-string
'`a${x}b${y}c`': {
Template: {
parts: [
{ Literal: { type: TokenType.String, value: 'a' } },
{ Identifier: 'x' },
{ Literal: { type: TokenType.String, value: 'b' } },
{ Identifier: 'y' },
{ Literal: { type: TokenType.String, value: 'c' } },
],
},
},
// eslint-disable-next-line no-template-curly-in-string
'`a${`x${y}z`}b`': {
Template: {
parts: [
{ Literal: { type: TokenType.String, value: 'a' } },
{
Template: {
parts: [
{ Literal: { type: TokenType.String, value: 'x' } },
{ Identifier: 'y' },
{ Literal: { type: TokenType.String, value: 'z' } },
],
},
},
{ Literal: { type: TokenType.String, value: 'b' } },
],
},
},
'a && b': {
Binary: {
left: { Identifier: 'a' },
operator: '&&',
right: { Identifier: 'b' },
},
},
// TODO: The template language currently does not support operator precedence. You must use parentheses to
// be explicit. This commented-out (failing) test case is the desired parse tree for this expression:
//
// 'a == b && c == d': {
// Binary: {
// left: {
// Binary: {
// left: { Identifier: 'a' },
// operator: '==',
// right: {
// Identifier: 'b',
// },
// },
// },
// operator: '&&',
// right: {
// Binary: {
// left: { Identifier: 'c' },
// operator: '==',
// right: { Identifier: 'd' },
// },
// },
// },
// },
//
// This is the undesirable parse tree for the expression. When the commented-out test case passes, this
// undesirable test case should be removed.
'a == b && c == d': {
Binary: {
left: {
Binary: {
left: {
Binary: {
left: { Identifier: 'a' },
operator: '==',
right: { Identifier: 'b' },
},
},
operator: '&&',
right: {
Identifier: 'c',
},
},
},
operator: '==',
right: {
Identifier: 'd',
},
},
},
'(a + b) * c': {
Binary: {
left: {
Binary: {
left: { Identifier: 'a' },
operator: '+',
right: { Identifier: 'b' },
},
},
operator: '*',
right: { Identifier: 'c' },
},
},
'ab * 1 + x(2, 3)': {
Binary: {
left: {
Binary: {
left: { Identifier: 'ab' },
operator: '*',
right: { Literal: { type: TokenType.Number, value: '1' } },
},
},
operator: '+',
right: {
FunctionCall: {
name: 'x',
args: [
{ Literal: { type: TokenType.Number, value: '2' } },
{ Literal: { type: TokenType.Number, value: '3' } },
],
},
},
},
},
}
const parser = new Parser()
for (const [expression, want] of Object.entries(TESTS)) {
test(expression, () => expect(parser.parse(expression)).toEqual(want))
}
test('throws an error on an invalid argument list', () => expect(() => parser.parse('a(1,,)')).toThrow())
test('throws an error on an unclosed string', () => expect(() => parser.parse('"')).toThrow())
test('throws an error on an unclosed template', () => expect(() => parser.parse('`')).toThrow())
test('throws an error on an invalid unary operator', () => expect(() => parser.parse('!')).toThrow())
test('throws an error on an invalid binary operator', () => expect(() => parser.parse('a*')).toThrow())
test('throws an error on an unclosed function call', () => expect(() => parser.parse('a(')).toThrow())
test('throws an error on an unterminated expression', () => expect(() => parser.parse('(a=')).toThrow())
})
describe('TemplateParser', () => {
const TESTS: { [template: string]: ExpressionNode } = {
// eslint-disable-next-line no-template-curly-in-string
'${x}': {
Template: {
parts: [{ Identifier: 'x' }],
},
},
// eslint-disable-next-line no-template-curly-in-string
'${x}${y}': {
Template: {
parts: [{ Identifier: 'x' }, { Identifier: 'y' }],
},
},
// eslint-disable-next-line no-template-curly-in-string
'${x+y}': {
Template: {
parts: [
{
Binary: {
left: { Identifier: 'x' },
operator: '+',
right: { Identifier: 'y' },
},
},
],
},
},
// eslint-disable-next-line no-template-curly-in-string
'a${x}': {
Template: {
parts: [{ Literal: { type: TokenType.String, value: 'a' } }, { Identifier: 'x' }],
},
},
// eslint-disable-next-line no-template-curly-in-string
'${x}b': {
Template: {
parts: [{ Identifier: 'x' }, { Literal: { type: TokenType.String, value: 'b' } }],
},
},
// eslint-disable-next-line no-template-curly-in-string
'a${x}b': {
Template: {
parts: [
{ Literal: { type: TokenType.String, value: 'a' } },
{ Identifier: 'x' },
{ Literal: { type: TokenType.String, value: 'b' } },
],
},
},
// eslint-disable-next-line no-template-curly-in-string
'a${x}b${y}c': {
Template: {
parts: [
{ Literal: { type: TokenType.String, value: 'a' } },
{ Identifier: 'x' },
{ Literal: { type: TokenType.String, value: 'b' } },
{ Identifier: 'y' },
{ Literal: { type: TokenType.String, value: 'c' } },
],
},
},
// eslint-disable-next-line no-template-curly-in-string
'a${`x${y}z`}b': {
Template: {
parts: [
{ Literal: { type: TokenType.String, value: 'a' } },
{
Template: {
parts: [
{ Literal: { type: TokenType.String, value: 'x' } },
{ Identifier: 'y' },
{ Literal: { type: TokenType.String, value: 'z' } },
],
},
},
{ Literal: { type: TokenType.String, value: 'b' } },
],
},
},
}
const parser = new TemplateParser()
for (const [template, want] of Object.entries(TESTS)) {
test(template, () => expect(parser.parse(template)).toEqual(want))
}
}) | the_stack |
import * as assert from 'assert'
import * as E from 'fp-ts/lib/Either'
import { none, some } from 'fp-ts/lib/Option'
import { flow } from 'fp-ts/lib/function'
import * as t from 'io-ts'
import { failure } from 'io-ts/lib/PathReporter'
import * as sinon from 'sinon'
import { Decoder } from '../src/Decode'
import * as Http from '../src/Http'
describe('Http', () => {
describe('toTask()', () => {
let server: sinon.SinonFakeServer
beforeEach(() => {
server = sinon.fakeServer.create({ respondImmediately: true })
})
afterEach(() => {
server.restore()
})
it('should fetch a valid url', async () => {
server.respondWith('GET', 'http://example.com/test', [200, {}, JSON.stringify({ a: 'test' })])
const request = Http.get('http://example.com/test', fromCodec(t.type({ a: t.string })))
const result = await Http.toTask(request)()
assert.deepStrictEqual(result, E.right({ a: 'test' }))
})
it('should validate the payload', async () => {
const body = JSON.stringify({ a: 'test' })
server.respondWith('GET', 'http://example.com/test', [200, {}, body])
const request = Http.get('http://example.com/test', fromCodec(t.number))
const result = await Http.toTask(request)()
assert.deepStrictEqual(
result,
E.left({
_tag: 'BadPayload',
value: 'Invalid value {"a":"test"} supplied to : number',
response: {
url: 'http://example.com/test',
status: { code: 200, message: 'OK' },
headers: {},
body
}
})
)
})
it('should handle 404', async () => {
server.respondWith('GET', 'http://example.com/test', [404, { 'X-Some': 'header' }, ''])
const request = Http.get('http://example.com/test', fromCodec(t.string))
const result = await Http.toTask(request)()
assert.deepStrictEqual(result, E.left({ _tag: 'BadUrl', value: 'http://example.com/test' }))
})
it('should handle bad responses', async () => {
const body = JSON.stringify({ error: 'bad response' })
server.respondWith('GET', 'http://example.com/test', [500, { 'X-Some': 'header' }, body])
const request = Http.get('http://example.com/test', fromCodec(t.string))
const result = await Http.toTask(request)()
assert.deepStrictEqual(
result,
E.left({
_tag: 'BadStatus',
response: {
url: 'http://example.com/test',
status: { code: 500, message: 'Internal Server Error' },
headers: { 'X-Some': 'header' },
body
}
})
)
})
it('should handle a timeout', done => {
// Use server with clock in order to simulate a timeout
const clockServer = sinon.fakeServerWithClock.create({ respondImmediately: false })
clockServer.respondWith('GET', 'http://example.com/test', [200, {}, ''])
const request = Http.get('http://example.com/test', fromCodec(t.string))
request.timeout = some(1)
Http.toTask(request)().then(result => {
// tslint:disable-line
assert.deepStrictEqual(result, E.left({ _tag: 'Timeout' }))
done()
})
// Move fake timer ahead in order to fire the Timeout error.
// sinon's type-definition lacks of right definition for `FakeServerWithClock`'s clock property
// which is defined here https://github.com/sinonjs/nise/blob/master/lib/fake-server/fake-server-with-clock.js#L16
// and it is an instance of `FakeTimer` (https://sinonjs.org/releases/v7.5.0/fake-timers/).
const c: any = clockServer
c.clock.tick(1000)
})
it('should handle a network error (generic)', done => {
const xhr = sinon.useFakeXMLHttpRequest()
const requests: sinon.SinonFakeXMLHttpRequest[] = []
xhr.onCreate = r => requests.push(r)
const request = Http.get('http://example.com/test', fromCodec(t.string))
Http.toTask(request)().then(result => {
// tslint:disable-line
assert.deepStrictEqual(result, E.left({ _tag: 'NetworkError', value: 'ajax error' }))
xhr.restore()
done()
})
requests[0].error()
})
it('should handle a network error (generic non error)', async () => {
const oriXHR = XMLHttpRequest
// Make it throw a non `Error` in order to check the refinement
XMLHttpRequest = (function () {
throw 'booom!' // tslint:disable-line no-string-throw
} as unknown) as any
const request = Http.get('http://example.com/test', fromCodec(t.string))
const result = await Http.toTask(request)()
assert.deepStrictEqual(result, E.left({ _tag: 'NetworkError', value: '' }))
XMLHttpRequest = oriXHR
})
it('should handle a parsing error', async () => {
const body = '{bad:"test"}'
server.respondWith('GET', 'http://example.com/test', xhr => {
// This hack is needed in order to avoid JSON parsing of the response body by sinon fake server
// and consequent error swallowing
const tmp: any = xhr
tmp.responseType = ''
xhr.respond(200, {}, body)
})
const request = Http.get('http://example.com/test', fromCodec(t.unknown))
const result = await Http.toTask(request)()
assert.deepStrictEqual(
result,
E.left({
_tag: 'BadPayload',
value: 'Unexpected token b in JSON at position 1',
response: {
url: 'http://example.com/test',
status: { code: 200, message: 'OK' },
headers: {},
body
}
})
)
})
})
describe('send()', () => {
let server: sinon.SinonFakeServer
beforeEach(() => {
server = sinon.fakeServer.create({ respondImmediately: true })
})
afterEach(() => {
server.restore()
})
it('should request an http call and return a Cmd - OK', done => {
server.respondWith('GET', 'http://example.com/test', [200, {}, JSON.stringify({ a: 'test' })])
const request = Http.send(E.fold(msg, msg))
const cmd = request(Http.get('http://example.com/test', fromCodec(t.type({ a: t.string }))))
return cmd.subscribe(async to => {
const result = await to()
assert.deepStrictEqual(result, some({ payload: { a: 'test' } }))
done()
})
})
it('should request an http call and return a Cmd - KO', done => {
const body = JSON.stringify({ error: 'bad response' })
server.respondWith('GET', 'http://example.com/test', [500, {}, body])
const request = Http.send(E.fold(msg, msg))
const cmd = request(Http.get('http://example.com/test', fromCodec(t.string)))
return cmd.subscribe(async to => {
const result = await to()
assert.deepStrictEqual(
result,
some({
payload: {
_tag: 'BadStatus',
response: {
url: 'http://example.com/test',
status: { code: 500, message: 'Internal Server Error' },
headers: {},
body
}
}
})
)
done()
})
})
it('should request an http call and return a Cmd - EMPTY', done => {
server.respondWith('GET', 'http://example.com/test', [204, {}, ''])
const request = Http.send(E.fold(msg, msg))
const cmd = request(Http.get('http://example.com/test', fromCodec(t.UnknownRecord)))
return cmd.subscribe(async to => {
const result = await to()
assert.deepStrictEqual(result, some({ payload: {} }))
done()
})
})
})
describe('sendFull()', () => {
let server: sinon.SinonFakeServer
beforeEach(() => {
server = sinon.fakeServer.create({ respondImmediately: true })
})
afterEach(() => {
server.restore()
})
it('should request an http call and return a Cmd - OK', done => {
server.respondWith('GET', 'http://example.com/test', [
200,
{ 'Content-Type': 'application/json', 'content-length': 11 },
JSON.stringify({ a: 'test' })
])
const request = Http.sendBy(E.fold(msg, msg))
const cmd = request(Http.get('http://example.com/test', fromCodec(t.type({ a: t.string }))))
return cmd.subscribe(async to => {
const result = await to()
assert.deepStrictEqual(
result,
some({
payload: {
url: 'http://example.com/test',
status: { code: 200, message: 'OK' },
headers: { 'Content-Type': 'application/json', 'content-length': '11' },
body: { a: 'test' }
}
})
)
done()
})
})
it('should request an http call and return a Cmd - KO', done => {
const body = JSON.stringify({ error: 'bad response' })
server.respondWith('GET', 'http://example.com/test', [500, { 'Content-Type': 'application/json' }, body])
const request = Http.sendBy(E.fold(msg, msg))
const cmd = request(Http.get('http://example.com/test', fromCodec(t.string)))
return cmd.subscribe(async to => {
const result = await to()
assert.deepStrictEqual(
result,
some({
payload: {
_tag: 'BadStatus',
response: {
url: 'http://example.com/test',
status: { code: 500, message: 'Internal Server Error' },
headers: { 'Content-Type': 'application/json' },
body
}
}
})
)
done()
})
})
it('should request an http call and return a Cmd - EMPTY', done => {
server.respondWith('GET', 'http://example.com/test', [204, { 'content-length': 0 }, ''])
const request = Http.sendBy(E.fold(msg, msg))
const cmd = request(Http.get('http://example.com/test', fromCodec(t.UnknownRecord)))
return cmd.subscribe(async to => {
const result = await to()
assert.deepStrictEqual(
result,
some({
payload: {
url: 'http://example.com/test',
status: { code: 204, message: 'No Content' },
headers: { 'content-length': '0' },
body: {}
}
})
)
done()
})
})
})
it('get() should return a GET Request', () => {
const decoder = fromCodec(t.string)
assert.deepStrictEqual(Http.get('http://example.com', decoder), {
method: 'GET',
headers: {},
url: 'http://example.com',
body: undefined,
expect: decoder,
timeout: none,
withCredentials: false
})
})
it('post() should return a POST Request', () => {
const body = { some: 'data' }
const decoder = fromCodec(t.string)
assert.deepStrictEqual(Http.post('http://example.com', body, decoder), {
method: 'POST',
headers: {},
url: 'http://example.com',
body,
expect: decoder,
timeout: none,
withCredentials: false
})
})
})
// --- Utilities
interface Msg {
payload: any
}
const msg = (payload: any): Msg => ({ payload })
function fromCodec<A>(codec: t.Decoder<unknown, A>): Decoder<A> {
return flow(
codec.decode,
E.mapLeft(errors => failure(errors).join('\n'))
)
} | the_stack |
import ago from "s-ago";
import { matchSorter } from "match-sorter";
import { Fragment, useCallback, useEffect, useRef, useState } from "react";
import { groupBy } from "../../../common/groupBy";
import type {
LocalStateUI,
MenuItemHeader,
MenuItemLink,
MenuItemText,
} from "../../../common/types";
import {
helpers,
logEvent,
menuItems,
realtimeUpdate,
safeLocalStorage,
toWorker,
useLocalShallow,
} from "../../util";
import { getText, makeAnchorProps } from "../SideBar";
import orderBy from "lodash-es/orderBy";
import { SPORT_HAS_LEGENDS, SPORT_HAS_REAL_PLAYERS } from "../../../common";
import Modal from "../Modal";
const TWO_MONTHS_IN_MILLISECONDS = 2 * 30 * 24 * 60 * 60 * 1000;
const ONE_WEEK_IN_MILLISECONDS = 7 * 24 * 60 * 60 * 1000;
const saveLastUsed = (init?: boolean) => {
let now = Date.now();
// If init, set it up so notification will show in a week
if (init) {
now = now - TWO_MONTHS_IN_MILLISECONDS + ONE_WEEK_IN_MILLISECONDS;
}
safeLocalStorage.setItem("commandPaletteLastUsed", String(now));
};
const useCommandPalette = () => {
const [show, setShow] = useState(false);
useEffect(() => {
const handleKeydown = (event: KeyboardEvent) => {
if (event.altKey || event.shiftKey || event.isComposing) {
return;
}
if (event.code === "KeyK" && (event.ctrlKey || event.metaKey)) {
event.preventDefault();
setShow(current => !current);
}
};
document.addEventListener("keydown", handleKeydown);
return () => {
document.removeEventListener("keydown", handleKeydown);
};
}, []);
const onHide = useCallback(() => {
setShow(false);
}, []);
return {
show,
onHide,
};
};
const MODES: { key: "@" | "/" | "!"; description: string }[] = [
{
key: "@",
description: "players",
},
{
key: "/",
description: "teams",
},
{
key: "!",
description: "leagues",
},
];
type Mode = typeof MODES[number];
// Tiebreaker - original sort order, rather than alphabetical (default)
const baseSort = () => 0;
const getResultsGroupedDefault = ({
godMode,
inLeague,
onHide,
playMenuOptions,
searchText,
}: {
godMode: boolean;
inLeague: boolean;
onHide: () => void;
playMenuOptions: LocalStateUI["playMenuOptions"];
searchText: string;
}) => {
const filterMenuItem = (menuItem: MenuItemLink | MenuItemText) => {
if (menuItem.type === "text") {
return false;
}
if (!menuItem.commandPalette) {
return false;
}
if (!menuItem.league && inLeague) {
return false;
}
if (!menuItem.nonLeague && !inLeague) {
return false;
}
if (menuItem.godMode && !godMode) {
return false;
}
return true;
};
const flat = menuItems.filter(
menuItem => menuItem.type === "link",
) as MenuItemLink[];
const nested = menuItems.filter(
menuItem => menuItem.type === "header",
) as MenuItemHeader[];
const results = [
...flat.filter(filterMenuItem).map(menuItem => {
return {
category: "",
menuItem,
};
}),
...nested.map(header => {
return (header.children.filter(filterMenuItem) as MenuItemLink[]).map(
menuItem => {
return {
category: header.long,
menuItem,
};
},
);
}),
]
.flat()
.map(({ category, menuItem }) => {
const anchorProps = makeAnchorProps(menuItem, onHide, true);
let text = getText(menuItem.text);
if (menuItem.godMode) {
text = (
<>
<span className="legend-square god-mode me-1" />
{text}
</>
);
}
const search = category ? `${category} ${text}` : text;
return {
category,
text,
search,
anchorProps,
};
});
results.unshift(
...playMenuOptions.map(option => ({
category: "Play",
text: option.label,
search: `Play ${option.label}`,
anchorProps: {
href: option.url,
onClick: () => {
onHide();
if (!option.url) {
toWorker("playMenu", option.id as any, undefined);
}
},
} as AnchorProps,
})),
);
const output = [];
if (searchText === "") {
// No search - return groups
const resultsGrouped = groupBy(results, "category");
for (const category of Object.keys(resultsGrouped)) {
if (resultsGrouped[category]) {
output.push({
category,
results: resultsGrouped[category],
});
}
}
} else {
// Search - return sorted by relevance, no grouping
const filteredResults = matchSorter(results, searchText, {
keys: ["search"],
baseSort,
});
if (filteredResults.length > 0) {
output.push({
category: "",
results: filteredResults,
});
}
}
return output;
};
type AnchorProps = ReturnType<typeof makeAnchorProps>;
const getResultsGroupedTeams = ({
hideDisabledTeams,
onHide,
searchText,
teamInfoCache,
}: {
hideDisabledTeams: LocalStateUI["hideDisabledTeams"];
onHide: () => void;
searchText: string;
teamInfoCache: LocalStateUI["teamInfoCache"];
}) => {
const teamInfos = teamInfoCache
.map((t, tid) => ({
text: `${t.region} ${t.name} (${t.abbrev}${
t.disabled ? ", disabled" : ""
})`,
disabled: t.disabled,
anchorProps: {
href: helpers.leagueUrl(["roster", `${t.abbrev}_${tid}`]),
onClick: onHide,
} as AnchorProps,
}))
.filter(t => !hideDisabledTeams || !t.disabled);
const filteredResults = matchSorter(teamInfos, searchText, {
keys: ["text"],
baseSort,
});
return [
{
category: "",
results: filteredResults.map(t => ({
category: "",
text: t.text,
anchorProps: t.anchorProps,
})),
},
];
};
const getResultsGroupedLeagues = async ({
onHide,
searchText,
}: {
onHide: () => void;
searchText: string;
}) => {
const leagues = await toWorker("main", "getLeagues", undefined);
const newLeagueResults = [];
if (SPORT_HAS_REAL_PLAYERS) {
newLeagueResults.push(
{
text: "New League - Real Players",
href: "/new_league/real",
},
{
text: "New League - Random Players",
href: "/new_league/random",
},
);
if (SPORT_HAS_LEGENDS) {
newLeagueResults.push({
text: "New League - Legends",
href: "/new_league/legends",
});
}
newLeagueResults.push({
text: "New League - Custom",
href: "/new_league",
});
} else {
newLeagueResults.push({
text: "New League",
href: "/new_league",
});
}
const results = [
{
category: "",
text: "Switch League",
anchorProps: {
href: "/",
onClick: onHide,
} as AnchorProps,
},
...newLeagueResults.map(row => ({
category: "",
text: row.text,
anchorProps: {
href: row.href,
onClick: onHide,
} as AnchorProps,
})),
...orderBy(leagues, "lastPlayed", "desc").map(l => {
const lastPlayed = `last played ${
l.lastPlayed ? ago(l.lastPlayed) : "???"
}`;
return {
category: "Leagues",
text: (
<>
{l.name} - {lastPlayed}
<br />
{l.phaseText} - {l.teamRegion} {l.teamName}
</>
),
search: `${l.name} - ${lastPlayed} ${l.phaseText} - ${l.teamRegion} ${l.teamName}`,
anchorProps: {
href: `/l/${l.lid}`,
onClick: onHide,
} as AnchorProps,
};
}),
];
const output = [];
if (searchText === "") {
// No search - return groups
const resultsGrouped = groupBy(results, "category");
for (const category of Object.keys(resultsGrouped)) {
if (resultsGrouped[category]) {
output.push({
category,
results: resultsGrouped[category],
});
}
}
} else {
// Search - return sorted by relevance, no grouping
const filteredResults = matchSorter(results, searchText, {
keys: [row => (row as any).search ?? row.text],
baseSort,
});
if (filteredResults.length > 0) {
output.push({
category: "",
results: filteredResults.map(row => ({
category: row.category,
text: row.text,
anchorProps: row.anchorProps,
hideCollapsedCategory: true,
})),
});
}
}
return output;
};
const getResultsGroupedPlayers = async ({
challengeNoRatings,
onHide,
searchText,
}: {
challengeNoRatings: LocalStateUI["challengeNoRatings"];
onHide: () => void;
searchText: string;
}) => {
const players = await toWorker("main", "getPlayersCommandPalette", undefined);
const playerInfos = orderBy(players, ["lastName", "firstName", "abbrev"]).map(
p => {
return {
text: `${p.firstName} ${p.lastName} - ${p.abbrev}, ${p.ratings.pos}, ${
p.age
}yo${
!challengeNoRatings
? ` - ${p.ratings.ovr} ovr, ${p.ratings.pot} pot`
: ""
}`,
anchorProps: {
href: helpers.leagueUrl(["player", p.pid]),
onClick: onHide,
} as AnchorProps,
};
},
);
const filteredResults = matchSorter(playerInfos, searchText, {
keys: ["text"],
baseSort,
});
return [
{
category: "",
results: filteredResults.map(row => ({
category: "",
text: row.text,
anchorProps: row.anchorProps,
})),
},
];
};
const getResultsGrouped = async ({
challengeNoRatings,
godMode,
hideDisabledTeams,
inLeague,
mode,
onHide,
playMenuOptions,
searchText,
teamInfoCache,
}: {
challengeNoRatings: LocalStateUI["challengeNoRatings"];
godMode: boolean;
hideDisabledTeams: LocalStateUI["hideDisabledTeams"];
inLeague: boolean;
mode: Mode | undefined;
onHide: () => void;
playMenuOptions: LocalStateUI["playMenuOptions"];
searchText: string;
teamInfoCache: LocalStateUI["teamInfoCache"];
}) => {
let resultsGrouped;
if (mode?.key === "/") {
resultsGrouped = getResultsGroupedTeams({
hideDisabledTeams,
onHide,
searchText,
teamInfoCache,
});
} else if (mode?.key === "!") {
resultsGrouped = await getResultsGroupedLeagues({
onHide,
searchText,
});
} else if (mode?.key === "@") {
resultsGrouped = await getResultsGroupedPlayers({
challengeNoRatings,
onHide,
searchText,
});
} else {
resultsGrouped = getResultsGroupedDefault({
godMode,
inLeague,
onHide,
playMenuOptions,
searchText,
});
}
let count = 0;
for (const group of resultsGrouped) {
count += group.results.length;
}
return {
resultsGrouped,
count,
};
};
const ACTIVE_CLASS = "table-bg-striped";
const SearchResults = ({
activeIndex,
collapseGroups,
resultsGrouped,
}: {
activeIndex: number | undefined;
collapseGroups: boolean;
resultsGrouped: Awaited<
ReturnType<typeof getResultsGrouped>
>["resultsGrouped"];
}) => {
const wrapperRef = useRef<HTMLDivElement | null>(null);
// Keep active element in viewport
useEffect(() => {
if (activeIndex !== undefined && wrapperRef.current) {
const activeElement = wrapperRef.current.querySelector(
`.${ACTIVE_CLASS}`,
);
if (activeElement) {
activeElement.scrollIntoView({
block: "nearest",
});
}
}
}, [activeIndex, resultsGrouped]);
let index = 0;
return (
<div ref={wrapperRef}>
{resultsGrouped.map(({ category, results }, i) => {
const block = (
<div
key={category}
className={`card border-0${i > 0 ? " pt-2 mt-2 border-top" : ""}`}
>
{!collapseGroups && category ? (
<div className="card-header bg-transparent border-0">
<span className="fw-bold text-secondary text-uppercase">
{category}
</span>
</div>
) : null}
<div className="list-group list-group-flush rounded-0">
{results.map((result, j) => {
const active = activeIndex === index;
index += 1;
return (
<a
key={j}
{...result.anchorProps}
className={`d-flex cursor-pointer list-group-item list-group-item-action border-0 ${
active ? ACTIVE_CLASS : ""
}`}
>
{collapseGroups &&
result.category &&
!(result as any).hideCollapsedCategory ? (
<>{result.category} > </>
) : null}
{result.text}
{active ? (
<div className="ms-auto">Press enter to select</div>
) : null}
</a>
);
})}
</div>
</div>
);
return block;
})}
</div>
);
};
const ModeText = ({ inLeague }: { inLeague: boolean }) => {
// Hide players/teams in league
const modes = MODES.filter(mode => inLeague || mode.key === "!");
return (
<>
Type{" "}
{modes.map((mode, i) => (
<Fragment key={mode.key}>
{i === 0 ? null : i === modes.length - 1 ? ", or " : ", "}
<span className="text-black">{mode.key}</span> to search{" "}
{mode.description}
</Fragment>
))}
.
</>
);
};
const ComandPalette = ({
show,
onHide,
}: {
show: boolean;
onHide: () => void;
}) => {
const searchInputRef = useRef<HTMLInputElement | null>(null);
const {
challengeNoRatings,
godMode,
hideDisabledTeams,
lid,
playMenuOptions,
teamInfoCache,
} = useLocalShallow(state => ({
challengeNoRatings: state.challengeNoRatings,
godMode: state.godMode,
hideDisabledTeams: state.hideDisabledTeams,
lid: state.lid,
playMenuOptions: state.playMenuOptions,
teamInfoCache: state.teamInfoCache,
}));
const inLeague = lid !== undefined;
const [searchText, setSearchText] = useState("");
const [mode, setMode] = useState<undefined | Mode>();
const [activeIndex, setActiveIndex] = useState<number | undefined>();
const [{ resultsGrouped, count }, setResults] = useState<
Awaited<ReturnType<typeof getResultsGrouped>>
>({
resultsGrouped: [],
count: 0,
});
useEffect(() => {
let active = true;
const update = async () => {
const newResults = await getResultsGrouped({
challengeNoRatings,
godMode,
hideDisabledTeams,
inLeague,
mode,
onHide,
playMenuOptions,
searchText,
teamInfoCache,
});
if (active) {
setResults(newResults);
}
};
update();
return () => {
active = false;
};
}, [
challengeNoRatings,
godMode,
hideDisabledTeams,
inLeague,
mode,
onHide,
playMenuOptions,
searchText,
teamInfoCache,
]);
useEffect(() => {
if (show) {
if (searchInputRef.current) {
searchInputRef.current.focus();
}
saveLastUsed();
} else {
setSearchText("");
setMode(undefined);
setActiveIndex(undefined);
}
}, [show]);
useEffect(() => {
if (!show) {
return;
}
const handleKeydown = (event: KeyboardEvent) => {
if (
event.altKey ||
event.ctrlKey ||
event.metaKey ||
event.shiftKey ||
event.isComposing
) {
return;
}
if (event.code === "ArrowDown") {
setActiveIndex(index => {
if (index === undefined) {
return 0;
}
if (index + 1 >= count) {
return 0;
}
return index + 1;
});
} else if (event.code === "ArrowUp") {
setActiveIndex(index => {
if (index === undefined) {
return 0;
}
if (index - 1 < 0) {
return count - 1;
}
return index - 1;
});
}
};
document.addEventListener("keydown", handleKeydown);
return () => {
document.removeEventListener("keydown", handleKeydown);
};
}, [count, setActiveIndex, show]);
if (!show) {
return null;
}
return (
<Modal show={show} onHide={onHide} scrollable>
<Modal.Header className="ps-3 pe-0 py-1">
<span
className="glyphicon glyphicon-search"
style={{
paddingBottom: 2,
}}
></span>
<form
className="flex-grow-1"
onSubmit={event => {
event.preventDefault();
if (activeIndex !== undefined) {
let index = 0;
for (const group of resultsGrouped) {
for (const result of group.results) {
if (index === activeIndex) {
if (result.anchorProps.onClick) {
(result.anchorProps.onClick as any)();
}
if (result.anchorProps.href) {
if (result.anchorProps.target) {
window.open(result.anchorProps.href);
} else {
realtimeUpdate([], result.anchorProps.href);
}
}
return;
}
index += 1;
}
}
}
}}
>
<div className="input-group ps-1">
{mode ? (
<span
className="input-group-text px-1 border-0 rounded-3 justify-content-center"
style={{ minWidth: 21 }}
>
{mode.key}
</span>
) : null}
<input
ref={searchInputRef}
className="form-control shadow-none border-0 ps-1 pe-0"
type="text"
placeholder={`Search ${mode?.description ?? "pages"}...`}
style={{
fontSize: 15,
}}
value={searchText}
onChange={event => {
const newText = event.target.value;
if (!mode && newText.length > 0) {
const newMode = MODES.find(mode => mode.key === newText[0]);
if (newMode) {
setMode(newMode);
setSearchText(newText.slice(1));
setActiveIndex(newText.length > 1 ? 0 : undefined);
return;
}
}
setSearchText(newText);
setActiveIndex(newText.length > 0 ? 0 : undefined);
}}
onKeyDown={event => {
// Handle backspace when mode is set and there is no text - unset mode
if (searchText === "" && mode && event.code === "Backspace") {
setMode(undefined);
setActiveIndex(undefined);
}
}}
/>
</div>
</form>
</Modal.Header>
<Modal.Body className="py-2 px-0">
{searchText === "" && !mode ? (
<p className="text-muted px-3 pb-2 mb-2 border-bottom">
<ModeText inLeague={inLeague} />
</p>
) : null}
{resultsGrouped.length > 0 ? (
<SearchResults
activeIndex={activeIndex}
collapseGroups={searchText !== ""}
resultsGrouped={resultsGrouped}
/>
) : (
<div className="px-3">No results found.</div>
)}
</Modal.Body>
</Modal>
);
};
// Wrapper so useEffect stuff in CommandPalette does not run until it shows
const ComandPaletteWrapper = () => {
const { show, onHide } = useCommandPalette();
useEffect(() => {
if (window.mobile) {
return;
}
const lastUsedOrBugged = safeLocalStorage.getItem("commandPaletteLastUsed");
if (lastUsedOrBugged === null) {
saveLastUsed(true);
return;
}
const lastDate = parseInt(lastUsedOrBugged);
if (Number.isNaN(lastDate)) {
saveLastUsed();
return;
}
const diff = Date.now() - lastDate;
if (diff >= TWO_MONTHS_IN_MILLISECONDS) {
logEvent({
extraClass: "",
type: "info",
text: "Pro tip: press ctrl+k or cmd+k to open the command palette, which allows easy keyboard navigation of your league.",
saveToDb: false,
persistent: true,
});
saveLastUsed();
}
}, []);
if (show) {
return <ComandPalette show={show} onHide={onHide} />;
}
return null;
};
export default ComandPaletteWrapper; | the_stack |
import * as ast from "@typescript-eslint/types/dist/ast-spec"
import { AST_NODE_TYPES, parse } from "@typescript-eslint/typescript-estree"
import { ExtractedToken, ExtractedTokenKind, Extractor } from "."
const twinLabel = "twin.macro"
export function findAll(code: string, jsxPropImportChecking: boolean) {
const tokens: ExtractedToken[] = []
let program: ast.Program
try {
program = parse(code, { jsx: true, range: true })
} catch {
return tokens
}
const ctx = createContext(program, jsxPropImportChecking)
program.body.forEach(parseStatement)
return tokens
function createContext(program: ast.Program, jsxPropChecking = true) {
let jsxProp = !jsxPropChecking
const twTemplate = new Set<string>()
const themeTemplate = new Set<string>()
const screenTemplate = new Set<string>()
for (const node of program.body) {
switch (node.type) {
case AST_NODE_TYPES.ImportDeclaration:
if (node.source.value === twinLabel) {
jsxProp = true
for (const clause of node.specifiers) {
switch (clause.type) {
case AST_NODE_TYPES.ImportDefaultSpecifier:
twTemplate.add(clause.local.name)
break
case AST_NODE_TYPES.ImportSpecifier:
if (clause.imported.name === "default") {
twTemplate.add(clause.local.name)
} else if (clause.imported.name === ExtractedTokenKind.TwinTheme) {
themeTemplate.add(clause.local.name)
} else if (clause.imported.name === ExtractedTokenKind.TwinScreen) {
screenTemplate.add(clause.local.name)
}
break
}
}
}
break
}
}
return { jsxProp, twTemplate, themeTemplate, screenTemplate }
}
function parseTaggedTemplateExpression(node: ast.TaggedTemplateExpression) {
if (node.tag.type !== AST_NODE_TYPES.Identifier) {
parseExpression(node.tag)
return
} else if (ctx.twTemplate.has(node.tag.name)) {
if (node.quasi.quasis.length === 1) {
const n: ast.TemplateElement = node.quasi.quasis[0]
tokens.push({
kind: ExtractedTokenKind.Twin,
start: n.range[0] + 1,
end: n.range[1] - 1,
value: n.value.cooked,
})
}
} else if (ctx.themeTemplate.has(node.tag.name)) {
if (node.quasi.quasis.length === 1) {
const n: ast.TemplateElement = node.quasi.quasis[0]
tokens.push({
kind: ExtractedTokenKind.TwinTheme,
start: n.range[0] + 1,
end: n.range[1] - 1,
value: n.value.cooked,
})
}
} else if (ctx.screenTemplate.has(node.tag.name)) {
if (node.quasi.quasis.length === 1) {
const n: ast.TemplateElement = node.quasi.quasis[0]
tokens.push({
kind: ExtractedTokenKind.TwinScreen,
start: n.range[0] + 1,
end: n.range[1] - 1,
value: n.value.cooked,
})
}
} else {
parseTemplateLiteral(node.quasi)
}
}
function parseCallExpression(node: ast.CallExpression) {
parseExpression(node.callee)
for (const a of node.arguments) {
switch (a.type) {
case AST_NODE_TYPES.SpreadElement:
parseExpression(a.argument)
break
default:
parseExpression(a)
}
}
}
function parseJSXAttribute(node: ast.JSXAttribute) {
if (node.name.type === AST_NODE_TYPES.JSXIdentifier) {
if (ctx.jsxProp && node.name.name === ExtractedTokenKind.Twin) {
if (node.value) getToken(node.value, ExtractedTokenKind.Twin)
} else if (ctx.jsxProp && node.name.name === ExtractedTokenKind.TwinCssProperty) {
if (node.value) getToken(node.value, ExtractedTokenKind.TwinCssProperty)
} else if (node.value && node.value.type !== AST_NODE_TYPES.Literal) {
parseJSXExpression(node.value)
}
}
return
function getToken(node: ast.Literal | ast.JSXExpression, kind: ExtractedTokenKind) {
switch (node.type) {
case AST_NODE_TYPES.JSXEmptyExpression:
break
case AST_NODE_TYPES.Literal:
if (typeof node.value === "string") {
tokens.push({
kind,
start: node.range[0] + 1,
end: node.range[1] - 1,
value: node.value,
})
}
break
case AST_NODE_TYPES.JSXExpressionContainer:
if (node.expression.type === AST_NODE_TYPES.Literal) {
if (typeof node.expression.value === "string") {
tokens.push({
kind,
start: node.expression.range[0] + 1,
end: node.expression.range[1] - 1,
value: node.expression.value,
})
}
} else if (node.expression.type !== AST_NODE_TYPES.JSXEmptyExpression) {
parseExpression(node.expression)
}
break
case AST_NODE_TYPES.JSXSpreadChild:
if (node.expression.type !== AST_NODE_TYPES.JSXEmptyExpression) {
parseExpression(node.expression)
}
break
}
}
}
function parseJSXElement(node: ast.JSXElement) {
parseJSXOpeningElement(node.openingElement)
node.children.forEach(parseJSXChild)
}
function parseJSXOpeningElement(node: ast.JSXOpeningElement) {
for (const attr of node.attributes) {
switch (attr.type) {
case AST_NODE_TYPES.JSXAttribute:
parseJSXAttribute(attr)
break
default:
parseJSXSpreadAttribute(attr)
break
}
}
}
function parseJSXChild(node: ast.JSXChild) {
switch (node.type) {
case AST_NODE_TYPES.JSXElement:
parseJSXElement(node)
break
case AST_NODE_TYPES.JSXFragment:
parseJSXFragment(node)
break
case AST_NODE_TYPES.JSXText:
break
default:
parseJSXExpression(node)
break
}
}
function parseJSXFragment(node: ast.JSXFragment) {
node.children.forEach(parseJSXChild)
}
function parseJSXSpreadAttribute(node: ast.JSXSpreadAttribute) {
parseExpression(node.argument)
}
function parseJSXExpression(node: ast.JSXExpression) {
switch (node.type) {
case AST_NODE_TYPES.JSXEmptyExpression:
break
case AST_NODE_TYPES.JSXSpreadChild:
if (node.expression.type !== AST_NODE_TYPES.JSXEmptyExpression) {
parseExpression(node.expression)
}
break
case AST_NODE_TYPES.JSXExpressionContainer:
if (node.expression.type !== AST_NODE_TYPES.JSXEmptyExpression) {
parseExpression(node.expression)
}
break
}
}
function parseExportDefaultDeclaration(node: ast.ExportDefaultDeclaration) {
parseDeclaration(node.declaration)
}
function parseVariableDeclaration(node: ast.VariableDeclaration) {
node.declarations.forEach(parseVariableDeclarator)
}
function parseExpression(node: ast.Expression) {
// LiteralExpression | LogicalExpression | MemberExpression | MetaProperty | NewExpression | ObjectPattern | Super | ThisExpression | TSAsExpression | TSNonNullExpression | TSTypeAssertion;
switch (node.type) {
case AST_NODE_TYPES.TaggedTemplateExpression:
parseTaggedTemplateExpression(node)
break
case AST_NODE_TYPES.TemplateLiteral:
parseTemplateLiteral(node)
break
case AST_NODE_TYPES.SequenceExpression:
node.expressions.forEach(parseExpression)
break
case AST_NODE_TYPES.ArrayExpression:
parseArrayExpression(node)
break
case AST_NODE_TYPES.ArrayPattern:
parseArrayPattern(node)
break
case AST_NODE_TYPES.FunctionExpression:
parseFunctionExpression(node)
break
case AST_NODE_TYPES.ArrowFunctionExpression:
parseArrowFunctionExpression(node)
break
case AST_NODE_TYPES.AssignmentExpression:
parseExpression(node.right)
break
case AST_NODE_TYPES.ConditionalExpression:
parseExpression(node.consequent)
parseExpression(node.alternate)
break
case AST_NODE_TYPES.LogicalExpression:
parseExpression(node.right)
break
case AST_NODE_TYPES.MemberExpression:
if (node.property.type !== AST_NODE_TYPES.PrivateIdentifier) {
parseExpression(node.property)
}
break
case AST_NODE_TYPES.BinaryExpression:
parseExpression(node.right)
break
case AST_NODE_TYPES.UpdateExpression:
parseExpression(node.argument)
break
case AST_NODE_TYPES.AwaitExpression:
parseExpression(node.argument)
break
case AST_NODE_TYPES.YieldExpression:
if (node.argument) parseExpression(node.argument)
break
case AST_NODE_TYPES.ObjectExpression:
for (const el of node.properties) {
parseObjectLiteralElement(el)
}
break
case AST_NODE_TYPES.ClassExpression:
parseClassBody(node.body)
break
case AST_NODE_TYPES.ChainExpression:
parseExpression(node.expression)
break
case AST_NODE_TYPES.CallExpression:
parseCallExpression(node)
break
case AST_NODE_TYPES.UnaryExpression:
parseUnaryExpression(node)
break
case AST_NODE_TYPES.ImportExpression:
parseExpression(node.source)
break
case AST_NODE_TYPES.JSXElement:
parseJSXElement(node)
break
case AST_NODE_TYPES.JSXFragment:
parseJSXFragment(node)
break
case AST_NODE_TYPES.Identifier:
break
case AST_NODE_TYPES.ThisExpression:
break
}
}
function parseDeclaration(node: ast.ExportDeclaration | ast.Expression) {
switch (node.type) {
case AST_NODE_TYPES.ClassDeclaration:
parseClassDeclaration(node)
break
case AST_NODE_TYPES.ClassExpression:
parseClassBody(node.body)
break
case AST_NODE_TYPES.FunctionDeclaration:
parseFunctionDeclaration(node)
break
case AST_NODE_TYPES.TSEnumDeclaration:
parseTSEnumDeclaration(node)
break
case AST_NODE_TYPES.VariableDeclaration:
parseVariableDeclaration(node)
break
case AST_NODE_TYPES.TSDeclareFunction:
case AST_NODE_TYPES.TSInterfaceDeclaration:
case AST_NODE_TYPES.TSModuleDeclaration:
case AST_NODE_TYPES.TSTypeAliasDeclaration:
break
default:
parseExpression(node)
}
}
function parseStatement(node: ast.Statement) {
switch (node.type) {
case AST_NODE_TYPES.BlockStatement:
parseBlockStatement(node)
break
case AST_NODE_TYPES.ClassDeclaration:
parseClassDeclaration(node)
break
case AST_NODE_TYPES.DoWhileStatement:
parseStatement(node.body)
break
case AST_NODE_TYPES.ExportDefaultDeclaration:
parseExportDefaultDeclaration(node)
break
case AST_NODE_TYPES.ExpressionStatement:
parseExpression(node.expression)
break
case AST_NODE_TYPES.ForInStatement:
parseExpression(node.right)
parseStatement(node.body)
break
case AST_NODE_TYPES.ForOfStatement:
parseExpression(node.right)
parseStatement(node.body)
break
case AST_NODE_TYPES.ForStatement:
if (node.init) {
if (node.init.type === AST_NODE_TYPES.VariableDeclaration) parseVariableDeclaration(node.init)
else parseExpression(node.init)
}
if (node.test) {
parseExpression(node.test)
}
if (node.update) {
parseExpression(node.update)
}
parseStatement(node.body)
break
case AST_NODE_TYPES.FunctionDeclaration:
parseFunctionDeclaration(node)
break
case AST_NODE_TYPES.IfStatement:
parseExpression(node.test)
if (node.alternate) parseStatement(node.alternate)
parseStatement(node.consequent)
break
case AST_NODE_TYPES.ReturnStatement:
if (node.argument) parseExpression(node.argument)
break
case AST_NODE_TYPES.ThrowStatement:
if (node.argument && node.argument.type !== AST_NODE_TYPES.TSAsExpression) parseStatement(node.argument)
break
case AST_NODE_TYPES.SwitchStatement:
parseExpression(node.discriminant)
for (const cs of node.cases) {
if (cs.test) parseExpression(cs.test)
cs.consequent.forEach(parseStatement)
}
break
case AST_NODE_TYPES.TryStatement:
parseStatement(node.block)
if (node.handler) {
if (node.handler.param) parseBindingName(node.handler.param)
parseBlockStatement(node.handler.body)
}
if (node.finalizer) parseStatement(node.finalizer)
break
case AST_NODE_TYPES.TSEnumDeclaration:
parseTSEnumDeclaration(node)
break
case AST_NODE_TYPES.TSExportAssignment:
parseExpression(node.expression)
break
case AST_NODE_TYPES.VariableDeclaration:
node.declarations.forEach(parseVariableDeclarator)
break
case AST_NODE_TYPES.WhileStatement:
parseExpression(node.test)
parseStatement(node.body)
break
case AST_NODE_TYPES.WithStatement:
parseExpression(node.object)
parseStatement(node.body)
break
case AST_NODE_TYPES.ExportNamedDeclaration:
if (node.declaration) parseDeclaration(node.declaration)
break
case AST_NODE_TYPES.ImportDeclaration:
case AST_NODE_TYPES.TSModuleDeclaration:
case AST_NODE_TYPES.TSNamespaceExportDeclaration:
case AST_NODE_TYPES.TSTypeAliasDeclaration:
case AST_NODE_TYPES.TSImportEqualsDeclaration:
case AST_NODE_TYPES.BreakStatement:
case AST_NODE_TYPES.ContinueStatement:
case AST_NODE_TYPES.DebuggerStatement:
case AST_NODE_TYPES.ExportAllDeclaration:
case AST_NODE_TYPES.LabeledStatement:
break
}
}
function parseBlockStatement(node: ast.BlockStatement) {
node.body.forEach(parseStatement)
}
function parseVariableDeclarator(node: ast.VariableDeclarator) {
parseBindingName(node.id)
if (node.init) parseExpression(node.init)
}
function parseDestructuringPattern(node: ast.DestructuringPattern | null) {
if (node) {
switch (node.type) {
case AST_NODE_TYPES.ArrayPattern:
node.elements.forEach(parseDestructuringPattern)
for (const el of node.elements) {
if (el) parseDestructuringPattern(el)
}
break
case AST_NODE_TYPES.AssignmentPattern:
parseExpression(node.right)
break
}
}
}
function parseMethodDefinition(node: ast.MethodDefinition) {
if (node.value.type === AST_NODE_TYPES.FunctionExpression) parseFunctionExpression(node.value)
}
function parseArrayPattern(node: ast.ArrayPattern) {
for (const el of node.elements) {
if (el) parseDestructuringPattern(el)
}
}
function parseProperty(node: ast.Property) {
if (node.computed) parseExpression(node.key)
switch (node.value.type) {
case AST_NODE_TYPES.AssignmentPattern:
parseExpression(node.value.right)
break
case AST_NODE_TYPES.ArrayPattern:
parseArrayPattern(node.value)
break
case AST_NODE_TYPES.ObjectPattern:
parseObjectPattern(node.value)
break
case AST_NODE_TYPES.Identifier:
break
case AST_NODE_TYPES.TSEmptyBodyFunctionExpression:
break
default:
parseExpression(node.value)
}
}
function parseRestElement(node: ast.RestElement) {
if (node.value) {
parseExpression(node.value.right)
}
}
function parseObjectPattern(node: ast.ObjectPattern) {
for (const prop of node.properties) {
if (prop.type === AST_NODE_TYPES.Property) {
parseProperty(prop)
} else {
parseRestElement(prop)
}
}
}
function parseObjectLiteralElement(node: ast.ObjectLiteralElement) {
switch (node.type) {
case AST_NODE_TYPES.MethodDefinition:
parseMethodDefinition(node)
break
case AST_NODE_TYPES.Property:
parseProperty(node)
break
case AST_NODE_TYPES.SpreadElement:
parseExpression(node.argument)
break
}
}
function parseUnaryExpression(node: ast.UnaryExpression) {
switch (node.argument.type) {
case AST_NODE_TYPES.Literal:
break
case AST_NODE_TYPES.UnaryExpression:
parseUnaryExpression(node.argument)
break
default:
parseExpression(node.argument)
break
}
}
function parseTemplateLiteral(node: ast.TemplateLiteral) {
node.expressions.forEach(parseExpression)
}
function parseFunctionDeclaration(node: ast.FunctionDeclaration) {
parseBlockStatement(node.body)
}
function parseTSEnumDeclaration(node: ast.TSEnumDeclaration) {
for (const member of node.members) {
parseTSEnumMember(member)
}
}
function parseTSEnumMember(node: ast.TSEnumMember) {
if (node.initializer) {
parseExpression(node.initializer)
}
}
function parseFunctionExpression(node: ast.FunctionExpression) {
parseBlockStatement(node.body)
}
function parseArrowFunctionExpression(node: ast.ArrowFunctionExpression) {
switch (node.body.type) {
case AST_NODE_TYPES.BlockStatement:
parseBlockStatement(node.body)
break
default:
parseExpression(node.body)
}
}
function parseClassDeclaration(node: ast.ClassDeclaration) {
parseClassBody(node.body)
}
function parseClassBody(node: ast.ClassBody) {
for (const el of node.body) {
parseClassElement(el)
}
}
function parseClassElement(node: ast.ClassElement) {
switch (node.type) {
case AST_NODE_TYPES.PropertyDefinition:
if (node.value) {
parseExpression(node.value)
}
break
case AST_NODE_TYPES.MethodDefinition:
if (node.value.type === AST_NODE_TYPES.FunctionExpression) parseFunctionExpression(node.value)
break
case AST_NODE_TYPES.StaticBlock:
node.body.forEach(parseStatement)
break
}
}
function parseBindingName(node: ast.BindingName) {
switch (node.type) {
case AST_NODE_TYPES.ArrayPattern:
parseArrayPattern(node)
break
case AST_NODE_TYPES.ObjectPattern:
parseObjectPattern(node)
break
}
}
function parseArrayExpression(node: ast.ArrayExpression) {
node.elements.forEach(parseExpression)
}
}
export function find(code: string, position: number, jsxPropImportChecking: boolean) {
let token: ExtractedToken | undefined
let program: ast.Program
try {
program = parse(code, { jsx: true, range: true })
} catch {
return token
}
const ctx = createContext(program, jsxPropImportChecking)
program.body.forEach(parseStatement)
return token
function createContext(program: ast.Program, jsxPropChecking = true) {
let jsxProp = !jsxPropChecking
const twTemplate = new Set<string>()
const themeTemplate = new Set<string>()
const screenTemplate = new Set<string>()
for (const node of program.body) {
switch (node.type) {
case AST_NODE_TYPES.ImportDeclaration:
if (node.source.value === twinLabel) {
jsxProp = true
for (const clause of node.specifiers) {
switch (clause.type) {
case AST_NODE_TYPES.ImportDefaultSpecifier:
twTemplate.add(clause.local.name)
break
case AST_NODE_TYPES.ImportSpecifier:
if (clause.imported.name === "default") {
twTemplate.add(clause.local.name)
} else if (clause.imported.name === ExtractedTokenKind.TwinTheme) {
themeTemplate.add(clause.local.name)
} else if (clause.imported.name === ExtractedTokenKind.TwinScreen) {
screenTemplate.add(clause.local.name)
}
break
}
}
}
break
}
}
return { jsxProp, twTemplate, themeTemplate, screenTemplate }
}
function inRange(node: ast.Node): boolean {
return !(position < node.range[0] + 1 || position >= node.range[1])
}
function parseTaggedTemplateExpression(node: ast.TaggedTemplateExpression) {
if (node.tag.type !== AST_NODE_TYPES.Identifier) {
parseExpression(node.tag)
return
} else if (ctx.twTemplate.has(node.tag.name)) {
if (node.quasi.quasis.length === 1) {
const n: ast.TemplateElement = node.quasi.quasis[0]
if (!inRange(n)) return
token = {
kind: ExtractedTokenKind.Twin,
start: n.range[0] + 1,
end: n.range[1] - 1,
value: n.value.cooked,
}
return
}
} else if (ctx.themeTemplate.has(node.tag.name)) {
if (node.quasi.quasis.length === 1) {
const n: ast.TemplateElement = node.quasi.quasis[0]
if (!inRange(n)) return
token = {
kind: ExtractedTokenKind.TwinTheme,
start: n.range[0] + 1,
end: n.range[1] - 1,
value: n.value.cooked,
}
return
}
} else if (ctx.screenTemplate.has(node.tag.name)) {
if (node.quasi.quasis.length === 1) {
const n: ast.TemplateElement = node.quasi.quasis[0]
if (!inRange(n)) return
token = {
kind: ExtractedTokenKind.TwinScreen,
start: n.range[0] + 1,
end: n.range[1] - 1,
value: n.value.cooked,
}
return
}
} else {
parseTemplateLiteral(node.quasi)
}
}
function parseCallExpression(node: ast.CallExpression) {
parseExpression(node.callee)
for (const a of node.arguments) {
switch (a.type) {
case AST_NODE_TYPES.SpreadElement:
parseExpression(a.argument)
break
default:
parseExpression(a)
}
}
}
function parseJSXAttribute(node: ast.JSXAttribute) {
if (node.name.type === AST_NODE_TYPES.JSXIdentifier) {
if (ctx.jsxProp && node.name.name === ExtractedTokenKind.Twin) {
if (node.value) getToken(node.value, ExtractedTokenKind.Twin)
} else if (ctx.jsxProp && node.name.name === ExtractedTokenKind.TwinCssProperty) {
if (node.value) getToken(node.value, ExtractedTokenKind.TwinCssProperty)
} else if (node.value && node.value.type !== AST_NODE_TYPES.Literal) {
parseJSXExpression(node.value)
}
}
return
function getToken(node: ast.Literal | ast.JSXExpression, kind: ExtractedTokenKind) {
switch (node.type) {
case AST_NODE_TYPES.JSXEmptyExpression:
break
case AST_NODE_TYPES.Literal:
if (!inRange(node)) return
if (typeof node.value === "string") {
token = {
kind,
start: node.range[0] + 1,
end: node.range[1] - 1,
value: node.value,
}
return
}
break
case AST_NODE_TYPES.JSXExpressionContainer:
if (node.expression.type === AST_NODE_TYPES.Literal) {
if (!inRange(node.expression)) return
if (typeof node.expression.value === "string") {
token = {
kind,
start: node.expression.range[0] + 1,
end: node.expression.range[1] - 1,
value: node.expression.value,
}
}
} else if (node.expression.type !== AST_NODE_TYPES.JSXEmptyExpression) {
parseExpression(node.expression)
}
break
case AST_NODE_TYPES.JSXSpreadChild:
if (node.expression.type !== AST_NODE_TYPES.JSXEmptyExpression) {
parseExpression(node.expression)
}
break
}
}
}
function parseJSXElement(node: ast.JSXElement) {
parseJSXOpeningElement(node.openingElement)
node.children.forEach(parseJSXChild)
}
function parseJSXOpeningElement(node: ast.JSXOpeningElement) {
for (const attr of node.attributes) {
switch (attr.type) {
case AST_NODE_TYPES.JSXAttribute:
parseJSXAttribute(attr)
break
default:
parseJSXSpreadAttribute(attr)
break
}
}
}
function parseJSXChild(node: ast.JSXChild) {
if (!inRange(node)) return
switch (node.type) {
case AST_NODE_TYPES.JSXElement:
parseJSXElement(node)
break
case AST_NODE_TYPES.JSXFragment:
parseJSXFragment(node)
break
case AST_NODE_TYPES.JSXText:
break
default:
parseJSXExpression(node)
break
}
}
function parseJSXFragment(node: ast.JSXFragment) {
node.children.forEach(parseJSXChild)
}
function parseJSXSpreadAttribute(node: ast.JSXSpreadAttribute) {
parseExpression(node.argument)
}
function parseJSXExpression(node: ast.JSXExpression) {
switch (node.type) {
case AST_NODE_TYPES.JSXEmptyExpression:
break
case AST_NODE_TYPES.JSXSpreadChild:
if (node.expression.type !== AST_NODE_TYPES.JSXEmptyExpression) {
parseExpression(node.expression)
}
break
case AST_NODE_TYPES.JSXExpressionContainer:
if (node.expression.type !== AST_NODE_TYPES.JSXEmptyExpression) {
parseExpression(node.expression)
}
break
}
}
function parseExportDefaultDeclaration(node: ast.ExportDefaultDeclaration) {
parseDeclaration(node.declaration)
}
function parseVariableDeclaration(node: ast.VariableDeclaration) {
node.declarations.forEach(parseVariableDeclarator)
}
function parseExpression(node: ast.Expression) {
if (!inRange(node)) return
// LiteralExpression | LogicalExpression | MemberExpression | MetaProperty | NewExpression | ObjectPattern | Super | ThisExpression | TSAsExpression | TSNonNullExpression | TSTypeAssertion;
switch (node.type) {
case AST_NODE_TYPES.TaggedTemplateExpression:
parseTaggedTemplateExpression(node)
break
case AST_NODE_TYPES.TemplateLiteral:
parseTemplateLiteral(node)
break
case AST_NODE_TYPES.SequenceExpression:
node.expressions.forEach(parseExpression)
break
case AST_NODE_TYPES.ArrayExpression:
parseArrayExpression(node)
break
case AST_NODE_TYPES.ArrayPattern:
parseArrayPattern(node)
break
case AST_NODE_TYPES.FunctionExpression:
parseFunctionExpression(node)
break
case AST_NODE_TYPES.ArrowFunctionExpression:
parseArrowFunctionExpression(node)
break
case AST_NODE_TYPES.AssignmentExpression:
parseExpression(node.right)
break
case AST_NODE_TYPES.ConditionalExpression:
parseExpression(node.consequent)
parseExpression(node.alternate)
break
case AST_NODE_TYPES.LogicalExpression:
parseExpression(node.right)
break
case AST_NODE_TYPES.MemberExpression:
if (node.property.type !== AST_NODE_TYPES.PrivateIdentifier) {
parseExpression(node.property)
}
break
case AST_NODE_TYPES.BinaryExpression:
parseExpression(node.right)
break
case AST_NODE_TYPES.UpdateExpression:
parseExpression(node.argument)
break
case AST_NODE_TYPES.AwaitExpression:
parseExpression(node.argument)
break
case AST_NODE_TYPES.YieldExpression:
if (node.argument) parseExpression(node.argument)
break
case AST_NODE_TYPES.ObjectExpression:
for (const el of node.properties) {
parseObjectLiteralElement(el)
}
break
case AST_NODE_TYPES.ClassExpression:
parseClassBody(node.body)
break
case AST_NODE_TYPES.ChainExpression:
parseExpression(node.expression)
break
case AST_NODE_TYPES.CallExpression:
parseCallExpression(node)
break
case AST_NODE_TYPES.UnaryExpression:
parseUnaryExpression(node)
break
case AST_NODE_TYPES.ImportExpression:
parseExpression(node.source)
break
case AST_NODE_TYPES.JSXElement:
parseJSXElement(node)
break
case AST_NODE_TYPES.JSXFragment:
parseJSXFragment(node)
break
case AST_NODE_TYPES.Identifier:
break
case AST_NODE_TYPES.ThisExpression:
break
}
}
function parseDeclaration(node: ast.ExportDeclaration | ast.Expression) {
if (!inRange(node)) return
switch (node.type) {
case AST_NODE_TYPES.ClassDeclaration:
parseClassDeclaration(node)
break
case AST_NODE_TYPES.ClassExpression:
parseClassBody(node.body)
break
case AST_NODE_TYPES.FunctionDeclaration:
parseFunctionDeclaration(node)
break
case AST_NODE_TYPES.TSEnumDeclaration:
parseTSEnumDeclaration(node)
break
case AST_NODE_TYPES.VariableDeclaration:
parseVariableDeclaration(node)
break
case AST_NODE_TYPES.TSDeclareFunction:
case AST_NODE_TYPES.TSInterfaceDeclaration:
case AST_NODE_TYPES.TSModuleDeclaration:
case AST_NODE_TYPES.TSTypeAliasDeclaration:
break
default:
parseExpression(node)
}
}
function parseStatement(node: ast.Statement) {
if (!inRange(node)) return
switch (node.type) {
case AST_NODE_TYPES.BlockStatement:
parseBlockStatement(node)
break
case AST_NODE_TYPES.ClassDeclaration:
parseClassDeclaration(node)
break
case AST_NODE_TYPES.DoWhileStatement:
parseStatement(node.body)
break
case AST_NODE_TYPES.ExportDefaultDeclaration:
parseExportDefaultDeclaration(node)
break
case AST_NODE_TYPES.ExpressionStatement:
parseExpression(node.expression)
break
case AST_NODE_TYPES.ForInStatement:
parseExpression(node.right)
parseStatement(node.body)
break
case AST_NODE_TYPES.ForOfStatement:
parseExpression(node.right)
parseStatement(node.body)
break
case AST_NODE_TYPES.ForStatement:
if (node.init) {
if (node.init.type === AST_NODE_TYPES.VariableDeclaration) parseVariableDeclaration(node.init)
else parseExpression(node.init)
}
if (node.test) {
parseExpression(node.test)
}
if (node.update) {
parseExpression(node.update)
}
parseStatement(node.body)
break
case AST_NODE_TYPES.FunctionDeclaration:
parseFunctionDeclaration(node)
break
case AST_NODE_TYPES.IfStatement:
parseExpression(node.test)
if (node.alternate) parseStatement(node.alternate)
parseStatement(node.consequent)
break
case AST_NODE_TYPES.ReturnStatement:
if (node.argument) parseExpression(node.argument)
break
case AST_NODE_TYPES.ThrowStatement:
if (node.argument && node.argument.type !== AST_NODE_TYPES.TSAsExpression) parseStatement(node.argument)
break
case AST_NODE_TYPES.SwitchStatement:
parseExpression(node.discriminant)
for (const cs of node.cases) {
if (cs.test) parseExpression(cs.test)
cs.consequent.forEach(parseStatement)
}
break
case AST_NODE_TYPES.TryStatement:
parseStatement(node.block)
if (node.handler) {
if (node.handler.param) parseBindingName(node.handler.param)
parseBlockStatement(node.handler.body)
}
if (node.finalizer) parseStatement(node.finalizer)
break
case AST_NODE_TYPES.TSEnumDeclaration:
parseTSEnumDeclaration(node)
break
case AST_NODE_TYPES.TSExportAssignment:
parseExpression(node.expression)
break
case AST_NODE_TYPES.VariableDeclaration:
node.declarations.forEach(parseVariableDeclarator)
break
case AST_NODE_TYPES.WhileStatement:
parseExpression(node.test)
parseStatement(node.body)
break
case AST_NODE_TYPES.WithStatement:
parseExpression(node.object)
parseStatement(node.body)
break
case AST_NODE_TYPES.ExportNamedDeclaration:
if (node.declaration) parseDeclaration(node.declaration)
break
case AST_NODE_TYPES.ImportDeclaration:
case AST_NODE_TYPES.TSModuleDeclaration:
case AST_NODE_TYPES.TSNamespaceExportDeclaration:
case AST_NODE_TYPES.TSTypeAliasDeclaration:
case AST_NODE_TYPES.TSImportEqualsDeclaration:
case AST_NODE_TYPES.BreakStatement:
case AST_NODE_TYPES.ContinueStatement:
case AST_NODE_TYPES.DebuggerStatement:
case AST_NODE_TYPES.ExportAllDeclaration:
case AST_NODE_TYPES.LabeledStatement:
break
}
}
function parseBlockStatement(node: ast.BlockStatement) {
node.body.forEach(parseStatement)
}
function parseVariableDeclarator(node: ast.VariableDeclarator) {
parseBindingName(node.id)
if (node.init) parseExpression(node.init)
}
function parseDestructuringPattern(node: ast.DestructuringPattern | null) {
if (node) {
if (!inRange(node)) return
switch (node.type) {
case AST_NODE_TYPES.ArrayPattern:
node.elements.forEach(parseDestructuringPattern)
for (const el of node.elements) {
if (el) parseDestructuringPattern(el)
}
break
case AST_NODE_TYPES.AssignmentPattern:
parseExpression(node.right)
break
}
}
}
function parseMethodDefinition(node: ast.MethodDefinition) {
if (node.value.type === AST_NODE_TYPES.FunctionExpression) parseFunctionExpression(node.value)
}
function parseArrayPattern(node: ast.ArrayPattern) {
for (const el of node.elements) {
if (el) parseDestructuringPattern(el)
}
}
function parseProperty(node: ast.Property) {
if (node.computed) parseExpression(node.key)
switch (node.value.type) {
case AST_NODE_TYPES.AssignmentPattern:
parseExpression(node.value.right)
break
case AST_NODE_TYPES.ArrayPattern:
parseArrayPattern(node.value)
break
case AST_NODE_TYPES.ObjectPattern:
parseObjectPattern(node.value)
break
case AST_NODE_TYPES.Identifier:
break
case AST_NODE_TYPES.TSEmptyBodyFunctionExpression:
break
default:
parseExpression(node.value)
}
}
function parseRestElement(node: ast.RestElement) {
if (node.value) {
parseExpression(node.value.right)
}
}
function parseObjectPattern(node: ast.ObjectPattern) {
for (const prop of node.properties) {
if (prop.type === AST_NODE_TYPES.Property) {
parseProperty(prop)
} else {
parseRestElement(prop)
}
}
}
function parseObjectLiteralElement(node: ast.ObjectLiteralElement) {
switch (node.type) {
case AST_NODE_TYPES.MethodDefinition:
parseMethodDefinition(node)
break
case AST_NODE_TYPES.Property:
parseProperty(node)
break
case AST_NODE_TYPES.SpreadElement:
parseExpression(node.argument)
break
}
}
function parseUnaryExpression(node: ast.UnaryExpression) {
switch (node.argument.type) {
case AST_NODE_TYPES.Literal:
break
case AST_NODE_TYPES.UnaryExpression:
parseUnaryExpression(node.argument)
break
default:
parseExpression(node.argument)
break
}
}
function parseTemplateLiteral(node: ast.TemplateLiteral) {
node.expressions.forEach(parseExpression)
}
function parseFunctionDeclaration(node: ast.FunctionDeclaration) {
parseBlockStatement(node.body)
}
function parseTSEnumDeclaration(node: ast.TSEnumDeclaration) {
for (const member of node.members) {
parseTSEnumMember(member)
}
}
function parseTSEnumMember(node: ast.TSEnumMember) {
if (node.initializer) {
parseExpression(node.initializer)
}
}
function parseFunctionExpression(node: ast.FunctionExpression) {
parseBlockStatement(node.body)
}
function parseArrowFunctionExpression(node: ast.ArrowFunctionExpression) {
switch (node.body.type) {
case AST_NODE_TYPES.BlockStatement:
parseBlockStatement(node.body)
break
default:
parseExpression(node.body)
}
}
function parseClassDeclaration(node: ast.ClassDeclaration) {
parseClassBody(node.body)
}
function parseClassBody(node: ast.ClassBody) {
for (const el of node.body) {
parseClassElement(el)
}
}
function parseClassElement(node: ast.ClassElement) {
switch (node.type) {
case AST_NODE_TYPES.PropertyDefinition:
if (node.value) {
parseExpression(node.value)
}
break
case AST_NODE_TYPES.MethodDefinition:
if (node.value.type === AST_NODE_TYPES.FunctionExpression) parseFunctionExpression(node.value)
break
case AST_NODE_TYPES.StaticBlock:
node.body.forEach(parseStatement)
break
}
}
function parseBindingName(node: ast.BindingName) {
if (!inRange(node)) return
switch (node.type) {
case AST_NODE_TYPES.ArrayPattern:
parseArrayPattern(node)
break
case AST_NODE_TYPES.ObjectPattern:
parseObjectPattern(node)
break
}
}
function parseArrayExpression(node: ast.ArrayExpression) {
node.elements.forEach(parseExpression)
}
}
export const typescriptExtractor: Extractor = {
findAll(languageId, code, jsxPropImportChecking) {
return findAll(code, jsxPropImportChecking)
},
find(languageId, code, position, hover, jsxPropImportChecking) {
const pos = position + (hover ? 1 : 0)
return find(code, pos, jsxPropImportChecking)
},
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/imagesOperationsMappers";
import * as Parameters from "../models/parameters";
import { ImageSearchClientContext } from "../imageSearchClientContext";
/** Class representing a ImagesOperations. */
export class ImagesOperations {
private readonly client: ImageSearchClientContext;
/**
* Create a ImagesOperations.
* @param {ImageSearchClientContext} client Reference to the service client.
*/
constructor(client: ImageSearchClientContext) {
this.client = client;
}
/**
* @summary The Image Search API lets you send a search query to Bing and get back a list of
* relevant images. This section provides technical details about the query parameters and headers
* that you use to request images and the JSON response objects that contain them. For examples
* that show how to make requests, see [Searching the Web for
* Images](https://docs.microsoft.com/azure/cognitive-services/bing-image-search/search-the-web).
* @param query The user's search query term. The term cannot be empty. The term may contain [Bing
* Advanced Operators](http://msdn.microsoft.com/library/ff795620.aspx). For example, to limit
* images to a specific domain, use the [site:](http://msdn.microsoft.com/library/ff795613.aspx)
* operator. To help improve relevance of an insights query (see
* [insightsToken](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#insightstoken)),
* you should always include the user's query term. Use this parameter only with the Image Search
* API.Do not specify this parameter when calling the Trending Images API.
* @param [options] The optional parameters
* @returns Promise<Models.ImagesSearchResponse>
*/
search(query: string, options?: Models.ImagesSearchOptionalParams): Promise<Models.ImagesSearchResponse>;
/**
* @param query The user's search query term. The term cannot be empty. The term may contain [Bing
* Advanced Operators](http://msdn.microsoft.com/library/ff795620.aspx). For example, to limit
* images to a specific domain, use the [site:](http://msdn.microsoft.com/library/ff795613.aspx)
* operator. To help improve relevance of an insights query (see
* [insightsToken](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#insightstoken)),
* you should always include the user's query term. Use this parameter only with the Image Search
* API.Do not specify this parameter when calling the Trending Images API.
* @param callback The callback
*/
search(query: string, callback: msRest.ServiceCallback<Models.Images>): void;
/**
* @param query The user's search query term. The term cannot be empty. The term may contain [Bing
* Advanced Operators](http://msdn.microsoft.com/library/ff795620.aspx). For example, to limit
* images to a specific domain, use the [site:](http://msdn.microsoft.com/library/ff795613.aspx)
* operator. To help improve relevance of an insights query (see
* [insightsToken](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#insightstoken)),
* you should always include the user's query term. Use this parameter only with the Image Search
* API.Do not specify this parameter when calling the Trending Images API.
* @param options The optional parameters
* @param callback The callback
*/
search(query: string, options: Models.ImagesSearchOptionalParams, callback: msRest.ServiceCallback<Models.Images>): void;
search(query: string, options?: Models.ImagesSearchOptionalParams | msRest.ServiceCallback<Models.Images>, callback?: msRest.ServiceCallback<Models.Images>): Promise<Models.ImagesSearchResponse> {
return this.client.sendOperationRequest(
{
query,
options
},
searchOperationSpec,
callback) as Promise<Models.ImagesSearchResponse>;
}
/**
* @summary The Image Detail Search API lets you search on Bing and get back insights about an
* image, such as webpages that include the image. This section provides technical details about
* the query parameters and headers that you use to request insights of images and the JSON
* response objects that contain them. For examples that show how to make requests, see [Searching
* the Web for
* Images](https://docs.microsoft.com/azure/cognitive-services/bing-image-search/search-the-web).
* @param query The user's search query term. The term cannot be empty. The term may contain [Bing
* Advanced Operators](http://msdn.microsoft.com/library/ff795620.aspx). For example, to limit
* images to a specific domain, use the [site:](http://msdn.microsoft.com/library/ff795613.aspx)
* operator. To help improve relevance of an insights query (see
* [insightsToken](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#insightstoken)),
* you should always include the user's query term. Use this parameter only with the Image Search
* API.Do not specify this parameter when calling the Trending Images API.
* @param [options] The optional parameters
* @returns Promise<Models.ImagesDetailsResponse>
*/
details(query: string, options?: Models.ImagesDetailsOptionalParams): Promise<Models.ImagesDetailsResponse>;
/**
* @param query The user's search query term. The term cannot be empty. The term may contain [Bing
* Advanced Operators](http://msdn.microsoft.com/library/ff795620.aspx). For example, to limit
* images to a specific domain, use the [site:](http://msdn.microsoft.com/library/ff795613.aspx)
* operator. To help improve relevance of an insights query (see
* [insightsToken](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#insightstoken)),
* you should always include the user's query term. Use this parameter only with the Image Search
* API.Do not specify this parameter when calling the Trending Images API.
* @param callback The callback
*/
details(query: string, callback: msRest.ServiceCallback<Models.ImageInsights>): void;
/**
* @param query The user's search query term. The term cannot be empty. The term may contain [Bing
* Advanced Operators](http://msdn.microsoft.com/library/ff795620.aspx). For example, to limit
* images to a specific domain, use the [site:](http://msdn.microsoft.com/library/ff795613.aspx)
* operator. To help improve relevance of an insights query (see
* [insightsToken](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#insightstoken)),
* you should always include the user's query term. Use this parameter only with the Image Search
* API.Do not specify this parameter when calling the Trending Images API.
* @param options The optional parameters
* @param callback The callback
*/
details(query: string, options: Models.ImagesDetailsOptionalParams, callback: msRest.ServiceCallback<Models.ImageInsights>): void;
details(query: string, options?: Models.ImagesDetailsOptionalParams | msRest.ServiceCallback<Models.ImageInsights>, callback?: msRest.ServiceCallback<Models.ImageInsights>): Promise<Models.ImagesDetailsResponse> {
return this.client.sendOperationRequest(
{
query,
options
},
detailsOperationSpec,
callback) as Promise<Models.ImagesDetailsResponse>;
}
/**
* @summary The Image Trending Search API lets you search on Bing and get back a list of images
* that are trending based on search requests made by others. The images are broken out into
* different categories. For example, Popular People Searches. For a list of markets that support
* trending images, see [Trending
* Images](https://docs.microsoft.com/en-us/azure/cognitive-services/bing-image-search/trending-images).
* @param [options] The optional parameters
* @returns Promise<Models.ImagesTrendingResponse>
*/
trending(options?: Models.ImagesTrendingOptionalParams): Promise<Models.ImagesTrendingResponse>;
/**
* @param callback The callback
*/
trending(callback: msRest.ServiceCallback<Models.TrendingImages>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
trending(options: Models.ImagesTrendingOptionalParams, callback: msRest.ServiceCallback<Models.TrendingImages>): void;
trending(options?: Models.ImagesTrendingOptionalParams | msRest.ServiceCallback<Models.TrendingImages>, callback?: msRest.ServiceCallback<Models.TrendingImages>): Promise<Models.ImagesTrendingResponse> {
return this.client.sendOperationRequest(
{
options
},
trendingOperationSpec,
callback) as Promise<Models.ImagesTrendingResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const searchOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "images/search",
urlParameters: [
Parameters.endpoint
],
queryParameters: [
Parameters.aspect,
Parameters.color,
Parameters.countryCode,
Parameters.count,
Parameters.freshness,
Parameters.height,
Parameters.id,
Parameters.imageContent,
Parameters.imageType,
Parameters.license,
Parameters.market,
Parameters.maxFileSize,
Parameters.maxHeight,
Parameters.maxWidth,
Parameters.minFileSize,
Parameters.minHeight,
Parameters.minWidth,
Parameters.offset,
Parameters.query,
Parameters.safeSearch,
Parameters.size,
Parameters.setLang,
Parameters.width
],
headerParameters: [
Parameters.xBingApisSDK,
Parameters.acceptLanguage,
Parameters.userAgent,
Parameters.clientId,
Parameters.clientIp,
Parameters.location
],
responses: {
200: {
bodyMapper: Mappers.Images
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const detailsOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "images/details",
urlParameters: [
Parameters.endpoint
],
queryParameters: [
Parameters.cropBottom,
Parameters.cropLeft,
Parameters.cropRight,
Parameters.cropTop,
Parameters.cropType,
Parameters.countryCode,
Parameters.id,
Parameters.imageUrl,
Parameters.insightsToken,
Parameters.modules,
Parameters.market,
Parameters.query,
Parameters.safeSearch,
Parameters.setLang
],
headerParameters: [
Parameters.xBingApisSDK,
Parameters.acceptLanguage,
Parameters.contentType,
Parameters.userAgent,
Parameters.clientId,
Parameters.clientIp,
Parameters.location
],
responses: {
200: {
bodyMapper: Mappers.ImageInsights
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const trendingOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "images/trending",
urlParameters: [
Parameters.endpoint
],
queryParameters: [
Parameters.countryCode,
Parameters.market,
Parameters.safeSearch,
Parameters.setLang
],
headerParameters: [
Parameters.xBingApisSDK,
Parameters.acceptLanguage,
Parameters.userAgent,
Parameters.clientId,
Parameters.clientIp,
Parameters.location
],
responses: {
200: {
bodyMapper: Mappers.TrendingImages
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
}; | the_stack |
import * as _ from 'lodash';
import { safeYAMLToJS, safeJSToYAML } from '@console/shared/src/utils/yaml';
import { ImageOptionFormData } from '../sections/ImagesSection';
import { BuildConfig, BuildConfigTrigger, ImageReference } from '../types';
import { BuildConfigFormikValues } from './types';
const deleteKeys = (object: Record<string, any>, ...keys: string[]) => {
keys.forEach((key) => delete object[key]);
};
const convertFormDataNameToBuildConfig = (
values: BuildConfigFormikValues,
buildConfig: BuildConfig,
) => {
buildConfig.metadata.name = values.formData.name;
};
const convertFormDataToBuildConfigSource = (
values: BuildConfigFormikValues,
buildConfig: BuildConfig,
) => {
switch (values.formData.source.type) {
case 'git': {
const { git } = values.formData.source.git;
buildConfig.spec.source = {
...buildConfig.spec.source,
type: 'Git',
git: git.ref
? {
uri: git.url,
ref: git.ref,
}
: {
uri: git.url,
},
contextDir: git.dir,
};
if (git.secret) {
buildConfig.spec.source.sourceSecret = { name: git.secret };
} else {
delete buildConfig.spec.source.sourceSecret;
}
deleteKeys(buildConfig.spec.source, 'dockerfile');
// Set default 'Source' strategy if no strategy is defined yet.
if (!buildConfig.spec.strategy?.type) {
buildConfig.spec.strategy = {
type: values.formData.images.strategyType || 'Source',
...buildConfig.spec.strategy,
};
}
// Updates both app.openshift.io/vcs-* annotations only if the url exists
// so that we set the branch also if it was not defined earlier.
if (buildConfig.metadata.annotations?.['app.openshift.io/vcs-uri']) {
buildConfig.metadata.annotations['app.openshift.io/vcs-uri'] = git.url;
if (git.ref) {
buildConfig.metadata.annotations['app.openshift.io/vcs-ref'] = git.ref;
} else {
delete buildConfig.metadata.annotations['app.openshift.io/vcs-ref'];
}
}
break;
}
case 'dockerfile': {
buildConfig.spec.source = {
...buildConfig.spec.source,
type: 'Dockerfile',
dockerfile: values.formData.source.dockerfile,
};
deleteKeys(buildConfig.spec.source, 'git');
// Set default 'Docker' strategy if no strategy is defined yet.
if (!buildConfig.spec.strategy?.type) {
buildConfig.spec.strategy = {
type: values.formData.images.strategyType || 'Docker',
...buildConfig.spec.strategy,
};
}
break;
}
case 'binary': {
buildConfig.spec.source = {
...buildConfig.spec.source,
type: 'Binary',
};
// Set default 'Source' strategy if no strategy is defined yet.
if (!buildConfig.spec.strategy?.type) {
buildConfig.spec.strategy = {
type: values.formData.images.strategyType || 'Source',
...buildConfig.spec.strategy,
};
}
break;
}
default:
// nothing
}
};
const convertImageOptionFormDataToImageReference = (
imageOptionFormData: ImageOptionFormData,
buildConfigNamespace: string,
): ImageReference => {
if (imageOptionFormData.type === 'imageStreamTag') {
const { namespace, image = '', tag } = imageOptionFormData.imageStreamTag.imageStream;
const name = tag ? `${image}:${tag}` : image;
return namespace === buildConfigNamespace
? {
kind: 'ImageStreamTag',
name,
}
: {
kind: 'ImageStreamTag',
namespace,
name,
};
}
if (imageOptionFormData.type === 'imageStreamImage') {
const image = imageOptionFormData.imageStreamImage;
const namespace = image.includes('/')
? image.substring(0, image.indexOf('/'))
: buildConfigNamespace;
const name = image.includes('/') ? image.substring(image.indexOf('/') + 1) : image;
return {
kind: 'ImageStreamImage',
namespace,
name,
};
}
if (imageOptionFormData.type === 'dockerImage') {
return {
kind: 'DockerImage',
name: imageOptionFormData.dockerImage,
};
}
return null;
};
const convertFormDataImagesToBuildConfig = (
values: BuildConfigFormikValues,
buildConfig: BuildConfig,
) => {
// Build from => Strategy
const from = convertImageOptionFormDataToImageReference(
values.formData.images.buildFrom,
buildConfig.metadata.namespace,
);
// The strategy object is automatically created in convertFormDataToBuildConfigSource
// if the source type is known. Fallback to Source strategy here if an image is selected
// without any information about the strategy type.
if (from && !buildConfig.spec.strategy?.type) {
buildConfig.spec.strategy = {
type: values.formData.images.strategyType || 'Source',
...buildConfig.spec.strategy,
};
}
const strategyKey = `${buildConfig.spec.strategy?.type?.toLowerCase()}Strategy`;
if (from && !buildConfig.spec.strategy?.[strategyKey]) {
buildConfig.spec.strategy[strategyKey] = { from };
} else if (from) {
buildConfig.spec.strategy[strategyKey].from = from;
} else if (buildConfig.spec.strategy?.[strategyKey]) {
delete buildConfig.spec.strategy[strategyKey].from;
}
// Push to => Output
const to = convertImageOptionFormDataToImageReference(
values.formData.images.pushTo,
buildConfig.metadata.namespace,
);
if (to && !buildConfig.spec.output) {
buildConfig.spec.output = { to };
} else if (to) {
buildConfig.spec.output.to = to;
} else if (buildConfig.spec.output) {
delete buildConfig.spec.output.to;
}
};
const convertFormDataEnvironmentVariablesToBuildConfig = (
values: BuildConfigFormikValues,
buildConfig: BuildConfig,
) => {
const env = values.formData.environmentVariables;
// The strategy object is automatically created in convertFormDataToBuildConfigSource
// if the source type is known. Fallback to Source strategy here if some
// environment variables are defined.
if (env.length > 0 && !buildConfig.spec.strategy?.type) {
buildConfig.spec.strategy = {
type: values.formData.images.strategyType || 'Source',
...buildConfig.spec.strategy,
};
}
const strategyKey = `${buildConfig.spec.strategy?.type?.toLowerCase()}Strategy`;
if (env.length > 0 && !buildConfig.spec.strategy?.[strategyKey]) {
buildConfig.spec.strategy[strategyKey] = { env };
} else if (env.length > 0) {
buildConfig.spec.strategy[strategyKey].env = env;
} else if (buildConfig.spec.strategy?.[strategyKey]) {
delete buildConfig.spec.strategy[strategyKey].env;
}
};
const convertFormDataTriggersToBuildConfig = (
values: BuildConfigFormikValues,
buildConfig: BuildConfig,
) => {
const triggers: BuildConfigTrigger[] = [];
if (values.formData.triggers?.configChange) {
triggers.push({ type: 'ConfigChange' });
}
if (values.formData.triggers?.imageChange) {
triggers.push({ type: 'ImageChange' });
}
if (values.formData.triggers?.otherTriggers) {
triggers.push(
...values.formData.triggers.otherTriggers
.filter((trigger) => trigger.type)
.map(
(trigger) =>
({
type: trigger.type,
[trigger.type.toLowerCase()]: { secret: trigger.secret },
} as BuildConfigTrigger),
),
);
}
if (triggers.length > 0) {
buildConfig.spec.triggers = triggers;
} else {
delete buildConfig.spec.triggers;
}
};
const convertFormDataSecretsToBuildConfig = (
values: BuildConfigFormikValues,
buildConfig: BuildConfig,
) => {
const secrets = values.formData.secrets.map((secret) => ({
secret: { name: secret.secret },
destinationDir: secret.mountPoint,
}));
// The source object is automatically created in convertFormDataToBuildConfigSource
// if the source type is known. Fallback to Source source here if some secrets are defined.
if (secrets.length > 0 && !buildConfig.spec.source?.type) {
buildConfig.spec.source = {
type: 'Source',
...buildConfig.spec.source,
};
}
if (secrets.length > 0) {
buildConfig.spec.source = {
...buildConfig.spec.source,
secrets,
};
} else if (buildConfig.spec.source?.secrets) {
delete buildConfig.spec.source.secrets;
}
};
const convertFormDataPolicyToBuildConfig = (
values: BuildConfigFormikValues,
buildConfig: BuildConfig,
) => {
if (values.formData.policy.runPolicy) {
buildConfig.spec.runPolicy = values.formData.policy.runPolicy;
} else {
delete buildConfig.spec.runPolicy;
}
};
const convertFormDataHooksToBuildConfig = (
values: BuildConfigFormikValues,
buildConfig: BuildConfig,
) => {
if (values.formData.hooks.enabled) {
if (
values.formData.hooks.type === 'command' &&
values.formData.hooks.commands.some((command) => !!command)
) {
buildConfig.spec.postCommit = {
command: values.formData.hooks.commands,
args: values.formData.hooks.arguments,
};
} else if (values.formData.hooks.type === 'shell') {
buildConfig.spec.postCommit = {
script: values.formData.hooks.shell,
args: values.formData.hooks.arguments,
};
} else if (
(values.formData.hooks.type === 'command' &&
values.formData.hooks.arguments?.some((argument) => !!argument)) ||
values.formData.hooks.type === 'onlyArgs'
) {
buildConfig.spec.postCommit = {
args: values.formData.hooks.arguments,
};
} else {
delete buildConfig.spec.postCommit;
}
} else {
delete buildConfig.spec.postCommit;
}
};
export const convertFormDataToBuildConfig = (
originBuildConfig: BuildConfig,
values: BuildConfigFormikValues,
): BuildConfig => {
// Ensure general format
let buildConfig = _.cloneDeep(originBuildConfig);
if (!buildConfig || typeof buildConfig !== 'object') {
buildConfig = {
apiVersion: 'build.openshift.io/v1',
kind: 'BuildConfig',
metadata: {},
spec: {},
};
}
if (!buildConfig.apiVersion) buildConfig.apiVersion = 'build.openshift.io/v1';
if (!buildConfig.kind) buildConfig.kind = 'BuildConfig';
if (!buildConfig.metadata || typeof buildConfig.metadata !== 'object') buildConfig.metadata = {};
if (!buildConfig.spec || typeof buildConfig.spec !== 'object') buildConfig.spec = {};
// Convert all sections
convertFormDataNameToBuildConfig(values, buildConfig);
convertFormDataToBuildConfigSource(values, buildConfig);
convertFormDataImagesToBuildConfig(values, buildConfig);
convertFormDataEnvironmentVariablesToBuildConfig(values, buildConfig);
convertFormDataTriggersToBuildConfig(values, buildConfig);
convertFormDataSecretsToBuildConfig(values, buildConfig);
convertFormDataPolicyToBuildConfig(values, buildConfig);
convertFormDataHooksToBuildConfig(values, buildConfig);
return buildConfig;
};
export const convertFormDataToYAML = (values: BuildConfigFormikValues): string => {
const parsedBuildConfig = safeYAMLToJS(values.yamlData);
const updatedBuildConfig = convertFormDataToBuildConfig(parsedBuildConfig, values);
return safeJSToYAML(updatedBuildConfig, '', { skipInvalid: true });
}; | the_stack |
import * as fs from 'fs';
import * as ts from 'typescript';
interface Const {
typeName: string // repeated in each const
goType: string
me: ts.Node
name: string // constant's name
value: string // constant's value
}
let Consts: Const[] = [];
let seenConstTypes = new Map<string, boolean>();
interface Struct {
me: ts.Node
name: string
embeds: string[]
fields?: Field[]
}
let Structs: Struct[] = [];
interface Field {
me: ts.Node
id: ts.Identifier
goName: string
optional: boolean
goType: string
json: string
gostuff?: string
substruct?: Field[] // embedded struct from TypeLiteral
}
interface Type {
me: ts.Node
goName: string
goType: string
stuff: string
}
let Types: Type[] = [];
// Used in printing the AST
let seenThings = new Map<string, number>();
function seenAdd(x: string) {
seenThings[x] = (seenThings[x] === undefined ? 1 : seenThings[x] + 1)
}
let dir = process.env['HOME'];
let fnames = [
`/vscode-languageserver-node/protocol/src/protocol.ts`,
`/vscode-languageserver-node/types/src/main.ts`
];
let outFname = '/tmp/tsprotocol.go';
let fda: number, fdb: number, fde: number; // file descriptors
function createOutputFiles() {
fda = fs.openSync('/tmp/ts-a', 'w') // dump of AST
fdb = fs.openSync('/tmp/ts-b', 'w') // unused, for debugging
fde = fs.openSync(outFname, 'w') // generated Go
}
function pra(s: string) {
return (fs.writeSync(fda, s))
}
function prb(s: string) {
return (fs.writeSync(fdb, s))
}
function prgo(s: string) {
return (fs.writeSync(fde, s))
}
function generate(files: string[], options: ts.CompilerOptions): void {
let program = ts.createProgram(files, options);
program.getTypeChecker(); // used for side-effects
// dump the ast, for debugging
for (const sourceFile of program.getSourceFiles()) {
if (!sourceFile.isDeclarationFile) {
// walk the tree to do stuff
ts.forEachChild(sourceFile, describe);
}
}
pra('\n')
for (const key of Object.keys(seenThings).sort()) {
pra(`${key}: ${seenThings[key]}\n`)
}
// visit every sourceFile in the program, generating types
for (const sourceFile of program.getSourceFiles()) {
if (!sourceFile.isDeclarationFile) {
ts.forEachChild(sourceFile, genTypes)
}
}
return;
function genTypes(node: ts.Node) {
// Ignore top-level items with no output
if (ts.isExpressionStatement(node) || ts.isFunctionDeclaration(node) ||
ts.isImportDeclaration(node) || ts.isVariableStatement(node) ||
ts.isExportDeclaration(node) ||
node.kind == ts.SyntaxKind.EndOfFileToken) {
return;
}
if (ts.isInterfaceDeclaration(node)) {
doInterface(node)
return;
} else if (ts.isTypeAliasDeclaration(node)) {
doTypeAlias(node)
} else if (ts.isModuleDeclaration(node)) {
doModuleDeclaration(node)
} else if (ts.isEnumDeclaration(node)) {
doEnumDecl(node)
} else if (ts.isClassDeclaration(node)) {
doClassDeclaration(node)
} else {
throw new Error(`unexpected ${ts.SyntaxKind[node.kind]} ${loc(node)}`)
}
}
function doClassDeclaration(node: ts.ClassDeclaration) {
let id: ts.Identifier
let props = new Array<ts.PropertyDeclaration>()
let extend: ts.HeritageClause;
let bad = false
node.forEachChild((n: ts.Node) => {
if (ts.isIdentifier(n)) {
id = n;
return
}
if (ts.isPropertyDeclaration(n)) {
props.push(n);
return
}
if (n.kind == ts.SyntaxKind.ExportKeyword) {
return
}
if (n.kind == ts.SyntaxKind.Constructor || ts.isMethodDeclaration(n) ||
ts.isGetAccessor(n) || ts.isTypeParameterDeclaration(n)) {
bad = true;
return
}
if (ts.isHeritageClause(n)) {
extend = n;
return
}
throw new Error(`doClass ${loc(n)} ${kinds(n)}`)
})
if (bad) {
// the class is not useful for Go.
return
} // might we want the PropertyDecls? (don't think so)
let fields: Field[] = [];
for (const pr of props) {
fields.push(fromPropDecl(pr))
}
let ans = {
me: node,
name: toGoName(getText(id)),
embeds: heritageStrs(extend),
fields: fields
};
Structs.push(ans)
}
function fromPropDecl(node: ts.PropertyDeclaration): Field {
let id: ts.Identifier;
let opt = false
let typ: ts.Node
node.forEachChild((n: ts.Node) => {
if (ts.isIdentifier(n)) {
id = n;
return
}
if (n.kind == ts.SyntaxKind.QuestionToken) {
opt = true;
return
}
if (typ != undefined)
throw new Error(`fromPropDecl too long ${loc(node)}`)
typ = n
})
let goType = computeType(typ).goType
let ans = {
me: node,
id: id,
goName: toGoName(getText(id)),
optional: opt,
goType: goType,
json: `\`json:"${id.text}${opt ? ',omitempty' : ''}"\``
};
return ans
}
function doInterface(node: ts.InterfaceDeclaration) {
// name: Identifier;
// typeParameters?: NodeArray<TypeParameterDeclaration>;
// heritageClauses?: NodeArray<HeritageClause>;
// members: NodeArray<TypeElement>;
// find the Identifier from children
// process the PropertySignature children
// the members might have generic info, but so do the children
let id: ts.Identifier;
let extend: ts.HeritageClause
let generid: ts.Identifier
let properties = new Array<ts.PropertySignature>()
let index: ts.IndexSignatureDeclaration // generate some sort of map
node.forEachChild((n: ts.Node) => {
if (n.kind == ts.SyntaxKind.ExportKeyword || ts.isMethodSignature(n)) {
// ignore
} else if (ts.isIdentifier(n)) {
id = n;
} else if (ts.isHeritageClause(n)) {
extend = n;
} else if (ts.isTypeParameterDeclaration(n)) {
// Act as if this is <T = any>
generid = n.name;
} else if (ts.isPropertySignature(n)) {
properties.push(n);
} else if (ts.isIndexSignatureDeclaration(n)) {
if (index !== undefined) {
throw new Error(`${loc(n)} multiple index expressions`)
}
index = n
} else {
throw new Error(`${loc(n)} doInterface ${ts.SyntaxKind[n.kind]} `)
}
})
let fields: Field[] = [];
for (const p of properties) {
fields.push(genProp(p, generid))
}
if (index != undefined) {
fields.push(fromIndexSignature(index))
}
const ans = {
me: node,
name: toGoName(getText(id)),
embeds: heritageStrs(extend),
fields: fields
};
Structs.push(ans)
}
function heritageStrs(node: ts.HeritageClause): string[] {
// ExpressionWithTypeArguments+, and each is an Identifier
let ans: string[] = [];
if (node == undefined) {
return ans
}
let x: ts.ExpressionWithTypeArguments[] = []
node.forEachChild((n: ts.Node) => {
if (ts.isExpressionWithTypeArguments(n)) x.push(n)
})
for (const p of x) {
p.forEachChild((n: ts.Node) => {
if (ts.isIdentifier(n)) {
ans.push(toGoName(getText(n)));
return;
}
if (ts.isTypeReferenceNode(n)) {
// don't want these, ignore them
return;
}
throw new Error(`expected Identifier ${loc(n)} ${kinds(p)} `)
})
}
return ans
}
function genProp(node: ts.PropertySignature, gen: ts.Identifier): Field {
let id: ts.Identifier
let thing: ts.Node
let opt = false
node.forEachChild((n: ts.Node) => {
if (ts.isIdentifier(n)) {
id = n
} else if (n.kind == ts.SyntaxKind.QuestionToken) {
opt = true
} else if (n.kind == ts.SyntaxKind.ReadonlyKeyword) {
return
} else {
if (thing !== undefined) {
throw new Error(`${loc(n)} weird`)
}
thing = n
}
})
let goName = toGoName(id.text)
let { goType, gostuff, optional, fields } = computeType(thing)
// Generics
if (gen && gen.text == goType) goType = 'interface{}';
opt = opt || optional;
let ans = {
me: node,
id: id,
goName: goName,
optional: opt,
goType: goType,
gostuff: gostuff,
substruct: fields,
json: `\`json:"${id.text}${opt ? ',omitempty' : ''}"\``
};
// Rather than checking that goName is a const type, just do
switch (goType) {
case 'CompletionItemKind':
case 'TextDocumentSyncKind':
case 'CodeActionKind':
case 'InsertTextFormat': // float64
case 'DiagnosticSeverity':
ans.optional = false
}
return ans
}
function doModuleDeclaration(node: ts.ModuleDeclaration) {
// Export Identifier ModuleBlock
let id: ts.Identifier;
let mb: ts.ModuleBlock;
node.forEachChild((n: ts.Node) => {
if ((ts.isIdentifier(n) && (id = n)) ||
(ts.isModuleBlock(n) && mb === undefined && (mb = n)) ||
(n.kind == ts.SyntaxKind.ExportKeyword)) {
return;
}
throw new Error(`doModuleDecl ${loc(n)} ${ts.SyntaxKind[n.kind]}`)
})
// Don't want FunctionDeclarations
// mb has VariableStatement and useless TypeAliasDeclaration
// some of the VariableStatement are consts, and want their comments
// and each VariableStatement is Export, VariableDeclarationList
// and each VariableDeclarationList is a single VariableDeclaration
let v: ts.VariableDeclaration[] = [];
function f(n: ts.Node) {
if (ts.isVariableDeclaration(n)) {
v.push(n);
return
}
if (ts.isFunctionDeclaration(n)) {
return
}
n.forEachChild(f)
}
f(node)
for (const vx of v) {
if (hasNewExpression(vx)) {
return
}
buildConst(getText(id), vx)
}
}
function buildConst(tname: string, node: ts.VariableDeclaration): Const {
// node is Identifier, optional-goo, (FirstLiteralToken|StringLiteral)
let id: ts.Identifier
let str: string
let first: string
node.forEachChild((n: ts.Node) => {
if (ts.isIdentifier(n)) {
id = n
} else if (ts.isStringLiteral(n)) {
str = getText(n)
} else if (n.kind == ts.SyntaxKind.FirstLiteralToken) {
first = getText(n)
}
})
if (str == undefined && first == undefined) {
return
} // various
const ty = (str != undefined) ? 'string' : 'float64'
const val = (str != undefined) ? str.replace(/'/g, '"') : first
const name = toGoName(getText(id))
const c = {
typeName: tname,
goType: ty,
me: node.parent.parent,
name: name,
value: val
};
Consts.push(c)
return c
}
// is node an ancestor of a NewExpression
function hasNewExpression(n: ts.Node): boolean {
let ans = false;
n.forEachChild((n: ts.Node) => {
if (ts.isNewExpression(n)) ans = true;
})
return ans
}
function doEnumDecl(node: ts.EnumDeclaration) {
// Generates Consts. Identifier EnumMember+
// EnumMember: Identifier StringLiteral
let id: ts.Identifier
let mems: ts.EnumMember[] = []
node.forEachChild((n: ts.Node) => {
if (ts.isIdentifier(n)) {
id = n // check for uniqueness?
} else if (ts.isEnumMember(n)) {
mems.push(n)
} else if (n.kind != ts.SyntaxKind.ExportKeyword) {
throw new Error(`doEnumDecl ${ts.SyntaxKind[n.kind]} ${loc(n)}`)
}
})
for (const m of mems) {
let name: string
let value: string
m.forEachChild((n: ts.Node) => {
if (ts.isIdentifier(n)) {
name = getText(n)
} else if (ts.isStringLiteral(n)) {
value = getText(n).replace(/'/g, '"')
} else {
throw new Error(`in doEnumDecl ${ts.SyntaxKind[n.kind]} ${loc(n)}`)
}
})
let ans = {
typeName: getText(id),
goType: 'string',
me: m,
name: name,
value: value
};
Consts.push(ans)
}
}
// top-level TypeAlias
function doTypeAlias(node: ts.TypeAliasDeclaration) {
// these are all Export Identifier alias
let id: ts.Identifier;
let alias: ts.Node;
let genid: ts.TypeParameterDeclaration // <T>, but we don't care
node.forEachChild((n: ts.Node) => {
if ((ts.isIdentifier(n) && (id = n)) ||
(n.kind == ts.SyntaxKind.ExportKeyword) ||
ts.isTypeParameterDeclaration(n) && (genid = n) ||
(alias === undefined && (alias = n))) {
return
}
throw new Error(`doTypeAlias ${loc(n)} ${ts.SyntaxKind[n.kind]}`)
})
let ans = {
me: node,
id: id,
goName: toGoName(getText(id)),
goType: '?',
stuff: ''
};
if (id.text.indexOf('--') != -1) {
return
} // don't care
if (ts.isUnionTypeNode(alias)) {
ans.goType = weirdUnionType(alias)
if (ans.goType == undefined) { // these are redundant
return
}
Types.push(ans)
return
}
if (ts.isIntersectionTypeNode(alias)) { // a Struct, not a Type
let embeds: string[] = []
alias.forEachChild((n: ts.Node) => {
if (ts.isTypeReferenceNode(n)) {
embeds.push(toGoName(computeType(n).goType))
} else
throw new Error(`expected TypeRef ${ts.SyntaxKind[n.kind]} ${loc(n)}`)
})
let ans = { me: node, name: toGoName(getText(id)), embeds: embeds };
Structs.push(ans)
return
}
if (ts.isArrayTypeNode(alias)) { // []DocumentFilter
ans.goType = '[]DocumentFilter';
Types.push(ans)
return
}
if (ts.isLiteralTypeNode(alias)) {
return // type A = 1, so nope
}
if (ts.isTypeReferenceNode(alias)) {
ans.goType = computeType(alias).goType
if (ans.goType.match(/und/) != null) throw new Error('396')
Types.push(ans) // type A B
return
}
if (alias.kind == ts.SyntaxKind.StringKeyword) { // type A string
ans.goType = 'string';
Types.push(ans);
return
}
throw new Error(`in doTypeAlias ${loc(node)} ${kinds(node)} ${
ts.SyntaxKind[alias.kind]}\n`)
}
// extract the one useful but weird case ()
function weirdUnionType(node: ts.UnionTypeNode): string {
let bad = false
let tl: ts.TypeLiteralNode[] = []
node.forEachChild((n: ts.Node) => {
if (ts.isTypeLiteralNode(n)) {
tl.push(n)
} else
bad = true
})
if (bad) return // none of these are useful (so far)
let x = computeType(tl[0])
x.fields[0].json = x.fields[0].json.replace(/"`/, ',omitempty"`')
let out: string[] = [];
for (const f of x.fields) {
out.push(strField(f))
}
out.push('}\n')
let ans = 'struct {\n'.concat(...out);
return ans
}
function computeType(node: ts.Node): { goType: string, gostuff?: string, optional?: boolean, fields?: Field[] } {
switch (node.kind) {
case ts.SyntaxKind.AnyKeyword:
case ts.SyntaxKind.ObjectKeyword:
return { goType: 'interface{}' };
case ts.SyntaxKind.BooleanKeyword:
return { goType: 'bool' };
case ts.SyntaxKind.NumberKeyword:
return { goType: 'float64' };
case ts.SyntaxKind.StringKeyword:
return { goType: 'string' };
case ts.SyntaxKind.NullKeyword:
case ts.SyntaxKind.UndefinedKeyword:
return { goType: 'nil' };
}
if (ts.isArrayTypeNode(node)) {
let { goType, gostuff, optional } = computeType(node.elementType)
return ({ goType: '[]' + goType, gostuff: gostuff, optional: optional })
} else if (ts.isTypeReferenceNode(node)) {
// typeArguments?: NodeArray<TypeNode>;typeName: EntityName;
// typeArguments won't show up in the generated Go
// EntityName: Identifier|QualifiedName
let tn: ts.EntityName = node.typeName;
if (ts.isQualifiedName(tn)) {
throw new Error(`qualified name at ${loc(node)}`);
} else if (ts.isIdentifier(tn)) {
return { goType: tn.text };
} else {
throw new Error(`expected identifier got ${
ts.SyntaxKind[node.typeName.kind]} at ${loc(tn)}`)
}
} else if (ts.isLiteralTypeNode(node)) {
// string|float64 (are there other possibilities?)
const txt = getText(node);
let typ = 'float64'
if (txt.charAt(0) == '\'') {
typ = 'string'
}
return { goType: typ, gostuff: getText(node) };
} else if (ts.isTypeLiteralNode(node)) {
let x: Field[] = [];
let indexCnt = 0
node.forEachChild((n: ts.Node) => {
if (ts.isPropertySignature(n)) {
x.push(genProp(n, undefined))
return
} else if (ts.isIndexSignatureDeclaration(n)) {
indexCnt++
x.push(fromIndexSignature(n))
return
}
throw new Error(
`${loc(n)} gotype ${ts.SyntaxKind[n.kind]}, not expected`)
});
if (indexCnt > 0) {
if (indexCnt != 1 || x.length != 1)
throw new Error(`undexpected Index ${loc(x[0].me)}`)
// instead of {map...} just the map
return ({ goType: x[0].goType, gostuff: x[0].gostuff })
}
return ({ goType: 'embedded!', fields: x })
} else if (ts.isUnionTypeNode(node)) {
let x = new Array<{ goType: string, gostuff?: string, optiona?: boolean }>()
node.forEachChild((n: ts.Node) => { x.push(computeType(n)) })
if (x.length == 2 && x[1].goType == 'nil') {
return x[0] // make it optional somehow? TODO
}
if (x[0].goType == 'bool') { // take it
return ({ goType: 'bool', gostuff: getText(node) })
}
// these are special cases from looking at the source
let gostuff = getText(node);
if (x[0].goType == `"off"` || x[0].goType == 'string') {
return ({ goType: 'string', gostuff: gostuff })
}
if (x[0].goType == 'TextDocumentSyncOptions') {
return ({ goType: 'interface{}', gostuff: gostuff })
}
if (x[0].goType == 'float64' && x[1].goType == 'string') {
return {
goType: 'interface{}', gostuff: gostuff
}
}
if (x[0].goType == 'MarkupContent' && x[1].goType == 'MarkedString') {
return {
goType: 'MarkupContent', gostuff: gostuff
}
}
// Fail loudly
console.log(`UnionType ${loc(node)}`)
for (const v of x) {
console.log(`${v.goType}`)
}
throw new Error('in UnionType, weird')
} else if (ts.isParenthesizedTypeNode(node)) {
// check that this is (TextDocumentEdit | CreateFile | RenameFile |
// DeleteFile)
return {
goType: 'TextDocumentEdit', gostuff: getText(node)
}
} else if (ts.isTupleTypeNode(node)) {
// string | [number, number]
return {
goType: 'string', gostuff: getText(node)
}
}
throw new Error(`unknown ${ts.SyntaxKind[node.kind]} at ${loc(node)}`)
}
function fromIndexSignature(node: ts.IndexSignatureDeclaration): Field {
let parm: ts.ParameterDeclaration
let at: ts.Node
node.forEachChild((n: ts.Node) => {
if (ts.isParameter(n)) {
parm = n
} else if (
ts.isArrayTypeNode(n) || n.kind == ts.SyntaxKind.AnyKeyword ||
ts.isUnionTypeNode(n)) {
at = n
} else
throw new Error(`fromIndexSig ${ts.SyntaxKind[n.kind]} ${loc(n)}`)
})
let goType = computeType(at).goType
let id: ts.Identifier
parm.forEachChild((n: ts.Node) => {
if (ts.isIdentifier(n)) {
id = n
} else if (n.kind != ts.SyntaxKind.StringKeyword) {
throw new Error(
`fromIndexSig expected string, ${ts.SyntaxKind[n.kind]} ${loc(n)}`)
}
})
goType = `map[string]${goType}`
return {
me: node, goName: toGoName(id.text), id: null, goType: goType,
optional: false, json: `\`json:"${id.text}"\``,
gostuff: `${getText(node)}`
}
}
function toGoName(s: string): string {
let ans = s
if (s.charAt(0) == '_') {
ans = 'Inner' + s.substring(1)
}
else { ans = s.substring(0, 1).toUpperCase() + s.substring(1) };
ans = ans.replace(/Uri$/, 'URI')
ans = ans.replace(/Id$/, 'ID')
return ans
}
// find the text of a node
function getText(node: ts.Node): string {
let sf = node.getSourceFile();
let start = node.getStart(sf)
let end = node.getEnd()
return sf.text.substring(start, end)
}
// return a string of the kinds of the immediate descendants
function kinds(n: ts.Node): string {
let res = 'Seen ' + ts.SyntaxKind[n.kind];
function f(n: ts.Node): void { res += ' ' + ts.SyntaxKind[n.kind] };
ts.forEachChild(n, f)
return res
}
function describe(node: ts.Node) {
if (node === undefined) {
return
}
let indent = '';
function f(n: ts.Node) {
seenAdd(kinds(n))
if (ts.isIdentifier(n)) {
pra(`${indent} ${loc(n)} ${ts.SyntaxKind[n.kind]} ${n.text}\n`)
}
else if (ts.isPropertySignature(n) || ts.isEnumMember(n)) {
pra(`${indent} ${loc(n)} ${ts.SyntaxKind[n.kind]}\n`)
}
else if (ts.isTypeLiteralNode(n)) {
let m = n.members
pra(`${indent} ${loc(n)} ${ts.SyntaxKind[n.kind]} ${m.length}\n`)
}
else { pra(`${indent} ${loc(n)} ${ts.SyntaxKind[n.kind]}\n`) };
indent += ' '
ts.forEachChild(n, f)
indent = indent.slice(0, indent.length - 2)
}
f(node)
}
function loc(node: ts.Node): string {
const sf = node.getSourceFile()
const start = node.getStart()
const x = sf.getLineAndCharacterOfPosition(start)
const full = node.getFullStart()
const y = sf.getLineAndCharacterOfPosition(full)
let fn = sf.fileName
const n = fn.search(/-node./)
fn = fn.substring(n + 6)
return `${fn} ${x.line + 1}:${x.character + 1} (${y.line + 1}:${
y.character + 1})`
}
}
function getComments(node: ts.Node): string {
const sf = node.getSourceFile();
const start = node.getStart(sf, false)
const starta = node.getStart(sf, true)
const x = sf.text.substring(starta, start)
return x
}
function emitTypes() {
for (const t of Types) {
if (t.goName == 'CodeActionKind') continue; // consts better choice
let stuff = (t.stuff == undefined) ? '' : t.stuff;
prgo(`// ${t.goName} is a type\n`)
prgo(`${getComments(t.me)}`)
prgo(`type ${t.goName} ${t.goType}${stuff}\n`)
}
}
function emitStructs() {
let seenName = new Map<string, boolean>()
for (const str of Structs) {
if (str.name == 'InitializeError') {
// only want the consts
continue
}
if (seenName[str.name]) {
continue
}
seenName[str.name] = true
prgo(genComments(str.name, getComments(str.me)))
/* prgo(`// ${str.name} is:\n`)
prgo(getComments(str.me))*/
prgo(`type ${str.name} struct {\n`)
for (const s of str.embeds) {
prgo(`\t${s}\n`)
}
if (str.fields != undefined) {
for (const f of str.fields) {
prgo(strField(f))
}
}
prgo(`}\n`)
}
}
function genComments(name: string, maybe: string): string {
if (maybe == '') return `\n\t// ${name} is\n`;
if (maybe.indexOf('/**') == 0) {
return maybe.replace('/**', `\n/*${name} defined:`)
}
throw new Error(`weird comment ${maybe.indexOf('/**')}`)
}
// Turn a Field into an output string
function strField(f: Field): string {
let ans: string[] = [];
let opt = f.optional ? '*' : ''
switch (f.goType.charAt(0)) {
case 's': // string
case 'b': // bool
case 'f': // float64
case 'i': // interface{}
case '[': // []foo
opt = ''
}
let stuff = (f.gostuff == undefined) ? '' : ` // ${f.gostuff}`
ans.push(genComments(f.goName, getComments(f.me)))
if (f.substruct == undefined) {
ans.push(`\t${f.goName} ${opt}${f.goType} ${f.json}${stuff}\n`)
}
else {
ans.push(`\t${f.goName} ${opt}struct {\n`)
for (const x of f.substruct) {
ans.push(strField(x))
}
ans.push(`\t} ${f.json}${stuff}\n`)
}
return (''.concat(...ans))
}
function emitConsts() {
// Generate modifying prefixes and suffixes to ensure consts are
// unique. (Go consts are package-level, but Typescript's are not.)
// Use suffixes to minimize changes to gopls.
let pref = new Map<string, string>(
[['DiagnosticSeverity', 'Severity']]) // typeName->prefix
let suff = new Map<string, string>([
['CompletionItemKind', 'Completion'], ['InsertTextFormat', 'TextFormat']
])
for (const c of Consts) {
if (seenConstTypes[c.typeName]) {
continue
}
seenConstTypes[c.typeName] = true
if (pref.get(c.typeName) == undefined) {
pref.set(c.typeName, '') // initialize to empty value
}
if (suff.get(c.typeName) == undefined) {
suff.set(c.typeName, '')
}
prgo(`// ${c.typeName} defines constants\n`)
prgo(`type ${c.typeName} ${c.goType}\n`)
}
prgo('const (\n')
let seenConsts = new Map<string, boolean>() // to avoid duplicates
for (const c of Consts) {
const x = `${pref.get(c.typeName)}${c.name}${suff.get(c.typeName)}`
if (seenConsts.get(x)) {
continue
}
seenConsts.set(x, true)
prgo(genComments(x, getComments(c.me)))
prgo(`\t${x} ${c.typeName} = ${c.value}\n`)
}
prgo(')\n')
}
function emitHeader(files: string[]) {
let lastMod = 0
let lastDate: Date
for (const f of files) {
const st = fs.statSync(f)
if (st.mtimeMs > lastMod) {
lastMod = st.mtimeMs
lastDate = st.mtime
}
}
prgo(`// Package protocol contains data types for LSP jsonrpcs\n`)
prgo(`// generated automatically from vscode-languageserver-node
// version of ${lastDate}\n`)
prgo('package protocol\n\n')
};
// ad hoc argument parsing: [-d dir] [-o outputfile], and order matters
function main() {
let args = process.argv.slice(2) // effective command line
if (args.length > 0) {
let j = 0;
if (args[j] == '-d') {
dir = args[j + 1]
j += 2
}
if (args[j] == '-o') {
outFname = args[j + 1]
j += 2
}
if (j != args.length) throw new Error(`incomprehensible args ${args}`)
}
let files: string[] = [];
for (let i = 0; i < fnames.length; i++) {
files.push(`${dir}${fnames[i]}`)
}
createOutputFiles()
generate(
files, { target: ts.ScriptTarget.ES5, module: ts.ModuleKind.CommonJS });
emitHeader(files)
emitStructs()
emitConsts()
emitTypes()
}
main() | the_stack |
import { v4 as uuid } from "uuid";
import * as he from "html-entities";
import { IBasicProtocolMessage } from "../MessageFormatter";
import { XMPPFeatures, XMPPStatusCode } from "./XMPPConstants";
function encode(text) {
return he.encode(text, { level: "xml", mode: "nonAscii"});
}
export interface IStza {
type: string;
xml: string;
}
export enum PresenceRole {
None = "none",
Visitor = "visitor",
Participant = "participant",
Moderator = "moderator",
}
export enum PresenceAffiliation {
None = "none",
Outcast = "outcast",
Member = "member",
Admin = "admin",
Owner = "owner",
}
export abstract class StzaBase implements IStza {
private hFrom: string = "";
private hTo: string = "";
private hId?: string = "";
constructor(from: string, to: string, id?: string) {
this.from = from;
this.to = to;
this.id = id;
}
get type(): string { throw Error('type not defined') }
get xml(): string { throw Error('xml not defined') }
get from() { return this.hFrom; }
set from(val: string) {
this.hFrom = encode(val);
}
get to() { return this.hTo; }
set to(val: string) {
this.hTo = encode(val);
}
get id(): string|undefined { return this.hId || undefined; }
set id(val: string|undefined) {
if (!val) { return; }
this.hId = encode(val);
}
}
export class StzaPresence extends StzaBase {
protected includeXContent: boolean = true;
constructor(
from: string,
to: string,
id?: string,
public presenceType?: string,
) {
super(from, to, id);
}
get xContent(): string { return ""; }
get xProtocol(): string { return "muc"; }
get presenceContent(): string { return ""; }
get type(): string {
return "presence";
}
get xml(): string {
const type = this.presenceType ? ` type='${this.presenceType}'` : "";
const id = this.id ? ` id="${this.id}"` : "";
let content = "";
if (this.includeXContent) {
content = this.xContent ? `<x xmlns='http://jabber.org/protocol/${this.xProtocol}'>${this.xContent}</x>` :
"<x xmlns='http://jabber.org/protocol/muc'/>";
}
return `<presence from="${this.from}" to="${this.to}"${id}${type}>${content}${this.presenceContent}</presence>`;
}
}
export class StzaPresenceItem extends StzaPresence {
public statusCodes: Set<XMPPStatusCode>;
public actor?: string;
public reason?: string;
constructor(
from: string,
to: string,
id?: string,
public affiliation: PresenceAffiliation = PresenceAffiliation.Member,
public role: PresenceRole = PresenceRole.Participant,
self: boolean = false,
public jid: string = "",
itemType: string = "",
) {
super(from, to, id, itemType);
this.statusCodes = new Set();
this.self = self;
}
set self(isSelf: boolean) {
this.statusCodes[isSelf ? "add" : "delete"](XMPPStatusCode.SelfPresence);
}
get xProtocol(): string { return "muc#user"; }
public get xContent() {
const jid = this.jid ? ` jid='${this.jid}'` : "";
let xml = [...this.statusCodes].map((s) => `<status code='${s}'/>`).join("");
xml += `<item affiliation='${this.affiliation}'${jid} role='${this.role}'`;
if (!this.actor && !this.reason) {
return xml + "/>";
}
xml += ">";
if (this.actor) {
xml += `<actor nick='${encode(this.actor)}'/>`
}
if (this.reason) {
xml += `<reason>${encode(this.reason)}</reason>`
}
xml += "</item>";
return xml;
}
}
export class StzaPresenceError extends StzaPresence {
constructor(
from: string,
to: string,
id: string,
public by: string,
public errType: string,
public innerError: string,
public text?: string,
) {
super(from, to, id, "error");
}
public get presenceContent() {
return `<error type='${this.errType}' by='${this.by}'><${this.innerError}`
+ " xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>"
+ (this.text ? `<text xmlns="urn:ietf:params:xml:ns:xmpp-stanzas">${encode(this.text)}</text>` : "")
+ "</error>";
}
}
export class StzaPresenceJoin extends StzaPresence {
constructor(
from: string,
to: string,
id?: string,
public presenceType?: string,
) {
super(from, to, id);
}
public get xContent() {
// No history.
// TODO: I'm sure we want to be able to configure this.
return `<history maxchars='0'/>`;
}
}
export class StzaPresencePart extends StzaPresence {
constructor(
from: string,
to: string,
) {
super(from, to, undefined, "unavailable");
this.includeXContent = false;
this.id = undefined;
}
}
export class StzaPresenceKick extends StzaPresenceItem {
constructor(
from: string,
to: string,
reason?: string,
actorNick?: string,
self: boolean = false,
) {
super(from, to, undefined, PresenceAffiliation.None, PresenceRole.None, self, undefined, "unavailable");
this.actor = actorNick;
this.reason = reason;
this.statusCodes.add(XMPPStatusCode.SelfKicked);
}
}
export class StzaMessage extends StzaBase {
public html: string = "";
public body: string = "";
public markable: boolean = true;
public attachments: string[] = [];
public replacesId?: string;
constructor(
from: string,
to: string,
idOrMsg?: string|IBasicProtocolMessage,
public messageType?: string,
) {
super(from, to, undefined);
if (idOrMsg && idOrMsg.hasOwnProperty("body")) {
idOrMsg = idOrMsg as IBasicProtocolMessage;
this.body = idOrMsg.body;
if (idOrMsg.formatted) {
const html = idOrMsg.formatted.find((f) => f.type === "html");
this.html = html ? html.body : "";
}
if (idOrMsg.opts) {
this.attachments = (idOrMsg.opts.attachments || []).map((a) => a.uri);
}
this.id = idOrMsg.id;
if (idOrMsg.original_message) {
this.replacesId = idOrMsg.original_message;
}
} else if (idOrMsg) {
this.id = idOrMsg as string;
}
this.id = this.id || uuid();
}
get type(): string {
return "message";
}
get xml(): string {
const type = this.messageType ? `type='${this.messageType}'` : "";
const attachments = this.attachments.map((a) =>
`<x xmlns='jabber:x:oob'><url>${encode(a)}</url></x>`,
);
if (this.attachments.length === 1) {
// For reasons unclear to me, XMPP reccomend we make the body == attachment url to make them show up inline.
this.body = this.attachments[0];
}
// XEP-0333
const markable = this.markable ? "<markable xmlns='urn:xmpp:chat-markers:0'/>" : "";
// XEP-0308
const replaces = this.replacesId ? `<replace id='${this.replacesId}' xmlns='urn:xmpp:message-correct:0'/>` : "";
return `<message from="${this.from}" to="${this.to}" id="${this.id}" ${type}>`
+ `${this.html}<body>${encode(this.body)}</body>${attachments}${markable}${replaces}</message>`;
}
}
export class StzaMessageSubject extends StzaBase {
constructor(
from: string,
to: string,
id?: string,
public subject: string = "",
) {
super(from, to, id);
}
get content(): string { return ""; }
get type(): string {
return "message";
}
get xml(): string {
return `<message from="${this.from}" to="${this.to}" id="${this.id}" type='groupchat'>`
+ `<subject>${encode(this.subject)}</subject></message>`;
}
}
export class StzaIqPing extends StzaBase {
protected extraContent: string = "";
constructor(
from: string,
to: string,
id: string,
public responseType: string,
) {
super(from, to, id || uuid());
}
get type(): string {
return "iq";
}
get xml(): string {
return `<iq from='${this.from}' to='${this.to}' id='${this.id}' type='${this.responseType}'>`
+ `<ping xmlns='urn:xmpp:ping'/>${this.extraContent}</iq>`;
}
}
export class StzaIqPingError extends StzaIqPing {
constructor(
from: string,
to: string,
id: string,
private eType: "service-unavailable"|"not-acceptable",
private by?: string,
) {
super(from, to, id, "error");
this.extraContent = `<error type='cancel'${this.by ? ` by='${this.by}'` : ""}>`
+ `<${this.eType} xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/></error>`;
}
}
export abstract class StzaIqDisco extends StzaBase {
constructor(
from: string,
to: string,
id: string,
protected iqType = "result",
protected queryType = "",
) {
super(from, to, id);
}
get type(): string {
return "iq";
}
get queryContent(): string { return ""; }
get xml(): string {
return `<iq from='${this.from}' to='${this.to}' id='${this.id}' type='${this.iqType}'>`
+ `<query xmlns='${this.queryType}'>${this.queryContent}</query></iq>`;
}
}
export class StzaIqDiscoItems extends StzaIqDisco {
private items: {jid: string, name: string}[];
constructor(
from: string,
to: string,
id: string,
queryType: string,
) {
super(from, to, id, "result", queryType);
this.items = [];
}
get queryContent(): string {
const items = this.items.map((item) =>
`<item jid='${encode(item.jid)}' name='${encode(item.name)}'/>`,
).join("");
return items;
}
public addItem(jid: string, name: string) {
this.items.push({jid, name});
}
}
export class StzaIqDiscoInfo extends StzaIqDisco {
public identity: Set<{category: string, type: string, name: string}>;
public feature: Set<XMPPFeatures>;
constructor(
from: string,
to: string,
id: string,
iqType = "result") {
super(from, to, id, iqType, "http://jabber.org/protocol/disco#info");
this.identity = new Set();
this.feature = new Set();
}
get queryContent(): string {
let identity = "";
let feature = "";
this.identity.forEach((ident) => {
identity += `<identity category='${ident.category}' type='${ident.type}' name='${ident.name}'/>`;
});
this.feature.forEach((feat) => {
feature += `<feature var='${feat}'/>`;
});
return identity + feature;
}
}
export class StzaIqSearchFields extends StzaBase {
constructor(
from: string,
to: string,
id: string,
public instructions: string,
public fields: {[key: string]: string},
) {
super(from, to, id);
}
get type(): string {
return "iq";
}
get queryContent(): string { return ""; }
get xml(): string {
const fields = Object.keys(this.fields).map((field) => `<${field}>${this.fields[field]}</${field}>`).join("");
return `<iq from='${this.from}' to='${this.to}' id='${this.id}' type='result' xml:lang='en'>`
+ `<query xmlns='jabber:iq:search'><instructions>${encode(this.instructions)}</instructions>`
+ `${fields}</query></iq>`;
}
}
export class SztaIqError extends StzaBase {
constructor(
from: string,
to: string,
id: string,
private errorType: string,
private errorCode: number|null,
private innerError: string,
private by?: string,
private text?: string,
) {
super(from, to, id);
}
get type(): string {
return "iq";
}
get xml(): string {
let errorParams = "";
if (this.errorCode) {
errorParams += ` code='${this.errorCode}'`;
}
if (this.by) {
errorParams += ` by='${this.by}'`;
}
return `<iq from='${this.from}' to='${this.to}' id='${this.id}' type='error' xml:lang='en'>`
+ `<error type='${this.errorType}'${errorParams}><${this.innerError} ` +
"xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>" +
(this.text ? `<text xmlns="urn:ietf:params:xml:ns:xmpp-stanzas">${encode(this.text)}</text>` : "") +
"</error></iq>";
}
}
export class StzaIqVcardRequest extends StzaBase {
constructor(from: string, to: string, id) {
super(from, to, id);
}
get type(): string {
return "iq";
}
get xml(): string {
return `<iq from='${this.from}' to='${this.to}' id='${this.id}' type='get'>` +
"<vCard xmlns='vcard-temp'/>" +
"</iq>";
}
} | the_stack |
import * as pem from 'pem';
import * as fs from 'fs';
const tests = {
'Create default sized dhparam key': (test: any) => {
pem.createDhparam((error: any, data: any) => {
const dhparam = (data && data.dhparam || '').toString();
test.ifError(error);
test.ok(dhparam);
test.ok(dhparam.match(/^\n*\-\-\-\-\-BEGIN DH PARAMETERS\-\-\-\-\-\n/));
test.ok(dhparam.match(/\n\-\-\-\-\-END DH PARAMETERS\-\-\-\-\-\n*$/));
test.ok(dhparam.trim().length > 150 && dhparam.trim().length < 160);
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
},
'Create 2048bit dhparam key': (test: any) => {
pem.createDhparam(2048, (error: any, data: any) => {
const dhparam = (data && data.dhparam || '').toString();
test.ifError(error);
test.ok(dhparam);
test.ok(dhparam.match(/^\n*\-\-\-\-\-BEGIN DH PARAMETERS\-\-\-\-\-\n/));
test.ok(dhparam.match(/\n\-\-\-\-\-END DH PARAMETERS\-\-\-\-\-\n*$/));
test.ok(dhparam.trim().length > 420 && dhparam.trim().length < 430);
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
},
'Create default sized Private key': (test: any) => {
pem.createPrivateKey((error: any, data: any) => {
const key = (data && data.key || '').toString();
test.ifError(error);
test.ok(key);
test.ok(key.match(/^\n*\-\-\-\-\-BEGIN RSA PRIVATE KEY\-\-\-\-\-\n/));
test.ok(key.match(/\n\-\-\-\-\-END RSA PRIVATE KEY\-\-\-\-\-\n*$/));
test.ok(key.trim().length > 850 && key.trim().length < 1900);
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
},
'Create 2048bit Private key': (test: any) => {
pem.createPrivateKey(2048, (error: any, data: any) => {
const key = (data && data.key || '').toString();
test.ifError(error);
test.ok(key);
test.ok(key.match(/^\n*\-\-\-\-\-BEGIN RSA PRIVATE KEY\-\-\-\-\-\n/));
test.ok(key.match(/\n\-\-\-\-\-END RSA PRIVATE KEY\-\-\-\-\-\n*$/));
test.ok(key.trim().length > 1650 && key.trim().length < 1700);
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
},
'Create 2048bit Private key with Password': (test: any) => {
pem.createPrivateKey(2048, {cipher: 'des', password: 'TestMe'}, (error: any, data: any) => {
const key = (data && data.key || '').toString();
test.ifError(error);
test.ok(key);
test.ok(key.match(/ENCRYPTED\n/));
test.ok(key.match(/^\n*\-\-\-\-\-BEGIN RSA PRIVATE KEY\-\-\-\-\-\n/));
test.ok(key.match(/\n\-\-\-\-\-END RSA PRIVATE KEY\-\-\-\-\-\n*$/));
test.ok(key.trim().length > 1700 && key.trim().length < 1780);
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
},
'Create default CSR': (test: any) => {
pem.createCSR((error: any, data: any) => {
const csr = (data && data.csr || '').toString();
test.ifError(error);
test.ok(csr);
test.ok(csr.match(/^\n*\-\-\-\-\-BEGIN CERTIFICATE REQUEST\-\-\-\-\-\n/));
test.ok(csr.match(/\n\-\-\-\-\-END CERTIFICATE REQUEST\-\-\-\-\-\n*$/));
test.ok(data && data.clientKey);
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
},
'Create CSR using config file': (test: any) => {
const certInfo = {
issuer : {},
country: 'EE',
state: 'Harjumaa',
locality: 'Tallinn',
organization: 'Node.ee',
organizationUnit: 'test',
commonName: 'www.node.ee',
emailAddress: 'andris@node.ee'
};
pem.createCSR({ csrConfigFile: './test/fixtures/test.cnf' }, (error: any, data: any) => {
const csr = (data && data.csr || '').toString();
test.ifError(error);
test.ok(csr);
test.ok(csr.match(/^\n*\-\-\-\-\-BEGIN CERTIFICATE REQUEST\-\-\-\-\-\n/));
test.ok(csr.match(/\n\-\-\-\-\-END CERTIFICATE REQUEST\-\-\-\-\-\n*$/));
test.ok(data && data.clientKey);
// test.ok(fs.readdirSync('./tmp').length === 0);
pem.readCertificateInfo(csr, (error: any, data: any) => {
test.ifError(error);
test.deepEqual(data, certInfo);
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
});
},
'Create CSR with own key': (test: any) => {
pem.createPrivateKey((error: any, data: any) => {
const key = (data && data.key || '').toString();
pem.createCSR({
clientKey: key
}, (error: any, data: any) => {
const csr = (data && data.csr || '').toString();
test.ifError(error);
test.ok(csr);
test.ok(csr.match(/^\n*\-\-\-\-\-BEGIN CERTIFICATE REQUEST\-\-\-\-\-\n/));
test.ok(csr.match(/\n\-\-\-\-\-END CERTIFICATE REQUEST\-\-\-\-\-\n*$/));
test.equal(data && data.clientKey, key);
test.ok(data && data.clientKey);
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
});
},
'Create CSR with own encrypted key': (test: any) => {
const password = 'my:secure! "password\'s\nawesome';
pem.createPrivateKey(2048, { cipher: 'des3', password }, (error: any, data: any) => {
const key = (data && data.key || '').toString();
pem.createCSR({
clientKey: key,
clientKeyPassword: password
}, (error: any, data: any) => {
const csr = (data && data.csr || '').toString();
test.ifError(error);
test.ok(csr);
test.ok(csr.match(/^\n*\-\-\-\-\-BEGIN CERTIFICATE REQUEST\-\-\-\-\-\n/));
test.ok(csr.match(/\n\-\-\-\-\-END CERTIFICATE REQUEST\-\-\-\-\-\n*$/));
test.equal(data && data.clientKey, key);
test.ok(data && data.clientKey);
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
});
},
'Create default certificate': (test: any) => {
pem.createCertificate((error: any, data: any) => {
const certificate = (data && data.certificate || '').toString();
test.ifError(error);
test.ok(certificate);
test.ok(certificate.match(/^\n*\-\-\-\-\-BEGIN CERTIFICATE\-\-\-\-\-\n/));
test.ok(certificate.match(/\n\-\-\-\-\-END CERTIFICATE\-\-\-\-\-\n*$/));
test.ok((data && data.clientKey) !== (data && data.serviceKey));
test.ok(data && data.clientKey);
test.ok(data && data.serviceKey);
test.ok(data && data.csr);
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
},
'Create self signed certificate': (test: any) => {
pem.createCertificate({
selfSigned: true
}, (error: any, data: any) => {
const certificate = (data && data.certificate || '').toString();
test.ifError(error);
test.ok(certificate);
test.ok(certificate.match(/^\n*\-\-\-\-\-BEGIN CERTIFICATE\-\-\-\-\-\n/));
test.ok(certificate.match(/\n\-\-\-\-\-END CERTIFICATE\-\-\-\-\-\n*$/));
test.ok((data && data.clientKey) === (data && data.serviceKey));
test.ok(data && data.clientKey);
test.ok(data && data.serviceKey);
test.ok(data && data.csr);
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
},
'Read default cert data from CSR': (test: any) => {
pem.createCSR((error: any, data: any) => {
const csr = (data && data.csr || '').toString();
test.ifError(error);
// test.ok(fs.readdirSync('./tmp').length === 0);
pem.readCertificateInfo(csr, (error: any, data: any) => {
test.ifError(error);
test.deepEqual(data, {
issuer : {},
country: '',
state: '',
locality: '',
organization: '',
organizationUnit: '',
commonName: 'localhost',
emailAddress: ''
});
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
});
},
'Read edited cert data from CSR': (test: any) => {
const certInfo = {
issuer : {},
country: 'EE',
state: 'Harjumaa',
locality: 'Tallinn',
organization: 'Node.ee',
organizationUnit: 'test',
commonName: 'www.node.ee',
emailAddress: 'andris@node.ee'
};
pem.createCSR(Object.create(certInfo), (error: any, data: any) => {
const csr = (data && data.csr || '').toString();
test.ifError(error);
// test.ok(fs.readdirSync('./tmp').length === 0);
pem.readCertificateInfo(csr, (error: any, data: any) => {
test.ifError(error);
test.deepEqual(data, certInfo);
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
});
},
'Read default cert data from certificate': (test: any) => {
pem.createCertificate((error: any, data: any) => {
const certificate = (data && data.certificate || '').toString();
test.ifError(error);
// test.ok(fs.readdirSync('./tmp').length === 0);
pem.readCertificateInfo(certificate, (error: any, data: any) => {
test.ifError(error);
if (data.validity) {
delete data.validity;
}
if (data.serial) {
delete data.serial;
}
test.deepEqual(data, {
issuer : {
country: '',
state: '',
locality: '',
organization: '',
organizationUnit: '',
commonName: 'localhost'
},
country: '',
state: '',
locality: '',
organization: '',
organizationUnit: '',
commonName: 'localhost',
emailAddress: ''
});
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
});
},
'Read edited cert data from certificate': (test: any) => {
const certInfo = {
issuer : {
country: 'EE',
state: 'Harjumaa',
locality: 'Tallinn',
organization: 'Node.ee',
organizationUnit: 'test',
commonName: 'www.node.ee'
},
country: 'EE',
state: 'Harjumaa',
locality: 'Tallinn',
organization: 'Node.ee',
organizationUnit: 'test',
commonName: 'www.node.ee',
emailAddress: 'andris@node.ee'
};
pem.createCertificate(Object.create(certInfo), (error: any, data: any) => {
const certificate = (data && data.certificate || '').toString();
test.ifError(error);
// test.ok(fs.readdirSync('./tmp').length === 0);
pem.readCertificateInfo(certificate, (error: any, data: any) => {
test.ifError(error);
if (data.validity) {
delete data.validity;
}
if (data.serial) {
delete data.serial;
}
test.deepEqual(data, certInfo);
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
});
},
'Get public key from private key': (test: any) => {
pem.createPrivateKey((error: any, data: any) => {
const key = (data && data.key || '').toString();
test.ifError(error);
test.ok(key);
// test.ok(fs.readdirSync('./tmp').length === 0);
pem.getPublicKey(key, (error: any, data: any) => {
const pubkey = (data && data.publicKey || '').toString();
test.ifError(error);
test.ok(pubkey);
test.ok(pubkey.match(/^\n*\-\-\-\-\-BEGIN PUBLIC KEY\-\-\-\-\-\n/));
test.ok(pubkey.match(/\n\-\-\-\-\-END PUBLIC KEY\-\-\-\-\-\n*$/));
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
});
},
'Get public key from CSR': (test: any) => {
pem.createCSR((error: any, data: any) => {
const key = (data && data.clientKey || '').toString();
test.ifError(error);
test.ok(key);
// test.ok(fs.readdirSync('./tmp').length === 0);
pem.getPublicKey(key, (error: any, data: any) => {
const pubkey = (data && data.publicKey || '').toString();
test.ifError(error);
test.ok(pubkey);
test.ok(pubkey.match(/^\n*\-\-\-\-\-BEGIN PUBLIC KEY\-\-\-\-\-\n/));
test.ok(pubkey.match(/\n\-\-\-\-\-END PUBLIC KEY\-\-\-\-\-\n*$/));
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
});
},
'Get public key from certificate': (test: any) => {
pem.createCertificate((error: any, data: any) => {
const key = (data && data.clientKey || '').toString();
test.ifError(error);
test.ok(key);
// test.ok(fs.readdirSync('./tmp').length === 0);
pem.getPublicKey(key, (error: any, data: any) => {
const pubkey = (data && data.publicKey || '').toString();
test.ifError(error);
test.ok(pubkey);
test.ok(pubkey.match(/^\n*\-\-\-\-\-BEGIN PUBLIC KEY\-\-\-\-\-\n/));
test.ok(pubkey.match(/\n\-\-\-\-\-END PUBLIC KEY\-\-\-\-\-\n*$/));
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
});
},
'Get fingerprint from certificate': (test: any) => {
pem.createCertificate((error: any, data: any) => {
const certificate = (data && data.certificate || '').toString();
test.ifError(error);
test.ok(certificate);
// test.ok(fs.readdirSync('./tmp').length === 0);
pem.getFingerprint(certificate, (error: any, data: any) => {
const fingerprint = (data && data.fingerprint || '').toString();
test.ifError(error);
test.ok(fingerprint);
test.ok(fingerprint.match(/^[0-9A-F]{2}(:[0-9A-F]{2}){19}$/));
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
});
},
'Get modulus from certificate': (test: any) => {
pem.createCertificate((error: any, data: any) => {
const certificate = (data && data.certificate || '').toString();
test.ifError(error);
test.ok(certificate);
// test.ok(fs.readdirSync('./tmp').length === 0);
pem.getModulus(certificate, (error: any, data: any) => {
const certmodulus = (data && data.modulus || '').toString();
test.ifError(error);
test.ok(certmodulus);
test.ok(certmodulus.match(/^[0-9A-F]*$/));
// test.ok(fs.readdirSync('./tmp').length === 0);
pem.getModulus(certificate, (error: any, data: any) => {
const keymodulus = (data && data.modulus || '').toString();
test.ifError(error);
test.ok(keymodulus);
test.ok(keymodulus.match(/^[0-9A-F]*$/));
test.ok(keymodulus === certmodulus);
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
});
});
},
'Get modulus from a protected key': (test: any) => {
const certificate = ''; // fs.readFileSync('./test/fixtures/test.crt').toString();
const key = ''; // fs.readFileSync('./test/fixtures/test.key').toString();
pem.getModulus(certificate, (error: any, data: any) => {
const certmodulus = (data && data.modulus || '').toString();
test.ifError(error);
test.ok(certmodulus);
test.ok(certmodulus.match(/^[0-9A-F]*$/));
// test.ok(fs.readdirSync('./tmp').length === 0);
pem.getModulus(key, 'password', (error: any, data: any) => {
const keymodulus = (data && data.modulus || '').toString();
test.ifError(error);
test.ok(keymodulus);
test.ok(keymodulus.match(/^[0-9A-F]*$/));
test.ok(keymodulus === certmodulus);
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
});
},
'Get DH param info': (test: any) => {
const dh = ''; // fs.readFileSync('./test/fixtures/test.dh').toString();
pem.getDhparamInfo(dh, (error: any, data: any) => {
const size = data && data.size || 0;
const prime = (data && data.prime || '').toString();
test.ifError(error);
test.equal(size, 1024);
test.ok(prime);
// test.ok(fs.readdirSync('./tmp').length === 0);
test.equal(typeof size, 'number');
test.ok(/([0-9a-f][0-9a-f]:)+[0-9a-f][0-9a-f]$/g.test(prime));
test.done();
});
},
'Create and verify wildcard certificate': (test: any) => {
const certInfo = {
commonName: '*.node.ee'
};
pem.createCertificate(Object.create(certInfo), (error: any, data: any) => {
const certificate = (data && data.certificate || '').toString();
test.ifError(error);
// test.ok(fs.readdirSync('./tmp').length === 0);
pem.readCertificateInfo(certificate, (error: any, data: any) => {
test.ifError(error);
test.equal(data.commonName, certInfo.commonName);
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
});
},
'Return an error if openssl was not found': (test: any) => {
pem.config({
pathOpenSSL: 'zzzzzzzzzzz'
});
pem.createPrivateKey((error: any) => {
test.ok(error);
pem.config({
pathOpenSSL: 'openssl'
});
pem.createPrivateKey((error: any) => {
test.ifError(error);
test.done();
});
});
},
'Create PKCS12 without key password': (test: any) => {
pem.createPrivateKey((error: any, data: any) => {
const key = (data && data.key || '').toString();
pem.createCertificate({
clientKey: key,
selfSigned: true
}, (error: any, csr: any) => {
pem.createPkcs12(csr.clientKey, csr.certificate, 'mypassword', (err: any, pkcs12: any) => {
test.ifError(err);
test.ok(pkcs12);
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
});
});
},
'Create PKCS12 with key password': (test: any) => {
pem.createPrivateKey({cipher: 'aes128', password: 'xxx'}, (error: any, data: any) => {
const key = (data && data.key || '').toString();
pem.createCertificate({
clientKey: key,
selfSigned: true
}, (error: any, csr: any) => {
pem.createPkcs12(csr.clientKey, csr.certificate, 'mypassword', {cipher: 'aes256', clientKeyPassword: 'xxx'}, (err: any, pkcs12: any) => {
test.ifError(err);
test.ok(pkcs12);
// test.ok(fs.readdirSync('./tmp').length === 0);
test.done();
});
});
});
},
'Create PKCS12 with ca certificates': (test: any) => {
pem.createCertificate({
commonName: 'CA Certificate'
}, (error: any, ca: any) => {
test.ifError(error);
pem.createCertificate({
serviceKey: ca.serviceKey,
serviceCertificate: ca.certificate,
serial: Date.now(),
}, (error: any, cert: any) => {
test.ifError(error);
pem.createPkcs12(cert.clientKey, cert.certificate, '', {certFiles: [ca.certificate]}, (error: any, pkcs12: any) => {
test.ifError(error);
test.ok(pkcs12.pkcs12);
// test.ok(fs.readdirSync('./tmp').length === 0);
const pkcs12Buffer = new Buffer(pkcs12.pkcs12);
pem.readPkcs12(pkcs12Buffer, (error: any, keystore: pem.Pkcs12ReadResult) => {
test.ifError(error);
test.ok(keystore);
test.equal(ca.certificate, keystore.ca[0]);
test.equal(cert.certificate, keystore.cert);
test.equal(cert.clientKey, keystore.key);
});
const pkcs12File: string = __dirname + '/test.pkcs12';
fs.writeFileSync(pkcs12File, pkcs12Buffer);
pem.readPkcs12(pkcs12File, (error: any, keystore: pem.Pkcs12ReadResult) => {
test.ifError(error);
test.ok(keystore);
test.equal(ca.certificate, keystore.ca[0]);
test.equal(cert.certificate, keystore.cert);
test.equal(cert.clientKey, keystore.key);
test.done();
});
});
});
});
},
'Respond with ENOENT for missing PKCS12 file': (test: any) => {
pem.readPkcs12('/i/do/not/exist.p12', (error: any) => {
test.ok(error);
test.equal(error.code, 'ENOENT');
test.done();
});
},
'Verify sigining chain': (test: any) => {
pem.createCertificate({
commonName: 'CA Certificate'
}, (error: any, ca: any) => {
test.ifError(error);
pem.createCertificate({
serviceKey: ca.serviceKey,
serviceCertificate: ca.certificate,
serial: Date.now(),
}, (error: any, cert: any) => {
test.ifError(error);
pem.verifySigningChain(cert.certificate, ca.certificate, (error: any, valid: any) => {
test.ifError(error);
test.ok(valid === true);
test.done();
});
});
});
},
'Verify deep sigining chain': (test: any) => {
pem.createCertificate({
commonName: 'CA Certificate'
}, (error: any, ca: any) => {
test.ifError(error);
pem.createCertificate({
commonName: 'Intermediate CA Certificate',
serviceKey: ca.serviceKey,
serviceCertificate: ca.certificate,
serial: Date.now(),
}, (error: any, intermediate: any) => {
test.ifError(error);
pem.createCertificate({
serviceKey: intermediate.clientKey,
serviceCertificate: intermediate.certificate,
serial: Date.now(),
}, (error: any, cert: any) => {
test.ifError(error);
pem.verifySigningChain(cert.certificate, [ca.certificate, intermediate.certificate], (error: any, valid: any) => {
test.ifError(error);
test.ok(valid === true);
test.done();
});
});
});
});
},
'Fail to verify invalid sigining chain': (test: any) => {
pem.createCertificate({
commonName: 'CA Certificate'
}, (error: any, ca: any) => {
test.ifError(error);
pem.createCertificate({
serviceKey: ca.serviceKey,
serviceCertificate: ca.certificate,
serial: Date.now(),
}, (error: any, cert: any) => {
test.ifError(error);
pem.verifySigningChain(cert.certificate, cert.certificate, (error: any, valid: any) => {
test.ifError(error);
test.ok(valid === false);
test.done();
});
});
});
},
'Fail to verify deep sigining chain with missing CA certificate': (test: any) => {
pem.createCertificate({
commonName: 'CA Certificate'
}, (error: any, ca: any) => {
test.ifError(error);
pem.createCertificate({
commonName: 'Intermediate CA Certificate',
serviceKey: ca.serviceKey,
serviceCertificate: ca.certificate,
serial: Date.now(),
}, (error: any, intermediate: any) => {
test.ifError(error);
pem.createCertificate({
serviceKey: intermediate.clientKey,
serviceCertificate: intermediate.certificate,
serial: Date.now(),
}, (error: any, cert: any) => {
test.ifError(error);
pem.verifySigningChain(cert.certificate, [intermediate.certificate], (error: any, valid: any) => {
test.ifError(error);
test.ok(valid === false);
test.done();
});
});
});
});
},
'Fail to verify deep sigining chain with missing intermediate certificate': (test: any) => {
pem.createCertificate({
commonName: 'CA Certificate'
}, (error: any, ca: any) => {
test.ifError(error);
pem.createCertificate({
commonName: 'Intermediate CA Certificate',
serviceKey: ca.serviceKey,
serviceCertificate: ca.certificate,
serial: Date.now(),
}, (error: any, intermediate: any) => {
test.ifError(error);
pem.createCertificate({
serviceKey: intermediate.clientKey,
serviceCertificate: intermediate.certificate,
serial: Date.now(),
days: 1024
}, (error: any, cert: any) => {
test.ifError(error);
pem.verifySigningChain(cert.certificate, [ca.certificate], (error: any, valid: any) => {
test.ifError(error);
test.ok(valid === false);
test.done();
});
});
});
});
}
}; | the_stack |
import { EventEmitter } from "events";
import * as most from "most";
import { Promise } from "bluebird";
import { StreamDSL } from "./StreamDSL";
import { LastState } from "../actions";
import { StorageMerger } from "../StorageMerger";
import { messageProduceHandle } from "../messageProduceHandle";
const MESSAGE = "message";
const NOOP = () => { };
/**
* table representation of a stream
*/
export class KTable extends StreamDSL {
public _tee: any;
public started: any;
public finalised: any;
public consumerOpen: any;
/**
* creates a table representation of a stream
* join operations of ktable instances are asynchronous
* and return promises
* keyMapETL = v -> {key, value} (sync)
* @param {string} topicName
* @param {function} keyMapETL
* @param {KStorage} storage
* @param {KafkaClient} kafka
* @param {boolean} isClone
*/
constructor(topicName, keyMapETL, storage = null, kafka = null, isClone = false) {
super(topicName, storage, kafka, isClone);
//KTable only works on {key, value} payloads
if (typeof keyMapETL !== "function") {
throw new Error("keyMapETL must be a valid function.");
}
this._tee = new EventEmitter();
this.started = false;
this.finalised = false;
//will close on first stream$.onComplete()
this.consumerOpen = true;
if (!isClone) {
this.map(keyMapETL);
} else {
this.consumerOpen = false;
this.started = true;
this._bindToTableStream();
}
}
/**
* start kafka consumption
* prepare production of messages if necessary
* when called with zero or just a single callback argument
* this function will return a promise and use the callback for errors
* @param {function|Object} kafkaReadyCallback - can also be an object (config)
* @param {function} kafkaErrorCallback
* @param {boolean} withBackPressure
* @param {Object} outputKafkaConfig
*/
start(kafkaReadyCallback = null, kafkaErrorCallback = null, withBackPressure = false, outputKafkaConfig = null) {
if (kafkaReadyCallback && typeof kafkaReadyCallback === "object" && arguments.length < 2) {
return new Promise((resolve, reject) => {
this._start(resolve, reject, kafkaReadyCallback.withBackPressure, kafkaReadyCallback.outputKafkaConfig);
});
}
if (arguments.length < 2) {
return new Promise((resolve, reject) => {
this._start(resolve, reject, withBackPressure);
});
}
return this._start(kafkaReadyCallback, kafkaErrorCallback, withBackPressure, outputKafkaConfig);
}
_start(kafkaReadyCallback = null, kafkaErrorCallback = null, withBackPressure = false, outputKafkaConfig = null) {
if (this.started) {
throw new Error("this KTable is already started.");
}
this.started = true;
if (!this.topicName && !this.produceAsTopic) {
return kafkaReadyCallback(); //possibly a good idea to skip finalise()
}
if (!this.finalised) {
this.finalise();
}
let producerReady = false;
let consumerReady = false;
const onReady = (type) => {
switch (type) {
case "producer": producerReady = true; break;
case "consumer": consumerReady = true; break;
}
//consumer && producer
if (producerReady && consumerReady && kafkaReadyCallback) {
kafkaReadyCallback();
}
//consumer only
if (!this.produceAsTopic && consumerReady && kafkaReadyCallback) {
kafkaReadyCallback();
}
//producer only
if (this.produceAsTopic && producerReady && kafkaReadyCallback && !this.kafka.topic && !this.kafka.topic.length) {
kafkaReadyCallback();
}
};
//overwrite kafka topics
this.kafka.overwriteTopics(this.topicName);
this.kafka.on(MESSAGE, msg => {
if (!this.consumerOpen) {
return;
}
super.writeToStream(msg);
});
this.kafka.start(() => { onReady("consumer"); }, kafkaErrorCallback, this.produceAsTopic, withBackPressure);
if (this.produceAsTopic) {
this.kafka.setupProducer(this.outputTopicName, this.outputPartitionsCount, () => { onReady("producer"); },
kafkaErrorCallback, outputKafkaConfig);
super.forEach(message => {
messageProduceHandle(
this.kafka,
message,
this.outputTopicName,
this.produceType,
this.produceCompressionType,
this.produceVersion,
kafkaErrorCallback
);
});
}
}
/**
* Emits an output when both input sources have records with the same key.
* @param {StreamDSL} stream
* @param {string} key
*/
innerJoin(stream, key = "key") {
throw new Error("not implemented yet."); //TODO implement
}
/**
* Emits an output for each record in either input source.
* If only one source contains a key, the other is null
* @param {StreamDSL} stream
*/
outerJoin(stream) {
throw new Error("not implemented yet."); //TODO implement
}
/**
* Emits an output for each record in the left or primary input source.
* If the other source does not have a value for a given key, it is set to null
* @param {StreamDSL} stream
*/
leftJoin(stream) {
throw new Error("not implemented yet."); //TODO implement
}
/**
* write message to the internal stream
* @param {any} message
*/
writeToTableStream(message) {
this._tee.emit(MESSAGE, message);
}
finalise(buildReadyCallback = null) {
if (this.finalised) {
throw new Error("this KTable has already been finalised.");
}
// a KStream is a simple changelog implementation (which StreamDSL delivers by default)
// a KTable is a table stream representation meaning that only the latest representation of
// a message must be present
const lastState = new LastState(this.storage);
this.asyncMap(lastState.execute.bind(lastState));
this.stream$.forEach(NOOP).then(_ => {
//streams until completed
this.kafka.closeConsumer();
this.consumerOpen = false;
if (typeof buildReadyCallback === "function") {
buildReadyCallback();
}
});
this._bindToTableStream();
this.finalised = true;
}
_bindToTableStream() {
this.stream$ = most.merge(this.stream$, most.fromEvent(MESSAGE, this._tee));
}
/**
* consume messages until ms passed
* @param {number} ms
* @param {function} finishedCallback
* @returns {KTable}
*/
consumeUntilMs(ms = 1000, finishedCallback = null) {
super.multicast();
// TODO we passing undefined here. Is that right?
this.stream$ = this.stream$.until(most.of(undefined).delay(ms));
if (!this.finalised) {
this.finalise(finishedCallback);
}
return this;
}
/**
* consume messages until a certain count is reached
* @param {number} count
* @param {function} finishedCallback
* @returns {KTable}
*/
consumeUntilCount(count = 1000, finishedCallback = null) {
super.multicast();
this.stream$ = this.stream$.take(count);
if (!this.finalised) {
this.finalise(finishedCallback);
}
return this;
}
/**
* consume messages until latest offset of topic
* @param {function} finishedCallback
*/
consumeUntilLatestOffset(finishedCallback = null) {
throw new Error("not implemented yet."); //TODO implement
/*
super.multicast();
if(!this.finalised){
this.finalise(finishedCallback);
} */
}
/**
* returns the state of the internal KStorage
* @returns {Promise<object>}
*/
getTable() {
return this.storage.getState();
}
/**
* rewrites content of internal KStorage
* to the stream, every observer will receive
* the content as KV {key, value} object
*/
replay() {
Object.keys(this.storage.state).forEach(key => {
const message = {
key: key,
value: this.storage.state[key]
};
this.writeToTableStream(message);
});
}
/**
* Emits an output for each record in any of the streams.
* Acts as simple merge of both streams.
* can be used with KStream or KTable instances
* returns a Promise with a NEW KTable instance
* @param {StreamDSL} stream
* @returns {Promise.<KTable>}
*/
merge(stream) {
if (!(stream instanceof StreamDSL)) {
throw new Error("stream has to be an instance of KStream or KTable.");
}
//multicast prevents replays
//create a new internal stream that merges both KStream.stream$s
const newStream$ = this.stream$.multicast().merge(stream.stream$.multicast());
return StorageMerger.mergeIntoState([this.getStorage(), stream.getStorage()]).then(mergedState => {
return this._cloneWith(newStream$, mergedState);
});
}
_cloneWith(newStream$, storageState = {}) {
const kafkaStreams = this._kafkaStreams;
if (!kafkaStreams) {
throw new Error("merging requires a kafka streams reference on the left-hand merger.");
}
const newStorage = kafkaStreams.getStorage();
const newKafkaClient = kafkaStreams.getKafkaClient();
return newStorage.setState(storageState).then(_ => {
const newInstance = new KTable(null, NOOP, newStorage, newKafkaClient, true);
newInstance.replaceInternalObservable(newStream$);
return newInstance;
});
}
/**
* as only joins and window operations return new stream instances
* you might need a clone sometimes, which can be accomplished
* using this function
* @returns {Promise.<KTable>}
*/
clone() {
const newStream$ = this.stream$.tap(NOOP);
return this._cloneWith(newStream$);
}
/**
* closes the internal stream
* and all kafka open connections
* as well as KStorage connections
* @returns {Promise.<boolean>}
*/
close() {
this.stream$ = this.stream$.take(0);
this.stream$ = null;
this.kafka.close();
return this.storage.close();
}
} | the_stack |
import React from 'react';
import { bind } from 'lodash-decorators';
import clsx from 'clsx';
import * as DraftJs from 'draft-js';
import { List } from 'immutable';
import { VisibilityProperty } from 'csstype';
import {
LinkDecorator,
isSoftNewLineEvent,
isListBlock,
RichTextEditorCommand,
RichTextEditorStyleMap,
isContentStateInUndoStack,
} from 'lib/richtext';
import * as Utils from 'lib/utils';
import { matchKeyPress, matchKeyMap, KeyMap } from 'lib/utils/keyboard';
import { RichTextEditorToolBar } from 'ui/RichTextEditorToolBar/RichTextEditorToolBar';
import './RichTextEditor.scss';
const compositeDecorator = new DraftJs.CompositeDecorator([LinkDecorator]);
const MAX_LIST_DEPTH = 5;
export interface IRichTextEditorProps {
className?: string;
readOnly?: boolean;
value: DraftJs.ContentState;
onChange?: (editorState: DraftJs.EditorState) => any;
onKeyDown?: (
event: React.KeyboardEvent,
editorState: DraftJs.EditorState
) => boolean;
onFocus?: () => any;
onBlur?: () => any;
decorator?: DraftJs.CompositeDecorator;
}
export interface IRichTextEditorState {
editorState: DraftJs.EditorState;
toolBarStyle: React.CSSProperties;
}
export class RichTextEditor extends React.PureComponent<
IRichTextEditorProps,
IRichTextEditorState
> {
public static defaultProps: Partial<IRichTextEditorProps> = {
readOnly: false,
};
public readonly state = {
editorState: DraftJs.EditorState.createWithContent(
this.props.value,
this.props.decorator ?? compositeDecorator
),
toolBarStyle: {
top: 0,
left: 0,
visibility: 'hidden' as 'hidden',
},
};
private editorRef = React.createRef<DraftJs.Editor>();
private toolBarRef = React.createRef<RichTextEditorToolBar>();
private selfRef = React.createRef<HTMLDivElement>();
@bind
public focus() {
if (this.editorRef) {
this.editorRef.current.focus();
this.setState({
toolBarStyle: this.calculateToolBarStyle(
this.state.editorState.getSelection()
),
});
}
}
@bind
public calculateToolBarPosition() {
if (!this.toolBarRef.current?.selfRef) {
return null;
}
const toolBarDivRef = this.toolBarRef.current.selfRef;
const toolBarHeight = toolBarDivRef.current.clientHeight;
const toolBarWidth = toolBarDivRef.current.clientWidth;
const selectionRect = Utils.getSelectionRect();
if (selectionRect == null) {
return null;
}
const position = {
top: Math.max(selectionRect.top - toolBarHeight - 5, 0),
left: Math.max(
selectionRect.left + (selectionRect.width - toolBarWidth) / 2,
0
),
};
return position;
}
@bind
public calculateToolBarStyle(selection: DraftJs.SelectionState) {
const isVisible = !selection.isCollapsed() && selection.getHasFocus();
const position =
(isVisible ? this.calculateToolBarPosition() : null) || {};
return {
...position,
visibility: (isVisible
? 'visible'
: 'hidden') as VisibilityProperty,
};
}
@bind
public onChange(editorState: DraftJs.EditorState) {
this.setState((state) => {
const previousSelection = state.editorState.getSelection();
const currentSelection = editorState.getSelection();
const toolBarStyle =
previousSelection !== currentSelection
? this.calculateToolBarStyle(currentSelection)
: state.toolBarStyle;
return {
...state,
editorState,
toolBarStyle,
};
});
if (this.props.onChange) {
this.props.onChange(editorState);
}
}
@bind
public handleReturnSoftNewLine(
editorState: DraftJs.EditorState,
event: React.KeyboardEvent
) {
const selection = editorState.getSelection();
if (isSoftNewLineEvent(event) && selection.isCollapsed()) {
this.onChange(DraftJs.RichUtils.insertSoftNewline(editorState));
return true;
}
return false;
}
@bind
public handleReturnList(editorState: DraftJs.EditorState) {
const selection = editorState.getSelection();
if (selection.isCollapsed()) {
const contentState = editorState.getCurrentContent();
const blockKey = selection.getStartKey();
const block = contentState.getBlockForKey(blockKey);
const blockType = block.getType();
const isListType = isListBlock(blockType);
if (isListType && block.getLength() === 0) {
const depth = block.getDepth();
let newEditorState: DraftJs.EditorState;
if (depth === 0) {
// Change block from list to unstyle
const newBlock = block.set(
'type',
'unstyled'
) as DraftJs.ContentBlock;
const newContentState = contentState.merge({
blockMap: contentState
.getBlockMap()
.set(blockKey, newBlock),
}) as DraftJs.ContentState;
newEditorState = DraftJs.EditorState.push(
editorState,
newContentState,
'change-block-type'
);
} else {
// Reduce depth of list by 1
const newBlock = block.set(
'depth',
depth - 1
) as DraftJs.ContentBlock;
const newContentState = contentState.merge({
blockMap: contentState
.getBlockMap()
.set(blockKey, newBlock),
}) as DraftJs.ContentState;
newEditorState = DraftJs.EditorState.push(
editorState,
newContentState,
'adjust-depth'
);
}
this.onChange(newEditorState);
return true;
}
}
return false;
}
@bind
public handleReturnSpecialBlock(editorState: DraftJs.EditorState) {
const selection = editorState.getSelection();
if (selection.isCollapsed()) {
const contentState = editorState.getCurrentContent();
const blockKey = selection.getStartKey();
const block = contentState.getBlockForKey(blockKey);
const blockType = block.getType();
const isSpecialBlock =
!isListBlock(blockType) && blockType !== 'unstyled';
if (
isSpecialBlock &&
block.getLength() === selection.getStartOffset()
) {
// If cursor is at the end
// Insert a new block after current block
const blockMap = contentState.getBlockMap();
const blockSeq = blockMap.toSeq();
const blocksBefore = blockSeq.takeUntil((b) => b === block);
const blocksAfter = blockSeq
.skipUntil((b) => b === block)
.rest();
const newBlockKey = DraftJs.genKey();
const newBlock = new DraftJs.ContentBlock({
key: newBlockKey,
type: 'unstyled',
text: '',
characterList: List(),
});
const newBlockMap = blocksBefore
.concat(
[
[blockKey, block],
[newBlockKey, newBlock],
],
blocksAfter
)
.toOrderedMap();
const newContentState = contentState.merge({
blockMap: newBlockMap,
selectionBefore: selection,
selectionAfter: selection.merge({
anchorKey: newBlockKey,
anchorOffset: 0,
focusKey: newBlockKey,
focusOffset: 0,
isBackward: false,
}),
}) as DraftJs.ContentState;
const newEditorState = DraftJs.EditorState.push(
editorState,
newContentState,
'split-block'
);
this.onChange(newEditorState);
return true;
}
}
return false;
}
@bind
public handleReturn(event: React.KeyboardEvent) {
const { editorState } = this.state;
const newEditorStateWithLink = this.handleInputLink(editorState);
if (this.handleReturnSoftNewLine(newEditorStateWithLink, event)) {
return 'handled';
}
if (this.handleReturnList(newEditorStateWithLink)) {
return 'handled';
}
if (this.handleReturnSpecialBlock(newEditorStateWithLink)) {
return 'handled';
}
if (newEditorStateWithLink !== editorState) {
return 'handled';
}
return 'not-handled';
}
@bind
public handleInputLink(editorState: DraftJs.EditorState) {
const selectionState = editorState.getSelection();
const anchorKey = selectionState.getAnchorKey();
const currentContent = editorState.getCurrentContent();
const currentBlock = currentContent.getBlockForKey(anchorKey);
const end = selectionState.getEndOffset();
const textBeforeSelection = currentBlock.getText().slice(0, end);
const urlMatch = textBeforeSelection.match(/[^\s]+$/);
const url = urlMatch ? urlMatch[0] : '';
if (!url.startsWith('https://') && !url.startsWith('http://')) {
return editorState;
}
const start = urlMatch.index;
// If the text is already a link do not toggle.
const entityAtStart = currentBlock.getEntityAt(start);
const isAlreadyLink =
entityAtStart !== null &&
currentContent.getEntity(entityAtStart).getType() === 'LINK';
if (isAlreadyLink) {
return editorState;
}
// Create link entity connected to text starting with https:// or http://
const contentStateWithEntity = currentContent.createEntity(
'LINK',
'MUTABLE',
{ url }
);
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
const newEditorState = DraftJs.EditorState.push(
editorState,
contentStateWithEntity,
'apply-entity'
);
const emptySelectionState = DraftJs.SelectionState.createEmpty(
anchorKey
);
const linkSelectionState = emptySelectionState.merge({
anchorOffset: start,
focusKey: anchorKey,
focusOffset: end,
});
// Selection state at end of url to move cursor to end of link
const endSelectionState = emptySelectionState.merge({
anchorOffset: end,
focusKey: anchorKey,
focusOffset: end,
hasFocus: true,
});
const newEditorStateWithLink = DraftJs.EditorState.forceSelection(
DraftJs.RichUtils.toggleLink(
newEditorState,
linkSelectionState as DraftJs.SelectionState,
entityKey
),
endSelectionState as DraftJs.SelectionState
);
this.onChange(newEditorStateWithLink);
return newEditorStateWithLink;
}
@bind
public handleBeforeInput(chars: string, editorState: DraftJs.EditorState) {
if (/\s/.test(chars)) {
// Convert links to url if applicable
const newEditorStateWithLink = this.handleInputLink(editorState);
if (newEditorStateWithLink === editorState) {
return 'not-handled';
}
// Insert original character that was input
const newContentState = DraftJs.Modifier.replaceText(
newEditorStateWithLink.getCurrentContent(),
newEditorStateWithLink.getSelection(),
chars
);
const newEditorStateWithChars = DraftJs.EditorState.push(
newEditorStateWithLink,
newContentState,
'insert-characters'
);
this.onChange(newEditorStateWithChars);
return 'handled';
}
return 'not-handled';
}
@bind
public onTab(event: React.KeyboardEvent) {
const { editorState } = this.state;
const newEditorState = DraftJs.RichUtils.onTab(
event,
editorState,
MAX_LIST_DEPTH
);
if (newEditorState !== editorState) {
this.onChange(newEditorState);
} else {
const newEditorStateWithLink = this.handleInputLink(editorState);
const newContentState = DraftJs.Modifier.replaceText(
newEditorStateWithLink.getCurrentContent(),
newEditorStateWithLink.getSelection(),
' '
);
const newEditorStateWithTab = DraftJs.EditorState.push(
newEditorStateWithLink,
newContentState,
'insert-characters'
);
this.onChange(newEditorStateWithTab);
}
}
@bind
public keyBindingFn(e: React.KeyboardEvent): RichTextEditorCommand {
let handled = false;
let command: RichTextEditorCommand = null;
// parent component key presses
if (this.props.onKeyDown) {
handled = this.props.onKeyDown(e, this.state.editorState);
}
// Default key presses
if (!handled) {
if (matchKeyPress(e, 'Tab')) {
this.onTab(e);
handled = true;
} else if (matchKeyMap(e, KeyMap.richText.strikethrough)) {
// Cmd+Shift+X
command = 'strikethrough';
handled = true;
} else if (matchKeyMap(e, KeyMap.richText.addLink)) {
command = 'show-link-input';
handled = true;
} else if (matchKeyMap(e, KeyMap.richText.bold)) {
command = 'bold';
handled = true;
} else if (matchKeyMap(e, KeyMap.richText.italics)) {
command = 'italic';
handled = true;
}
}
// Fall through to default behavior
if (!handled) {
command = DraftJs.getDefaultKeyBinding(e);
handled = !!command;
}
// stop event progation if the event is
// either handled by default behavior or custom behaivor
if (handled) {
e.stopPropagation();
e.preventDefault();
}
return command;
}
@bind
public handleKeyCommand(
command: RichTextEditorCommand,
editorState: DraftJs.EditorState
) {
switch (command) {
case 'show-link-input': {
if (!editorState.getSelection().isCollapsed()) {
this.toolBarRef.current.showLinkInput();
return 'handled';
}
}
case 'strikethrough': {
this.onChange(
DraftJs.RichUtils.toggleInlineStyle(
editorState,
'STRIKETHROUGH'
)
);
return 'handled';
}
default: {
const newState = DraftJs.RichUtils.handleKeyCommand(
editorState,
command
);
if (newState) {
this.onChange(newState);
return 'handled';
}
}
}
return 'not-handled';
}
public componentDidUpdate(prevProps: IRichTextEditorProps) {
if (
prevProps.value !== this.props.value &&
this.props.value !== this.state.editorState.getCurrentContent() &&
// This shouldn't happen, but just in case
!isContentStateInUndoStack(
this.props.value,
this.state.editorState.getUndoStack(),
5
)
) {
const newEditorState = DraftJs.EditorState.push(
this.state.editorState,
this.props.value,
'apply-entity'
);
this.setState({
editorState: newEditorState,
});
}
}
public componentDidCatch() {
// Suppressing error due to LinkDecorator failing on delete
// related github issue https://github.com/facebook/draft-js/issues/1320#issuecomment-476509968
this.forceUpdate();
}
public get editorState() {
return this.state.editorState;
}
public set editorState(editorState: DraftJs.EditorState) {
this.setState({
editorState,
});
}
public get draftJSEditor() {
return this.editorRef.current;
}
public getContent() {
return this.state.editorState.getCurrentContent();
}
public setContent(contentState: DraftJs.ContentState) {
this.setState({
editorState: DraftJs.EditorState.createWithContent(
contentState,
compositeDecorator
),
});
}
public render() {
const { className, onFocus, onBlur, readOnly } = this.props;
const { editorState, toolBarStyle } = this.state;
const toolBar = readOnly ? null : (
<div className="toolbar-wrapper" style={toolBarStyle}>
<RichTextEditorToolBar
ref={this.toolBarRef}
editorState={editorState}
focusEditor={this.focus}
onChange={this.onChange}
/>
</div>
);
const editor = (
<DraftJs.Editor
editorState={editorState}
keyBindingFn={this.keyBindingFn}
handleKeyCommand={this.handleKeyCommand}
onChange={this.onChange}
onFocus={onFocus}
onBlur={onBlur}
ref={this.editorRef}
handleReturn={this.handleReturn}
readOnly={readOnly}
spellCheck={true}
handleBeforeInput={this.handleBeforeInput}
customStyleMap={RichTextEditorStyleMap}
/>
);
const editorClassName = clsx({
RichTextEditor: true,
[className]: className,
});
return (
<div className={editorClassName} ref={this.selfRef}>
{toolBar}
{editor}
</div>
);
}
} | the_stack |
import 'mocha';
import { expect } from '@integration/testing-tools';
import { actorCalled, AssertionError, Expectation } from '@serenity-js/core';
import {
and,
contain,
containAtLeastOneItemThat,
endsWith,
Ensure,
equals,
includes,
isFalse,
isGreaterThan,
isLessThan,
isTrue,
not,
or,
startsWith,
} from '../../src';
describe('not', () => {
/** @test {not} */
it('allows for the actor flow to continue when the "actual" meets the expectation', () => {
return expect(actorCalled('Astrid').attemptsTo(
Ensure.that('Hello World!', not(startsWith('¡Hola'))),
)).to.be.fulfilled;
});
/** @test {not} */
it('breaks the actor flow when "actual" does not meet the expectation', () => {
return expect(actorCalled('Astrid').attemptsTo(
Ensure.that('Hello World!', not(startsWith('Hello'))),
)).to.be.rejectedWith(AssertionError, `Expected 'Hello World!' to not start with 'Hello'`)
.then((error: AssertionError) => {
expect(error.expected).to.equal('Hello');
expect(error.actual).to.equal('Hello World!');
});
});
/** @test {not} */
it('contributes to a human-readable description', () => {
expect(Ensure.that('Hello', not(startsWith('o'))).toString())
.to.equal(`#actor ensures that 'Hello' does not start with 'o'`);
});
it('flips the outcome of an assertion, but doesn\'t hide any errors that might have happened while making it', () => {
const blowsUp = () =>
Expectation.thatActualShould('blow up', 'expected')
.soThat((actual, expected) => {
throw new Error('boom');
});
return expect(actorCalled('Astrid').attemptsTo(
Ensure.that('Hello World!', not(blowsUp())),
)).to.be.rejectedWith(Error, `boom`);
});
describe('double negative', () => {
/** @test {not} */
it('contributes to a human-readable description', () => {
expect(Ensure.that('Hello', not(not(startsWith('o')))).toString())
.to.equal(`#actor ensures that 'Hello' does start with 'o'`);
});
});
describe('when combined with other assertions, such as', () => {
describe('and,', () => {
/** @test {not} */
/** @test {and} */
it('produces a sensible error message', () => {
return expect(actorCalled('Astrid').attemptsTo(
Ensure.that(3, not(and(isGreaterThan(2), isLessThan(4)))),
)).to.be.rejectedWith(AssertionError, `Expected 3 to not have value greater than 2 and have value that's less than 4`)
.then((error: AssertionError) => {
expect(error.expected).to.equal(4);
expect(error.actual).to.equal(3);
});
});
/** @test {not} */
/** @test {and} */
it('contributes to a human-readable description', () => {
expect(Ensure.that(3, not(and(isGreaterThan(2), isLessThan(4)))).toString())
.to.equal(`#actor ensures that 3 does not have value greater than 2 and have value that's less than 4`);
});
});
describe('contains,', () => {
/** @test {not} */
/** @test {contains} */
it('produces a sensible error message', () =>
expect(actorCalled('Astrid').attemptsTo(
Ensure.that([ 1, 2, 3 ], not(contain(2))),
)).
to.be.rejectedWith(AssertionError, `Expected [ 1, 2, 3 ] to not contain 2`).
then((error: AssertionError) => {
expect(error.expected).to.equal(2);
expect(error.actual).to.deep.equal([ 1, 2, 3 ]);
})
);
/** @test {not} */
/** @test {contains} */
it('contributes to a human-readable description', () => {
expect(Ensure.that([ 'H', 'e', 'l', 'l', 'o' ], not(contain('o'))).toString())
.to.equal(`#actor ensures that [ 'H', 'e', 'l', 'l', 'o' ] does not contain 'o'`);
});
});
describe('containAtLeastOneItemThat,', () => {
/** @test {not} */
/** @test {containAtLeastOneItemThat} */
it('produces a sensible error message', () =>
expect(actorCalled('Astrid').attemptsTo(
Ensure.that([ 1, 2, 3 ], not(containAtLeastOneItemThat(equals(2)))),
)).
to.be.rejectedWith(AssertionError, `Expected [ 1, 2, 3 ] to not contain at least one item that does equal 2`).
then((error: AssertionError) => {
expect(error.expected).to.equal(2);
expect(error.actual).to.deep.equal([ 1, 2, 3 ]);
})
);
/** @test {not} */
/** @test {containAtLeastOneItemThat} */
it('contributes to a human-readable description', () => {
expect(Ensure.that([ 'H', 'e', 'l', 'l', 'o' ], not(containAtLeastOneItemThat(equals('o')))).toString())
.to.equal(`#actor ensures that [ 'H', 'e', 'l', 'l', 'o' ] does not contain at least one item that does equal 'o'`);
});
});
describe('endsWith,', () => {
/** @test {not} */
/** @test {endsWith} */
it('produces a sensible error message', () => {
return expect(actorCalled('Astrid').attemptsTo(
Ensure.that('Hello', not(endsWith('o'))),
)).to.be.rejectedWith(AssertionError, `Expected 'Hello' to not end with 'o'`)
.then((error: AssertionError) => {
expect(error.expected).to.equal('o');
expect(error.actual).to.equal('Hello');
});
});
/** @test {not} */
/** @test {endsWith} */
it('contributes to a human-readable description', () => {
expect(Ensure.that('Hello', not(endsWith('o'))).toString())
.to.equal(`#actor ensures that 'Hello' does not end with 'o'`);
});
});
describe('equals,', () => {
/** @test {not} */
/** @test {equals} */
it('produces a sensible error message', () => {
return expect(actorCalled('Astrid').attemptsTo(
Ensure.that(true, not(equals(true))),
)).to.be.rejectedWith(AssertionError, `Expected true to not equal true`)
.then((error: AssertionError) => {
expect(error.expected).to.equal(true);
expect(error.actual).to.equal(true);
});
});
/** @test {not} */
/** @test {equals} */
it('contributes to a human-readable description', () => {
expect(Ensure.that(true, not(equals(true))).toString())
.to.equal(`#actor ensures that true does not equal true`);
});
});
describe('isTrue,', () => {
/** @test {not} */
/** @test {isTrue} */
it('produces a sensible error message', () => {
return expect(actorCalled('Astrid').attemptsTo(
Ensure.that(true, not(isTrue())),
)).to.be.rejectedWith(AssertionError, `Expected true to not equal true`)
.then((error: AssertionError) => {
expect(error.expected).to.equal(true);
expect(error.actual).to.equal(true);
});
});
/** @test {not} */
/** @test {isTrue} */
it('contributes to a human-readable description', () => {
expect(Ensure.that(true, not(isTrue())).toString())
.to.equal(`#actor ensures that true does not equal true`);
});
});
describe('isFalse,', () => {
/** @test {not} */
/** @test {isFalse} */
it('produces a sensible error message', () => {
return expect(actorCalled('Astrid').attemptsTo(
Ensure.that(false, not(isFalse())),
)).to.be.rejectedWith(AssertionError, `Expected false to not equal false`)
.then((error: AssertionError) => {
expect(error.expected).to.equal(false);
expect(error.actual).to.equal(false);
});
});
/** @test {not} */
/** @test {isFalse} */
it('contributes to a human-readable description', () => {
expect(Ensure.that(false, not(isFalse())).toString())
.to.equal(`#actor ensures that false does not equal false`);
});
});
describe('includes,', () => {
/** @test {not} */
/** @test {includes} */
it('produces a sensible error message', () => {
return expect(actorCalled('Astrid').attemptsTo(
Ensure.that('Hello', not(includes('Hello'))),
)).to.be.rejectedWith(AssertionError, `Expected 'Hello' to not include 'Hello'`)
.then((error: AssertionError) => {
expect(error.expected).to.equal('Hello');
expect(error.actual).to.equal('Hello');
});
});
/** @test {not} */
/** @test {includes} */
it('contributes to a human-readable description', () => {
expect(Ensure.that('Hello', not(includes('Hello'))).toString())
.to.equal(`#actor ensures that 'Hello' does not include 'Hello'`);
});
});
describe('isGreaterThan,', () => {
/** @test {not} */
/** @test {isGreaterThan} */
it('produces a sensible error message', () => {
return expect(actorCalled('Astrid').attemptsTo(
Ensure.that(2, not(isGreaterThan(1))),
)).to.be.rejectedWith(AssertionError, `Expected 2 to not have value greater than 1`)
.then((error: AssertionError) => {
expect(error.expected).to.equal(1);
expect(error.actual).to.equal(2);
});
});
/** @test {not} */
/** @test {isGreaterThan} */
it('contributes to a human-readable description', () => {
expect(Ensure.that(2, not(isGreaterThan(1))).toString())
.to.equal(`#actor ensures that 2 does not have value greater than 1`);
});
});
describe('isLessThan,', () => {
/** @test {not} */
/** @test {isLessThan} */
it('produces a sensible error message', () => {
return expect(actorCalled('Astrid').attemptsTo(
Ensure.that(1, not(isLessThan(2))),
)).to.be.rejectedWith(AssertionError, `Expected 1 to not have value that's less than 2`)
.then((error: AssertionError) => {
expect(error.expected).to.equal(2);
expect(error.actual).to.equal(1);
});
});
/** @test {not} */
/** @test {isLessThan} */
it('contributes to a human-readable description', () => {
expect(Ensure.that(1, not(isLessThan(2))).toString())
.to.equal(`#actor ensures that 1 does not have value that's less than 2`);
});
});
describe('or,', () => {
/** @test {not} */
/** @test {or} */
it('produces a sensible error message', () => {
return expect(actorCalled('Astrid').attemptsTo(
Ensure.that(1, not(or(isGreaterThan(0), isLessThan(2)))),
)).to.be.rejectedWith(AssertionError, `Expected 1 to not have value greater than 0 or have value that's less than 2`)
.then((error: AssertionError) => {
expect(error.expected).to.equal(0);
expect(error.actual).to.equal(1);
});
});
/** @test {not} */
/** @test {or} */
it('contributes to a human-readable description', () => {
expect(Ensure.that(1, not(isLessThan(2))).toString())
.to.equal(`#actor ensures that 1 does not have value that's less than 2`);
});
});
describe('startsWith,', () => {
/** @test {not} */
/** @test {startsWith} */
it('produces a sensible error message', () => {
return expect(actorCalled('Astrid').attemptsTo(
Ensure.that('Hello', not(startsWith('H'))),
)).to.be.rejectedWith(AssertionError, `Expected 'Hello' to not start with 'H'`)
.then((error: AssertionError) => {
expect(error.expected).to.equal('H');
expect(error.actual).to.equal('Hello');
});
});
/** @test {not} */
/** @test {startsWith} */
it('contributes to a human-readable description', () => {
expect(Ensure.that('Hello', not(startsWith('H'))).toString())
.to.equal(`#actor ensures that 'Hello' does not start with 'H'`);
});
});
});
}); | the_stack |
import SObject from '../Core/SObject';
import {SClass} from '../Core/Decorator';
import Texture from '../Texture/Texture';
import Debug from '../Debug';
import {Matrix3} from '../Core/Math';
/**
* `AtlasManager`的初始化参数类型。
*/
export interface IAtlasOptions {
/**
* 图片。
*/
image?: HTMLImageElement | HTMLCanvasElement;
/**
* 也可以直接传入一张纹理。
*/
texture?: Texture;
/**
* 帧定义,若不指定`uv`则会自动按比例计算。
*/
frames: {
[key: string]: {
/**
* 帧的区块信息。
*/
frame: {x: number, y: number, w: number, h: number};
/**
* 会自动生成,开发者无需关心。
*
* @hidden
*/
uvMatrix?: Matrix3;
/**
* 用于动态分配,开发者无需关心。
*
* @hidden
*/
right?: string;
/**
* 用于动态分配,开发者无需关心。
*
* @hidden
*/
down?: string;
/**
* 用于动态分配,开发者无需关心。
*
* @hidden
*/
space?: number;
};
};
/**
* 原信息,主要定义图片尺寸。
*/
meta: {
size: {w: number, h: number}
};
}
/**
* 判断一个实例是否为`AtlasManager`。
*/
export function isAtlasManager(value: any): value is AtlasManager {
return (value as AtlasManager).isAtlasManager;
}
function isPowerOfTwo(x: number) {
return (Math.log(x) / Math.log(2)) % 1 === 0;
}
export interface IAtlasCreationOptions {
/**
* 单元宽度。
*/
cellWidth?: number;
/**
* 单元高度。
*/
cellHeight?: number;
/**
* 单元间的间隙。
*/
spacing?: number;
/**
* 每行有多少帧(单元)。
*/
framesPerLine: number;
/**
* 需要从哪一帧开始。
*/
frameStart?: number;
/**
* 需要几帧。
*/
frameCount?: number;
}
/**
* 图集管理器。
* 一般通过`AtlasLoader`加载自动生成。
*
* @noInheritDoc
*/
@SClass({className: 'AtlasManager'})
export default class AtlasManager extends SObject {
public isAtlasManager = true;
protected _AUTO_ID = 0;
protected _image: HTMLCanvasElement;
protected _ctx: CanvasRenderingContext2D;
protected _tmpCanvas: HTMLCanvasElement;
protected _texture: Texture;
protected _frames: IAtlasOptions['frames'];
protected _meta: IAtlasOptions['meta'];
protected _canvases: {[frame: string]: HTMLCanvasElement};
protected _textures: {[frame: string]: Texture};
protected _updatable: boolean;
protected _root: string;
protected _area: number = 0;
protected _needReBuild: boolean = false;
/**
* 根据宽高创建一个空的图集,可自由申请或释放帧。
*/
public static CREATE_EMPTY(options: {width: number, height: number}) {
const {width, height} = options;
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const context = canvas.getContext('2d');
context.fillStyle = 'rgba(255, 255, 255, 0)';
context.fillRect(0, 0, width, height);
return new AtlasManager({image: canvas, frames: {}, meta: {size: {w: width, h: height}}}, true);
}
/**
* 根据宽高和行数、列数来创建一个空的图集。
* 这个图集将被行列分成若干个格子帧,开发者可以根据实际状况去使用`updateFrame`更新这些格子。
* 自动生成的帧的名字为`${row}${col}`,比如第一行第一列为`'11'`。
*
* @param onDraw 初始化时的回调,可以用于一开始绘制图像
*/
public static CREATE_FROM_GRIDS(
options: {
width: number,
height: number,
rows: number,
cols: number,
space?: number
},
onDraw?: (
atlas: AtlasManager,
context: CanvasRenderingContext2D,
region: {col: number, row: number, x: number, y: number, w: number, h: number},
frameName: string
) => void
) {
let {width, height, rows, cols, space} = options;
space = space || 0;
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const context = canvas.getContext('2d');
context.fillStyle = 'rgba(255, 255, 255, 0)';
context.fillRect(0, 0, width, height);
const w = ~~(width / cols) - space;
const h = ~~(height / rows) - space;
const frames = {};
for (let row = 0; row < rows; row += 1) {
for (let col = 0; col < cols; col += 1) {
const frameName = `${row}${col}`;
const x = col * (w + space);
const y = row * (h + space);
frames[frameName] = {
frame: {x, y, w, h},
space
};
}
}
const atlas = new AtlasManager({image: canvas, frames, meta: {size: {w: width, h: height}}}, true);
if (onDraw) {
for (let row = 0; row < rows; row += 1) {
for (let col = 0; col < cols; col += 1) {
const frameName = `${row}${col}`;
const {x, y, w, h} = atlas.getFrame(frameName);
onDraw(atlas, context, {x, y, w, h, row, col}, frameName);
}
}
}
return atlas;
}
/**
* 根据纹理和配置,来通过纹理创建一个不可修改的图集。通常用于精灵动画。
* 这个图集将被行列分成若干个格子帧,每一帧的名字为`0`、`1`、`2`......
*/
public static CREATE_FROM_TEXTURE(texture: Texture, options: IAtlasCreationOptions) {
const w = options.cellWidth;
const h = options.cellHeight;
const {origWidth: width, origHeight: height} = texture;
const spacing = options.spacing || 0;
const {framesPerLine} = options;
let {frameStart, frameCount} = options;
if (frameStart === undefined) {
frameStart = 0;
}
if (frameCount === undefined) {
frameCount = Infinity;
}
const frames = {};
let i = frameStart;
while (true) {
const row = framesPerLine === 1 ? i : ~~(i / framesPerLine);
const col = framesPerLine === 1 ? 0 : i % framesPerLine;
const x = col * (w + spacing);
const y = row * (h + spacing);
if (i >= frameCount || (y + h + spacing >= height)) {
break;
}
frames[i] = {
frame: {x, y, w, h}
};
i += 1;
}
return new AtlasManager({texture, frames, meta: {size: {w: width, h: height}}}, false);
}
/**
* 构建一个图集。
*
* @param options 初始化参数。
* @param updatable 是否是一个可更新的图集,若不是则不可调用`updateFrame`等方法。注意`updatable`的图集本身容器的宽高都必须为**2的幂!**比如512、1024、2048等等。
*/
constructor(options: IAtlasOptions, updatable: boolean = true) {
super();
this._frames = options.frames;
this._meta = options.meta;
this._canvases = {};
this._textures = {};
this._updatable = updatable;
if (options.texture) {
this._image = options.texture.image as any;
this._texture = options.texture;
} else if (options.image instanceof HTMLCanvasElement) {
this._image = options.image;
this._ctx = this._image.getContext('2d');
} else if (updatable) {
if (Debug.devMode && !(isPowerOfTwo(this._meta.size.w) && isPowerOfTwo(this._meta.size.h))) {
throw new Error(`Atlas ${this.name} is updatable but it size is not power of two !`);
}
this._image = document.createElement('canvas');
this._image.width = this._meta.size.w;
this._image.height = this._meta.size.h;
this._ctx = this._image.getContext('2d');
this._ctx.drawImage(options.image, 0, 0);
} else {
this._image = options.image as any;
}
}
/**
* 获取整体图片数据。
*/
get image() {
return this._image;
}
/**
* 获取元信息。
*/
get meta() {
return this._meta;
}
/**
* 获取帧集合。
*/
get frames() {
return this._frames;
}
/**
* 获取整体的纹理,也可以使用`getWholeTexture`。
*/
get texture() {
return this.getWholeTexture();
}
/**
* 获取当前图集的使用率,仅在**动态图集**的状况下有效。
*/
get usage() {
const {w, h} = this._meta.size;
return this._area / (w * h);
}
/**
* 纹理提交GPU后是否释放CPU内存
*/
public isImageCanRelease?: boolean = false;
/**
* 获取某一帧的数据。
*/
public getFrame(frameName: string): {x: number, y: number, w: number, h: number} {
return this._frames[frameName].frame;
}
/**
* @deprecated
*
* 请用`getUVMatrix`
* 获取某一帧的uv。
*/
public getUV(frameName: string): {x: number, y: number, w: number, h: number} {
throw new Error('`getUV` is deprecated, please use `getUVMatrix`!')
}
/**
* 获取某一帧的uv变换矩阵。
*/
public getUVMatrix(frameName: string): Matrix3 {
const f = this._frames[frameName];
if (!f) {
throw new Error(`Frame ${frameName} is not existed!`);
}
const {uvMatrix, frame} = f;
if (!uvMatrix) {
f.uvMatrix = this.buildUVMatrix(frame);
}
return f.uvMatrix;
}
protected buildUVMatrix(frame: {x: number, y: number, w: number, h: number}) {
const {w, h} = this._meta.size;
const matrix = new Matrix3();
// flipY
matrix.set(
frame.w / w,
0,
0,
0,
-frame.h / h,
0,
frame.x / w,
(frame.y + frame.h) / h,
1
);
return matrix;
}
/**
* 获取某一帧的图片数据,**会创建独立的canvas,慎重使用!**。建议使用`getTexture`。
*/
public getFrameImage(frameName: string): HTMLCanvasElement {
if (!this._canvases[frameName]) {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const {x, y, w, h} = this._frames[frameName].frame;
canvas.width = w;
canvas.height = h;
context.drawImage(this._image, x, y, w, h);
this._canvases[frameName] = canvas;
}
return this._canvases[frameName];
}
/**
* 获取某一帧的纹理数据,**会创建独立的canvas,慎重使用!**。建议使用`getWholeTexture`。
*/
public getTexture(frameName: string, options?: any) {
if (!options && this._textures[frameName]) {
return this._textures[frameName];
}
const frame = this.getFrame(frameName);
const {x, y, w, h} = frame;
let image: ImageData;
if (this._image instanceof HTMLImageElement) {
if (!this._tmpCanvas) {
this._tmpCanvas = document.createElement('canvas');
this._tmpCanvas.width = this._image.width;
this._tmpCanvas.height = this._image.height;
}
const ctx = this._tmpCanvas.getContext('2d');
ctx.drawImage(this._image, x, y, w, h, 0, 0, w, h);
image = ctx.getImageData(0, 0, w, h);
} else if (this._image instanceof HTMLCanvasElement) {
const ctx = this._image.getContext('2d');
image = ctx.getImageData(x, y, w, h);
} else {
Debug.warn(`Image is 'ArrayBuffer', not support get a frame !`)
}
if (options) {
return new Texture({image, isImageCanRelease: this.isImageCanRelease, ...options});
}
this._textures[frameName] = new Texture({image, isImageCanRelease: this.isImageCanRelease});
return this._textures[frameName];
}
/**
* 获取整体纹理数据,建议配合`getFrame`或`getUVMatrix`在shader中使用。
*/
public getWholeTexture(options?: any) {
if (options) {
if (this._texture) {
this._texture.destroy();
}
return this._texture = new Texture({image: this._image, isImageCanRelease: this.isImageCanRelease, ...options});
}
if (!this._texture) {
this._texture = new Texture({image: this._image, isImageCanRelease: this.isImageCanRelease});
}
return this._texture;
}
/**
* 更新某一frame,通过`onDraw`方法参数中的`context`和`region`来更新`canvas`画布上此帧所占据区域内的图像,并同步到GPU。
*/
public updateFrame(
frameName: string,
onDraw: (context: CanvasRenderingContext2D, region: {x: number, y: number, w: number, h: number}, frameName: string) => void
) {
if (!this._updatable) {
throw new Error(`Atlas ${this.name} is not updatable !`);
}
if (this._canvases[frameName]) {
delete this._canvases[frameName];
}
if (this._textures[frameName]) {
delete this._textures[frameName];
}
const {x, y, w, h} = this.getFrame(frameName);
onDraw(this._ctx, {x, y, w, h}, frameName);
this.updateGlSubBuffer(x, y, w, h);
}
/**
* 申请分配指定的`region`大小的一帧,其中`frameName`是你想要赋予的名字,若不传会自动生成。
* 如果分配成功,则会通过`onDraw`的参数返回`context`、实际区域`region`和被分配的帧名`frameName`,你可以在这个方法中绘制。
*
* @returns [string] 若成功,将返回分配的`frame`的名字,否则返回`null`。
*/
public allocateFrame(
region: {w: number, h: number, space?: number, frameName?: string},
onDraw?: (
context: CanvasRenderingContext2D,
region: {x: number, y: number, w: number, h: number},
frameName: string
) => void
): string {
if (!this._updatable) {
throw new Error(`Atlas ${this.name} is not updatable !`);
}
let {frameName} = region;
if (frameName && this._frames[frameName]) {
throw new Error(`Frame named ${frameName} is not already existed !`);
}
if (this._needReBuild) {
this.rebuildFrames();
}
frameName = this.generateFrame(this._root, region);
if (!frameName) {
return null;
}
this._area += region.w * region.h;
if (onDraw) {
const {x, y, w, h} = this.getFrame(frameName);
onDraw(this._ctx, {x, y, w, h}, frameName);
this.updateGlSubBuffer(x, y, w, h);
}
return frameName;
}
protected generateFrame(
rootFrame: string,
region: {w: number, h: number, space?: number, frameName?: string},
bottom?: number
): string {
let {w, h, space = 0, frameName} = region;
let {size} = this._meta;
if (bottom === undefined) {
bottom = this._meta.size.h;
}
if (!this._root) {
return this._root = this.addFrame(0, 0, w, h, frameName);
}
const root = this._frames[rootFrame];
let {right, down, frame} = root;
const x = frame.x + frame.w + space;
const y = frame.y + frame.h + space;
const aW = size.w - x;
const aH = bottom - y;
if (!right && !down && w <= aW && h <= frame.h) {
return root.right = this.addFrame(x, frame.y, w, h, frameName, space);
}
if (!right && w <= aW && h <= frame.h) {
return root.right = this.addFrame(x, frame.y, w, h, frameName, space);
}
if (!down && w <= (size.w - frame.x) && h <= aH) {
return root.down = this.addFrame(frame.x, y, w, h, frameName, space);
}
if (right && (frameName = this.generateFrame(right, region, y))) {
return frameName;
}
if (down && (frameName = this.generateFrame(down, region, bottom))) {
return frameName;
}
return null;
}
public rebuildFrames() {
const {size} = this._meta;
if (!this._tmpCanvas) {
const tmp = this._tmpCanvas = document.createElement('canvas');
tmp.width = size.w;
tmp.height = size.h;
}
const tmpCtx = this._tmpCanvas.getContext('2d');
tmpCtx.drawImage(this._image, 0, 0);
this._ctx.clearRect(0, 0, size.w, size.h);
this._ctx.fillStyle = 'rgba(255, 255, 255, 0)';
this._ctx.fillRect(0, 0, size.w, size.h);
const frames = Object.assign({}, this._frames);
this._frames = {};
this._root = null;
const keys = Object.keys(frames).sort((a, b) => {
return frames[b].frame.h - frames[a].frame.h;
});
keys.forEach(frameName => {
const frame = frames[frameName];
const {w, h} = frame.frame;
this.generateFrame(this._root, {w, h, frameName, space: frame.space});
const {x, y} = this._frames[frameName].frame;
const orig = frames[frameName].frame;
this._ctx.drawImage(this._tmpCanvas, orig.x, orig.y, w, h, x, y, w, h)
});
this.updateGlSubBuffer(0, 0, size.w, size.h);
this._needReBuild = false;
}
protected addFrame(x: number, y: number, w: number, h: number, frameName?: string, space?: number) {
frameName = frameName || `AUTO-${this._AUTO_ID++}`;
this._frames[frameName] = {frame: {x, y, w, h}, space};
return frameName;
}
/**
* 释放一帧的空间,将其标记为可分配状态。
*/
public releaseFrame(frameName: string) {
if (!this._updatable) {
throw new Error(`Atlas ${this.name} is not updatable !`);
}
const frame = this._frames[frameName];
if (frame) {
if (this._texture[frameName]) {
this._texture.destroy();
}
if (this._canvases[frameName]) {
delete this._canvases[frameName];
}
delete this._frames[frameName];
this._area -= frame.frame.h * frame.frame.w;
this._needReBuild = true;
}
}
protected updateGlSubBuffer(x: number, y: number, w: number, h: number) {
if (!this._texture) {
return;
}
this._texture.updateSubTexture(x, this._texture.flipY ? this._meta.size.h - y - h : y, this._ctx.getImageData(x, y, w, h));
}
/**
* 完全销毁释放图集。
*/
public destroy() {
for (const key in this._textures) {
this._textures[key].destroy();
}
if (this._texture) {
this._texture.destroy();
}
}
} | the_stack |
import { Component } from 'vue-property-decorator';
import _ from 'lodash';
import * as history from './history';
import ColumnSelect from '@/components/column-select/column-select';
import ConstantsList from '@/components/constants-list/constants-list';
import FormInput from '@/components/form-input/form-input';
import FormSelect from '@/components/form-select/form-select';
import template from './attribute-filter.html';
import { INDEX_COLUMN } from '@/common/constants';
import { SubsetInputPort, SubsetOutputPort, ConstantsInputPort } from '@/components/port';
import { SubsetPackage } from '@/data/package';
import { ValueType } from '@/data/parser';
import { getColumnSelectOptions } from '@/data/util';
import { injectNodeTemplate } from '@/components/node';
import { valueDisplay } from '@/common/util';
import SubsetNodeCommon from '../subset-node/subset-node-common';
export enum FilterType {
PATTERN = 'pattern',
RANGE = 'range',
EXTREMUM = 'extremum',
SAMPLING = 'sampling',
}
export enum PatternMatchMode {
FULL_STRING = 'full-string',
SUBSTRING = 'substring',
REGEX = 'regex',
}
enum ConstantsMode {
INPUT = 'input',
RECEIVED = 'received',
}
export enum ExtremumCriterion {
MINIMUM = 'minimum',
MAXIMUM = 'maximum',
}
/**
* Currently samplingCriterion can only be set to RANDOM.
* This is to avoid confusing the user with too complicated combined options.
*/
export enum SamplingCriterion {
MINIMUM = 'minimum',
MAXIMUM = 'maximum',
RANDOM = 'random',
}
export enum AmountType {
COUNT = 'count',
PERCENTAGE = 'percentage',
}
interface PatternParams {
patterns: string[];
mode: PatternMatchMode;
isCaseSensitive: boolean;
}
interface RangeParams {
min: number | string | null;
max: number | string | null;
}
interface AttributeFilterSave {
column: number | null;
filterType: FilterType;
patternParams: PatternParams;
rangeParams: RangeParams;
samplingCriterion: SamplingCriterion;
extremumCriterion: ExtremumCriterion;
amount: number | null;
amountType: AmountType;
isOnDistinctValues: boolean;
groupByColumn: number | null;
}
const DEFAULT_PATTERN_PARAMS: PatternParams = {
patterns: [],
mode: PatternMatchMode.SUBSTRING,
isCaseSensitive: false,
};
const DEFAULT_RANGE_PARAMS: RangeParams = {
min: null,
max: null,
};
@Component({
template: injectNodeTemplate(template),
components: {
ColumnSelect,
FormSelect,
ConstantsList,
FormInput,
},
})
export default class AttributeFilter extends SubsetNodeCommon {
protected NODE_TYPE = 'attribute-filter';
protected DEFAULT_WIDTH = 120;
protected RESIZABLE = true;
// Typing
protected inputPortMap: { [id: string]: SubsetInputPort | ConstantsInputPort } = {};
protected outputPortMap: { [id: string]: SubsetOutputPort } = {};
private column: number | null = null;
private filterType: FilterType = FilterType.PATTERN;
private patternParams = _.clone(DEFAULT_PATTERN_PARAMS);
private rangeParams = _.clone(DEFAULT_RANGE_PARAMS);
private extremumCriterion = ExtremumCriterion.MAXIMUM;
private samplingCriterion = SamplingCriterion.RANDOM;
private amount: number | null = null;
private amountType: AmountType = AmountType.PERCENTAGE;
// Sampling/extremum based on distinct values. Values are first uniqued before percentage or count is taken.
private isOnDistinctValues = false;
private groupByColumn: number | null = null;
get constantsMode(): ConstantsMode {
return this.inputPortMap.constants.isConnected() ? ConstantsMode.RECEIVED : ConstantsMode.INPUT;
}
get inputDisabled(): boolean {
return this.constantsMode === ConstantsMode.RECEIVED;
}
get constants(): Array<string | number> {
return (this.inputPortMap.constants as ConstantsInputPort).getConstantsPackage().getConstants();
}
get columnName(): string {
return this.dataset && this.column !== null ? this.getDataset().getColumnName(this.column) : '';
}
get groupByColumnName(): string {
return this.dataset && this.groupByColumn !== null ?
this.getDataset().getColumnName(this.groupByColumn) : '';
}
get columnType(): ValueType {
return this.dataset && this.column !== null ? this.getDataset().getColumnType(this.column) : ValueType.EMPTY;
}
get firstConstant(): string | number {
return this.constants.length ? this.constants[0] : '';
}
get secondConstant(): string | number {
return this.constants.length >= 2 ? this.constants[1] : (this.constants.length ? this.constants[1] : '');
}
get patternFilterDisplayText(): string {
let conjunction = 'is';
if (this.patternParams.mode === PatternMatchMode.SUBSTRING) {
conjunction = 'contains';
} else if (this.patternParams.mode === PatternMatchMode.REGEX) {
conjunction = 'matches';
}
const patterns: string[] = this.inputDisabled ?
this.constants.map(value => value.toString()) : this.patternParams.patterns;
const patternStr = patterns.length ? patterns.join(', ') : '(no pattern)';
return ` ${conjunction} ${patternStr}`;
}
get rangeFilterDisplayText(): string {
const min = this.inputDisabled ? this.firstConstant : this.rangeParams.min;
const max = this.inputDisabled ? this.secondConstant : this.rangeParams.max;
let rangeText = '';
if (min !== null && max !== null) {
rangeText = ` in [${valueDisplay(min, this.columnType)}, ${valueDisplay(max, this.columnType)}]`;
} else if (min === null && max !== null) {
rangeText = ' ≤ ' + valueDisplay(max, this.columnType);
} else if (min !== null && max === null) {
rangeText = ' ≥ ' + valueDisplay(min, this.columnType);
} else {
rangeText = '(no range)';
}
return rangeText;
}
get amountDisplayText(): string {
const amount = (this.inputDisabled ? this.firstConstant : this.amount) || '(no amount)';
return `${amount}${this.amountType === AmountType.PERCENTAGE ? '%' : ''}`;
}
get filterTypeOptions(): SelectOption[] {
return [
{ label: 'Pattern', value: FilterType.PATTERN },
{ label: 'Range', value: FilterType.RANGE },
{ label: 'Extremum', value: FilterType.EXTREMUM },
{ label: 'Sampling', value: FilterType.SAMPLING },
];
}
get patternMatchModeOptions(): SelectOption[] {
return [
{ label: 'Substring', value: PatternMatchMode.SUBSTRING },
{ label: 'Full String', value: PatternMatchMode.FULL_STRING },
{ label: 'Regular Expression', value: PatternMatchMode.REGEX },
];
}
get amountTypeOptions(): SelectOption[] {
return [
{ label: 'Percentage', value: AmountType.PERCENTAGE },
{ label: 'Count', value: AmountType.COUNT },
];
}
get extremumCriterionOptions(): SelectOption[] {
return [
{ label: 'Maximum', value: ExtremumCriterion.MAXIMUM },
{ label: 'Minimum', value: ExtremumCriterion.MINIMUM },
];
}
public setFilterType(type: FilterType) {
this.filterType = type;
this.updateAndPropagate();
}
public setColumn(column: number | null) {
this.column = column;
this.updateAndPropagate();
}
public setPatterns(patterns: string[]) {
this.patternParams.patterns = patterns;
this.updateAndPropagate();
}
public setPatternMatchMode(mode: PatternMatchMode) {
this.patternParams.mode = mode;
this.updateAndPropagate();
}
public setPatternCaseSensitive(value: boolean) {
this.patternParams.isCaseSensitive = value;
this.updateAndPropagate();
}
public setRangeMin(value: number | null) {
this.rangeParams.min = value;
this.updateAndPropagate();
}
public setRangeMax(value: number | null) {
this.rangeParams.max = value;
this.updateAndPropagate();
}
public setExtremumCriterion(criterion: ExtremumCriterion) {
this.extremumCriterion = criterion;
this.updateAndPropagate();
}
public setAmountType(type: AmountType) {
this.amountType = type;
this.updateAndPropagate();
}
public setAmount(amount: number | null) {
this.amount = amount;
this.updateAndPropagate();
}
public setGroupByColumn(column: number | null) {
this.groupByColumn = column;
this.updateAndPropagate();
}
public setOnDistinctValues(value: boolean) {
this.isOnDistinctValues = value;
this.updateAndPropagate();
}
protected get columnSelectOptionsWithIndex() {
const options = getColumnSelectOptions(this.dataset);
return this.filterType === FilterType.SAMPLING ?
options.concat({ value: INDEX_COLUMN, label: '[index]' }) : options;
}
protected onDatasetChange() {
if (this.column === null) {
return;
}
this.column = this.updateColumnOnDatasetChange(this.column);
}
protected created() {
this.serializationChain.push((): AttributeFilterSave => ({
column: this.column,
filterType: this.filterType,
patternParams: this.patternParams,
rangeParams: this.rangeParams,
samplingCriterion: this.samplingCriterion,
extremumCriterion: this.extremumCriterion,
amount: this.amount,
amountType: this.amountType,
isOnDistinctValues: this.isOnDistinctValues,
groupByColumn: this.groupByColumn,
}));
}
protected createInputPorts() {
this.inputPorts = [
new SubsetInputPort({
data: {
id: 'in',
node: this,
},
store: this.$store,
}),
new ConstantsInputPort({
data: {
id: 'constants',
node: this,
},
store: this.$store,
}),
];
}
protected update() {
if (!this.checkDataset()) {
return;
}
this.filter();
}
protected filter() {
if (this.column === null) {
this.coverText = 'No column';
this.forwardSubset(this.inputPortMap.in as SubsetInputPort, this.outputPortMap.out);
return;
}
this.coverText = '';
let pkg: SubsetPackage;
if (this.filterType === FilterType.PATTERN) {
pkg = this.filterByPattern();
} else if (this.filterType === FilterType.RANGE) {
pkg = this.filterByRange();
} else if (this.filterType === FilterType.EXTREMUM) {
pkg = this.filterByExtremum();
} else { // FilterType.SAMPLING
pkg = this.filterBySampling();
}
this.updateOutput(pkg);
}
private filterByPattern(): SubsetPackage {
const pkg = (this.inputPortMap.in as SubsetInputPort).getSubsetPackage().clone();
const dataset = this.getDataset();
const mode = this.patternParams.mode;
let patterns = this.inputDisabled ? this.constants.map(value => value.toString()) : this.patternParams.patterns;
if (!this.patternParams.isCaseSensitive && mode !== PatternMatchMode.REGEX) {
patterns = patterns.map(pattern => pattern.toLowerCase());
}
pkg.filterItems(item => {
let value = dataset.getCell(item, this.column as number).toString();
if (!this.patternParams.isCaseSensitive && mode !== PatternMatchMode.REGEX) {
value = value.toLowerCase();
}
if (mode === PatternMatchMode.FULL_STRING) {
if (patterns.indexOf(value) !== -1) {
return true;
}
} else if (mode === PatternMatchMode.SUBSTRING) {
for (const pattern of patterns) {
if (value.indexOf(pattern) !== -1) {
return true;
}
}
} else { // PatternMatchMode.REGEX
for (const pattern of patterns) {
const regex = new RegExp(pattern);
if (value.match(regex) !== null) {
return true;
}
}
}
return false;
});
return pkg;
}
private filterByRange(): SubsetPackage {
const pkg = (this.inputPortMap.in as SubsetInputPort).getSubsetPackage().clone();
const dataset = this.getDataset();
const min = this.inputDisabled ? (this.firstConstant || null) : this.rangeParams.min;
const max = this.inputDisabled ? (this.secondConstant || null) : this.rangeParams.max;
pkg.filterItems(item => {
const value = dataset.getCell(item, this.column as number);
if (min !== null && !(min <= value)) {
return false;
}
if (max !== null && !(value <= max)) {
return false;
}
return true;
});
return pkg;
}
private filterByExtremum(): SubsetPackage {
if (this.isOnDistinctValues) {
return this.extremumOnDistinctValues();
} else {
return this.extremumOnDataItems();
}
}
private extremumOnDataItems(): SubsetPackage {
const pkg = (this.inputPortMap.in as SubsetInputPort).getSubsetPackage().clone();
const dataset = this.getDataset();
const itemGroups = pkg.groupItems(this.groupByColumn);
pkg.clearItems();
const amount = +((this.inputDisabled ? this.firstConstant : this.amount) || 0);
for (const group of itemGroups) {
const groupWithValues = group.map(itemIndex => ({
index: itemIndex,
value: dataset.getCell(itemIndex, this.column as number),
}));
const sortedItems = _.sortBy(groupWithValues, 'value').map(pair => pair.index);
let count = this.amountType === AmountType.COUNT ?
amount : Math.ceil(amount / 100 * sortedItems.length);
if (count > sortedItems.length) {
count = sortedItems.length;
}
if (this.extremumCriterion === ExtremumCriterion.MAXIMUM) {
sortedItems.reverse();
}
const acceptedItems = sortedItems.slice(0, count);
pkg.addItemIndices(acceptedItems);
}
return pkg;
}
private extremumOnDistinctValues(): SubsetPackage {
const pkg = (this.inputPortMap.in as SubsetInputPort).getSubsetPackage().clone();
const dataset = this.getDataset();
const itemGroups = pkg.groupItems(this.groupByColumn);
pkg.clearItems();
const amount = +((this.inputDisabled ? this.firstConstant : this.amount) || 0);
for (const group of itemGroups) {
const columnValues: Array<number | string | null> = dataset.getDomainValues(this.column as number, group, true);
let count = this.amountType === AmountType.COUNT ?
amount : Math.ceil(amount / 100 * columnValues.length);
if (count > columnValues.length) {
count = columnValues.length;
}
if (this.extremumCriterion === ExtremumCriterion.MAXIMUM) {
columnValues.reverse();
}
const acceptedValues: Array<number | string | null> = columnValues.slice(0, count);
const acceptedValueSet = new Set(acceptedValues);
for (const itemIndex of group) {
const value = dataset.getCell(itemIndex, this.column as number);
if (acceptedValueSet.has(value)) {
pkg.addItemIndex(itemIndex);
}
}
}
return pkg;
}
private filterBySampling(): SubsetPackage {
if (this.isOnDistinctValues) {
return this.sampleOnDistinctValues();
} else {
return this.sampleOnDataItems();
}
}
private sampleOnDataItems(): SubsetPackage {
const pkg = (this.inputPortMap.in as SubsetInputPort).getSubsetPackage().clone();
const dataset = this.getDataset();
const itemGroups = pkg.groupItems(this.groupByColumn);
pkg.clearItems();
const amount = +((this.inputDisabled ? this.firstConstant : this.amount) || 0);
for (const group of itemGroups) {
const groupWithValues = group.map(itemIndex => ({
index: itemIndex,
value: dataset.getCell(itemIndex, this.column as number),
}));
const sortedItems = _.sortBy(groupWithValues, 'value').map(pair => pair.index);
let count = this.amountType === AmountType.COUNT ?
amount : Math.ceil(amount / 100 * sortedItems.length);
if (count > sortedItems.length) {
count = sortedItems.length;
}
let acceptedItems: number[] = [];
switch (this.samplingCriterion) {
case SamplingCriterion.MAXIMUM:
case SamplingCriterion.MINIMUM:
if (this.samplingCriterion === SamplingCriterion.MAXIMUM) {
sortedItems.reverse();
}
acceptedItems = sortedItems.slice(0, count);
break;
case SamplingCriterion.RANDOM:
acceptedItems = _.shuffle(sortedItems).slice(0, count);
break;
}
pkg.addItemIndices(acceptedItems);
}
return pkg;
}
private sampleOnDistinctValues(): SubsetPackage {
const pkg = (this.inputPortMap.in as SubsetInputPort).getSubsetPackage().clone();
const dataset = this.getDataset();
const itemGroups = pkg.groupItems(this.groupByColumn);
pkg.clearItems();
const amount = +((this.inputDisabled ? this.firstConstant : this.amount) || 0);
for (const group of itemGroups) {
const columnValues: Array<number | string | null> = dataset.getDomainValues(this.column as number, group, true);
let count = this.amountType === AmountType.COUNT ?
amount : Math.ceil(amount / 100 * columnValues.length);
if (count > columnValues.length) {
count = columnValues.length;
}
let acceptedValues: Array<number | string | null> = [];
switch (this.samplingCriterion) {
case SamplingCriterion.MAXIMUM:
case SamplingCriterion.MINIMUM:
if (this.samplingCriterion === SamplingCriterion.MAXIMUM) {
columnValues.reverse();
}
acceptedValues = columnValues.slice(0, count);
break;
case SamplingCriterion.RANDOM:
acceptedValues = _.shuffle(columnValues).slice(0, count);
break;
}
const acceptedValueSet = new Set(acceptedValues);
for (const itemIndex of group) {
const value = dataset.getCell(itemIndex, this.column as number);
if (acceptedValueSet.has(value)) {
pkg.addItemIndex(itemIndex);
}
}
}
return pkg;
}
private onSelectFilterType(type: FilterType, prevType: FilterType) {
this.commitHistory(history.selectFilterTypeEvent(this, type, prevType));
this.setFilterType(type);
}
private onSelectColumn(column: number | null, prevColumn: number | null) {
this.commitHistory(history.selectColumnEvent(this, column, prevColumn));
this.setColumn(column);
}
private onInputPatterns(patterns: string[], prevPatterns: string[]) {
this.commitHistory(history.inputPatternsEvent(this, patterns, prevPatterns));
this.setPatterns(patterns);
}
private onSelectPatternMatchMode(mode: PatternMatchMode, prevMode: PatternMatchMode) {
this.commitHistory(history.selectPatternMatchModeEvent(this, mode, prevMode));
this.setPatternMatchMode(mode);
}
private onTogglePatternCaseSensitive(value: boolean) {
this.commitHistory(history.togglePatternCaseSensitiveEvent(this, value));
this.setPatternCaseSensitive(value);
}
private onInputRangeMin(value: number | null, prevValue: number | null) {
this.commitHistory(history.inputRangeMin(this, value, prevValue));
this.setRangeMin(value);
}
private onInputRangeMax(value: number | null, prevValue: number | null) {
this.commitHistory(history.inputRangeMax(this, value, prevValue));
this.setRangeMax(value);
}
private onSelectExtremumCriterion(criterion: ExtremumCriterion, prevCriterion: ExtremumCriterion) {
this.commitHistory(history.selectExtremumCriterion(this, criterion, prevCriterion));
this.setExtremumCriterion(criterion);
}
private onSelectAmountType(type: AmountType, prevType: AmountType) {
this.commitHistory(history.selectAmountType(this, type, prevType));
this.setAmountType(type);
}
private onInputAmount(amount: number | null, prevAmount: number | null) {
this.commitHistory(history.inputAmount(this, amount, prevAmount));
this.setAmount(amount);
}
private onSelectGroupByColumn(column: number | null, prevColumn: number | null) {
this.commitHistory(history.selectGroupByColumn(this, column, prevColumn));
this.setGroupByColumn(column);
}
private onToggleOnDistinctValues(value: boolean) {
this.commitHistory(history.toggleOnDistinctValues(this, value));
this.setOnDistinctValues(value);
}
} | the_stack |
import { format, parseISO, isValid } from 'date-fns' // eslint-disable-line no-restricted-imports
// Importing 'is' directly from date-fns/locale/is has caused unexpected problems
import { is } from 'date-fns/locale' // eslint-disable-line no-restricted-imports
import {
CaseAppealDecision,
CaseCustodyRestrictions,
CaseGender,
CaseType,
} from '@island.is/judicial-system/types'
const getAsDate = (date: Date | string | undefined | null): Date => {
if (typeof date === 'string' || date instanceof String) {
return parseISO(date as string)
} else {
return date as Date
}
}
export function formatDate(
date: Date | string | undefined,
formatPattern: string,
shortenDayName?: boolean,
): string | undefined {
const theDate: Date = getAsDate(date)
if (isValid(theDate)) {
const formattedDate = format(theDate, formatPattern, {
locale: is,
})
if (shortenDayName) {
return formattedDate.replace('dagur,', 'd.')
} else {
return formattedDate
}
} else {
return undefined
}
}
// Credit: https://dzone.com/articles/capitalize-first-letter-string-javascript
export const capitalize = (text: string): string => {
if (!text) {
return ''
}
return text.charAt(0).toUpperCase() + text.slice(1)
}
export const lowercase = (text?: string): string => {
if (!text) {
return ''
}
return text.charAt(0).toLowerCase() + text.slice(1)
}
export const formatNationalId = (nationalId: string): string => {
if (nationalId?.length === 10) {
return `${nationalId.slice(0, 6)}-${nationalId.slice(6)}`
} else {
return nationalId
}
}
export const laws = {
_95_1_A: 'a-lið 1. mgr. 95. gr.',
_95_1_B: 'b-lið 1. mgr. 95. gr.',
_95_1_C: 'c-lið 1. mgr. 95. gr.',
_95_1_D: 'd-lið 1. mgr. 95. gr.',
_95_2: '2. mgr. 95. gr.',
_99_1_B: 'b-lið 1. mgr. 99. gr.',
_100_1: '1. mgr. 100. gr. sml.',
}
export const caseTypes = {
CUSTODY: 'gæsluvarðhald',
TRAVEL_BAN: 'farbann',
SEARCH_WARRANT: 'húsleit',
BANKING_SECRECY_WAIVER: 'rof bankaleyndar',
PHONE_TAPPING: 'símhlustun',
TELECOMMUNICATIONS: 'upplýsingar um fjarskiptasamskipti',
TRACKING_EQUIPMENT: 'eftirfararbúnaður',
PSYCHIATRIC_EXAMINATION: 'geðrannsókn',
SOUND_RECORDING_EQUIPMENT: 'hljóðupptökubúnaði komið fyrir',
AUTOPSY: 'krufning',
BODY_SEARCH: 'leit og líkamsrannsókn',
INTERNET_USAGE: 'upplýsingar um vefnotkun',
OTHER: 'annað',
}
const getRestrictionByValue = (value: CaseCustodyRestrictions) => {
switch (value) {
case CaseCustodyRestrictions.COMMUNICATION:
return 'D - Bréfskoðun, símabann'
case CaseCustodyRestrictions.ISOLATION:
return 'B - Einangrun'
case CaseCustodyRestrictions.MEDIA:
return 'E - Fjölmiðlabann'
case CaseCustodyRestrictions.VISITAION:
return 'C - Heimsóknarbann'
case CaseCustodyRestrictions.ALTERNATIVE_TRAVEL_BAN_REQUIRE_NOTIFICATION:
return 'Tilkynningaskylda'
case CaseCustodyRestrictions.ALTERNATIVE_TRAVEL_BAN_CONFISCATE_PASSPORT:
return 'Afhending vegabréfs'
}
}
export const getShortRestrictionByValue = (value: CaseCustodyRestrictions) => {
switch (value) {
case CaseCustodyRestrictions.COMMUNICATION:
return 'Bréfskoðun, símabann'
case CaseCustodyRestrictions.ISOLATION:
return 'Einangrun'
case CaseCustodyRestrictions.MEDIA:
return 'Fjölmiðlabann'
case CaseCustodyRestrictions.VISITAION:
return 'Heimsóknarbann'
case CaseCustodyRestrictions.ALTERNATIVE_TRAVEL_BAN_REQUIRE_NOTIFICATION:
return 'Tilkynningarskylda'
case CaseCustodyRestrictions.ALTERNATIVE_TRAVEL_BAN_CONFISCATE_PASSPORT:
return 'Afhending vegabréfs'
}
}
export enum NounCases {
NOMINATIVE, // Nefnifall
ACCUSATIVE, // Þolfall
DATIVE, // Þágufall
GENITIVE, // Eignarfall
}
export function formatAccusedByGender(
accusedGender?: CaseGender,
nounCase: NounCases = NounCases.NOMINATIVE,
isInvestigationCase?: boolean,
) {
if (isInvestigationCase) {
return nounCase === NounCases.NOMINATIVE ? 'varnaraðili' : 'varnaraðila'
} else {
switch (accusedGender) {
case CaseGender.MALE:
return nounCase === NounCases.NOMINATIVE ? 'kærði' : 'kærða'
case CaseGender.FEMALE:
return nounCase === NounCases.NOMINATIVE ? 'kærða' : 'kærðu'
case CaseGender.OTHER:
default:
return 'kærða'
}
}
}
// Formats the restrictions set by the judge
// Note that only the predetermined list of restrictions is relevant here
export function formatCustodyRestrictions(
accusedGender?: CaseGender,
custodyRestrictions?: CaseCustodyRestrictions[],
): string {
const relevantCustodyRestrictions = custodyRestrictions
?.filter((restriction) =>
[
CaseCustodyRestrictions.VISITAION,
CaseCustodyRestrictions.COMMUNICATION,
CaseCustodyRestrictions.MEDIA,
].includes(restriction),
)
.sort()
if (
!(relevantCustodyRestrictions && relevantCustodyRestrictions.length > 0)
) {
return ''
}
const filteredCustodyRestrictionsAsString = relevantCustodyRestrictions.reduce(
(res, custodyRestriction, index) => {
const isNextLast = index === relevantCustodyRestrictions.length - 2
const isLast = index === relevantCustodyRestrictions.length - 1
const isOnly = relevantCustodyRestrictions.length === 1
return (res +=
custodyRestriction === CaseCustodyRestrictions.COMMUNICATION
? `bréfaskoðun og símabanni${
isLast ? ' ' : isNextLast && !isOnly ? ' og ' : ', '
}`
: custodyRestriction === CaseCustodyRestrictions.MEDIA
? `fjölmiðlabanni${
isLast ? ' ' : isNextLast && !isOnly ? ' og ' : ', '
}`
: custodyRestriction === CaseCustodyRestrictions.VISITAION
? `heimsóknarbanni${
isLast ? ' ' : isNextLast && !isOnly ? ' og ' : ', '
}`
: '')
},
'',
)
return `Sækjandi tekur fram að gæsluvarðhaldið verði með ${filteredCustodyRestrictionsAsString}skv. 99. gr. laga nr. 88/2008.`
}
// Fromats the restrictions set by the judge when choosing alternative travle ban
export const formatAlternativeTravelBanRestrictions = (
accusedGender?: CaseGender,
custodyRestrictions?: CaseCustodyRestrictions[],
otherRestrictions?: string,
): string => {
const relevantCustodyRestrictions = custodyRestrictions?.filter(
(restriction) =>
[
CaseCustodyRestrictions.ALTERNATIVE_TRAVEL_BAN_REQUIRE_NOTIFICATION,
CaseCustodyRestrictions.ALTERNATIVE_TRAVEL_BAN_CONFISCATE_PASSPORT,
].includes(restriction),
)
const hasTravelBanRestrictions =
relevantCustodyRestrictions && relevantCustodyRestrictions?.length > 0
const hasOtherRestrictions = otherRestrictions && otherRestrictions.length > 0
// No restrictions
if (!hasTravelBanRestrictions && !hasOtherRestrictions) {
return ''
}
const accusedGenderText = formatAccusedByGender(
accusedGender,
NounCases.DATIVE,
)
const travelBanRestrictionsText = hasTravelBanRestrictions
? `Sækjandi tekur fram að farbannið verði með takmörkunum.${
relevantCustodyRestrictions?.includes(
CaseCustodyRestrictions.ALTERNATIVE_TRAVEL_BAN_REQUIRE_NOTIFICATION,
)
? ` Að ${accusedGenderText} verði gert að tilkynna sig.`
: ''
}${
relevantCustodyRestrictions?.includes(
CaseCustodyRestrictions.ALTERNATIVE_TRAVEL_BAN_CONFISCATE_PASSPORT,
)
? ` Að ${accusedGenderText} verði gert að afhenda vegabréfið sitt.`
: ''
}`
: ''
const paragraphBreak =
hasTravelBanRestrictions && hasOtherRestrictions ? '\n' : ''
const otherRestrictionsText = hasOtherRestrictions ? otherRestrictions : ''
return `${travelBanRestrictionsText}${paragraphBreak}${otherRestrictionsText}`
}
// Formats the requested restrictions from the prosecutor
export const formatRequestedCustodyRestrictions = (
type: CaseType,
requestedCustodyRestrictions?: CaseCustodyRestrictions[],
requestedOtherRestrictions?: string,
) => {
const hasRequestedCustodyRestrictions =
requestedCustodyRestrictions && requestedCustodyRestrictions?.length > 0
const hasRequestedOtherRestrictions =
requestedOtherRestrictions && requestedOtherRestrictions?.length > 0
// No restrictions
if (!hasRequestedCustodyRestrictions && !hasRequestedOtherRestrictions) {
return `Ekki er farið fram á takmarkanir á ${
type === CaseType.CUSTODY ? 'gæslu' : 'farbanni'
}.`
}
const requestedCustodyRestrictionsText = hasRequestedCustodyRestrictions
? requestedCustodyRestrictions &&
requestedCustodyRestrictions.reduce(
(acc, restriction, index) =>
`${acc}${index > 0 ? '\n' : ''}${getRestrictionByValue(restriction)}`,
'',
)
: ''
const paragraphBreak =
hasRequestedCustodyRestrictions && hasRequestedOtherRestrictions ? '\n' : ''
const requestedOtherRestrictionsText = hasRequestedOtherRestrictions
? requestedOtherRestrictions
: ''
return `${requestedCustodyRestrictionsText}${paragraphBreak}${requestedOtherRestrictionsText}`
}
export function formatGender(gender?: CaseGender): string {
switch (gender) {
case CaseGender.MALE:
return 'Karl'
case CaseGender.FEMALE:
return 'Kona'
case CaseGender.OTHER:
default:
return 'Kynsegin/Annað'
}
}
export function formatGenderPronouns(gender?: CaseGender): string {
switch (gender) {
case CaseGender.MALE:
return 'hann'
case CaseGender.FEMALE:
return 'hún'
case CaseGender.OTHER:
default:
return 'hán'
}
}
export function formatAppeal(
appealDecision: CaseAppealDecision | undefined,
stakeholder: string,
stakeholderGender: CaseGender = CaseGender.MALE,
): string {
const stakeholderGenderText = formatGenderPronouns(stakeholderGender)
switch (appealDecision) {
case CaseAppealDecision.APPEAL:
return `${stakeholder} lýsir því yfir að ${stakeholderGenderText} kæri úrskurðinn til Landsréttar.`
case CaseAppealDecision.ACCEPT:
return `${stakeholder} unir úrskurðinum.`
case CaseAppealDecision.POSTPONE:
return `${stakeholder} lýsir því yfir að ${stakeholderGenderText} taki sér lögbundinn kærufrest.`
default:
return ''
}
} | the_stack |
import {Watcher, Program, RawMap, RawValue, RawEAV, forwardDiffs, appendAsEAVs, createId} from "../watchers/watcher";
import {CompilerWatcher} from "../watchers/compiler";
class EditorWatcher extends Watcher {
editor: Program;
setup() {
this.editor = this.createEditor();
let {editor, program} = this;
editor
.bind("Draw the root editor view.", ({find, record}) => {
let editor = find("editor/root");
return [
record("editor/view", "ui/row", {editor}).add("children", [
record("editor/nav", "ui/column", {editor, sort: 0}),
record("editor/main", "ui/column", {editor, sort: 1}).add("children", [
record("ui/row", {editor, sort: 0, class: "editor-block-header"}).add("children", [
record("editor/block/description", "ui/column", {editor}),
record("editor/block/storyboard", "ui/row", {editor})
]),
record("ui/row", "editor/block/content", {editor, sort: 1})
])
])
];
})
.bind("Attach the current frame type to the editor content window.", ({find}) => {
let editor = find("editor/root");
let {active_frame} = editor;
let content = find("editor/block/content", {editor});
return [content.add("type", active_frame.type)];
})
.bind("A block's next node sort is it's max node sort + 1 (or 1).", ({find, choose, gather}) => {
let block = find("block");
// @NOTE: We can only reliably use an aggregate in a choose if the choose inputs are *only* used in the aggregate grouping.
let [sort] = choose(() => {
let {node} = block;
1 == gather(node.sort, node).per(block).sort("down");
return node.sort + 1;
}, () => 1);
return [block.add("next_node_sort", sort)];
})
.bind("A node is another node's parent if it has an AV who's V is the other node's entity", ({find}) => {
let parent = find("node");
let node = find("node");
node != parent;
let {attribute} = parent;
attribute.value == node.entity;
return [node.add({parent, parent_field: attribute.attribute})];
})
.bind("Mark nodes without parents as root nodes.", ({find, not}) => {
let node = find("node");
not(() => node.parent);
return [node.add("tag", "root-node")];
})
.commit("A node with no entity creates one.", ({find, not, record}) => {
let node = find("node");
not(() => node.entity);
return [node.add("entity", record("entity", {node, sort: node.sort}))];
})
.commit("If a node's attribute is a record and it's not already a subnode, fix that.", ({find, not, record}) => {
let editor = find("editor/root");
let {active_block} = editor;
let {node} = active_block;
let {attribute} = node;
find("editor/existing-node-attribute", {node, text: attribute.attribute, is_record: "true"});
not(() => attribute.value == find("node").entity);
let sort = active_block.next_node_sort;
let subnode;
return [
active_block.add("node", [
subnode = record("node", "derived-subnode", {sort, entity: record("entity", {sort, _node: node, _attr: attribute.attribute})})
]),
attribute.remove("value").add("value", subnode.entity)
];
})
.commit("A node is only derived once.", ({find, record}) => {
let node = find("node", "derived-subnode");
return [node.remove("tag", "derived-subnode")];
})
.commit("Deriving a subnode closes it's parent and opens it.", ({find, record}) => {
let node = find("node", "derived-subnode");
let tree_node = find("editor/node-tree/node", {node});
let parent_tree_node = find("editor/node-tree/node", {node: node.parent});
parent_tree_node.open;
return [
tree_node.add("open", "true"),
parent_tree_node.remove("open")
];
})
.commit("A node with an empty value has no value at all.", ({find}) => {
let node = find("node");
let {attribute} = node;
attribute.value == "";
return [attribute.remove("value", "")];
})
.bind("A node's name is it's parent_field if it has one, or it's tag attribute.", ({find, choose}) => {
let node = find("node");
let [name] = choose(
() => node.parent_field,
() => {
let {attribute} = node;
attribute.attribute == "tag";
return attribute.value;
},
() => "???"
);
return [node.add("name", name)]
})
.bind("A node's label is the uppercased first character of it's name.", ({find, lib:{string}}) => {
let node = find("node");
let {name} = node;
let label = string.uppercase(string.get(name, 1));
return [node.add("label", label)];
})
.bind("A node's color is derived from it's sort.", ({find, lib:{math}}) => {
let node = find("node");
let {color} = find("node-color", {sort: math.mod(node.sort - 1, 5) + 1})
return [node.add("color", color)];
})
// this.navigation();
this.header();
this.nodeTree();
this.queryEditor();
this.moleculeGenerator();
this.moleculeLayout();
this.infobox();
this.completionGenerator();
this.fixtures();
this.initEditor();
}
initEditor() {
const EDITOR_ID = createId();
const STYLE_ID = createId();
const TAG_MARINA_ID = createId();
const TAG_MARINARA_ID = createId();
const BLOCK_PPL_W_BOATS_ID = createId();
const BLOCK_BOAT_TYPES_ID = createId();
const FRAME_PPL_W_BOATS_QUERY_ID = createId();
let fixture:RawEAV[] = [
[EDITOR_ID, "tag", "editor/root"],
[STYLE_ID, "tag", "html/element"],
[STYLE_ID, "tagname", "link"],
[STYLE_ID, "rel", "stylesheet"],
[STYLE_ID, "href", "/assets/css/editor.css"],
["|init", "tag", "editor/init"]
];
// @NOTE: To get successive layers, multiply offsets by magnitude = ceil(mod(ix - 2, 6) + 2) and connect the dots
// @NOTE: Take special care about the 0,0, in ix: 1.
appendAsEAVs(fixture, {tag: "spiral", row: 1, sort: 1, x: 0, y: 0});
appendAsEAVs(fixture, {tag: "spiral", row: 1, sort: 2, x: 1, y: 0});
appendAsEAVs(fixture, {tag: "spiral", row: 1, sort: 3, x: 1, y: 1});
appendAsEAVs(fixture, {tag: "spiral", row: 1, sort: 4, x: 0, y: 1});
appendAsEAVs(fixture, {tag: "spiral", row: 1, sort: 5, x: -1, y: 0});
appendAsEAVs(fixture, {tag: "spiral", row: 1, sort: 6, x: 0, y: -1});
appendAsEAVs(fixture, {tag: "spiral", row: 1, sort: 7, x: 1, y: -1});
appendAsEAVs(fixture, {tag: "spiral", row: 8, sort: 8, x: 2, y: -1});
appendAsEAVs(fixture, {tag: "spiral", row: 0, sort: 1, x: 0, y: 0});
appendAsEAVs(fixture, {tag: "spiral", row: 0, sort: 2, x: 1, y: 0});
appendAsEAVs(fixture, {tag: "spiral", row: 0, sort: 3, x: 0, y: 1});
appendAsEAVs(fixture, {tag: "spiral", row: 0, sort: 4, x: -1, y: 1});
appendAsEAVs(fixture, {tag: "spiral", row: 0, sort: 5, x: -1, y: 0});
appendAsEAVs(fixture, {tag: "spiral", row: 0, sort: 6, x: -1, y: -1});
appendAsEAVs(fixture, {tag: "spiral", row: 0, sort: 7, x: 0, y: -1});
appendAsEAVs(fixture, {tag: "spiral", row: 0, sort: 8, x: 1, y: -1});
appendAsEAVs(fixture, {tag: "node-color", sort: 1, color: "#9926ea"});
appendAsEAVs(fixture, {tag: "node-color", sort: 2, color: "#6c86ff"});
appendAsEAVs(fixture, {tag: "node-color", sort: 3, color: "red"});
appendAsEAVs(fixture, {tag: "node-color", sort: 4, color: "orange"});
appendAsEAVs(fixture, {tag: "node-color", sort: 5, color: "green"});
appendAsEAVs(fixture, {tag: "node-color", sort: 6, color: "indigo"});
this.editor.inputEAVs(fixture);
}
fixtures() {
this.editor
.commit("When the init tag is added, preload the system with sample data.", ({find, record}) => {
let init = find("editor/init");
let editor = find("editor/root");
let block1, frame1, person_node, boat_node, dock_node;
return [
editor.add("block", [
block1 = record("block", {sort: 1}).add({
nav_tag: record("nav/tag", {name: "Marina"}),
name: "People with boats",
description: "Add a description...",
storyboard: [
frame1 = record("frame", {type: "query", sort: 1}),
record("frame", {type: "output", sort: 2}),
],
node: [
// dock_node = record("node", {sort: 3, entity: record("entity", {z: 1})}).add("attribute", [
// record({attribute: "state", z: 11})
// ]),
// boat_node = record("node", {sort: 2, entity: record("entity", {z: 2})}).add("attribute", [
// record({attribute: "type", value: "yacht", z:21}),
// record({attribute: "name", z:22}),
// record({attribute: "dock", value: dock_node.entity, z:23})
// ]),
// person_node = record("node", {sort: 1, entity: record("entity", {z: 3})}).add("attribute", [
// record({attribute: "tag", value: "person", z:31}),
// // record({attribute: "tag"}),
// record({attribute: "age", z:32}),
// record({attribute: "boat", value: boat_node.entity, z:33})
// ]),
]
})
]),
record("node", {sort: 0}), // Magic node. Do not remove. (Workaround sort bug)
editor.add({active_block: block1, active_frame: frame1}),
init.remove()
];
})
.commit("DEBUG: Add a spiral range to iterate over when expanding the spiral.", ({find, record}) => {
find("editor/root");
return [
record("spiral-range", {ix: 9}),
record("spiral-range", {ix: 10}),
record("spiral-range", {ix: 11}),
record("spiral-range", {ix: 12}),
record("spiral-range", {ix: 13}),
record("spiral-range", {ix: 14}),
record("spiral-range", {ix: 15}),
record("spiral-range", {ix: 16}),
record("range", {ix: 1}),
record("range", {ix: 2}),
record("range", {ix: 3}),
record("range", {ix: 4}),
record("range", {ix: 5}),
record("range", {ix: 6}),
record("range", {ix: 7}),
record("range", {ix: 8}),
record("range", {ix: 8}),
record("range", {ix: 9}),
record("range", {ix: 10}),
record("range", {ix: 11}),
record("range", {ix: 12}),
record("range", {ix: 13}),
record("range", {ix: 14}),
record("range", {ix: 15}),
record("range", {ix: 16}),
];
})
}
createEditor() {
let editor = new Program("Editor");
editor.attach("compiler");
editor.attach("ui");
editor.attach("shape");
let compiler = editor.attach("compiler") as CompilerWatcher;
compiler.injectInto(this.program);
compiler.registerWatcherFunction("send-to-editor", forwardDiffs(editor, "send-to-editor"));
return editor;
}
//--------------------------------------------------------------------
// Navigation
//--------------------------------------------------------------------
navigation() {
this.editor
.bind("Populate the nav bar with the program's block tags.", ({find, record}) => {
let nav = find("editor/nav");
let tag = nav.editor.block.nav_tag;
return [
nav.add("children", [
record("editor/nav/tag", "ui/column", {editor: nav.editor, sort: tag.name, nav_tag: tag}).add("children", [
record("ui/text", {sort: 0, text: tag.name})
])
])
];
})
.bind("Populate nav tags with the blocks that have them.", ({find, choose, record}) => {
let tag = find("editor/nav/tag");
let block = tag.editor.block;
block.nav_tag == tag.nav_tag;
let [name] = choose(() => block.name, () => "Untitled Block");
return [
tag.add("children", [
record("editor/nav/block", "ui/text", {editor: tag.editor, nav_tag: tag.nav_tag, block, text: name, sort: name})
])
];
});
}
//--------------------------------------------------------------------
// Header
//--------------------------------------------------------------------
header() {
this.editor
.bind("Populate the block description for the active block.", ({find, choose, record}) => {
let description = find("editor/block/description");
let active_block = description.editor.active_block;
let [name] = choose(() => active_block.name, () => "Untitled Block");
let [text] = choose(() => active_block.description, () => "");
return [
description.add("children", [
record("ui/text", {sort: 0, text: name, class: "editor-block-title"}),
record("ui/text", {sort: 1, text})
])
];
})
.bind("Populate the block storyboard for the active block.", ({find, record}) => {
let storyboard = find("editor/block/storyboard");
let {editor} = storyboard;
let {active_block} = editor;
let frame = active_block.storyboard;
return [
storyboard.add("children", [
record("editor/block/frame", "ui/column", {editor, sort: frame.sort, frame}).add("children", [
record("ui/text", {text: frame.type})
])
])
];
})
.bind("Mark the active frame.", ({find}) => {
let editor = find("editor/root");
let {active_frame:frame} = editor;
let frame_elem = find("editor/block/frame", {frame});
return [frame_elem.add("class", "active")];
})
.commit("Clicking a frame activates it.", ({find}) => {
let frame_elem = find("editor/block/frame");
find("html/event/click", {element: frame_elem});
let {frame, editor} = frame_elem;
return [editor.remove("active_frame").add("active_frame", frame)];
})
.bind("Add new frame button to the storyboard.", ({find, record}) => {
let storyboard = find("editor/block/storyboard");
let {editor} = storyboard;
let {active_block} = editor;
return [
storyboard.add("children", [
record("editor/new-frame", "editor/block/frame", "ui/column", {editor, sort: Infinity})
])
];
})
.commit("Clicking the new frame button opens it.", ({find}) => {
let new_frame = find("editor/new-frame");
find("html/event/click", "html/direct-target", {element: new_frame});
return [
new_frame.add("open", "true")
];
})
.bind("When the new frame is open, display a list of editor types to choose from.", ({find, record}) => {
let new_frame = find("editor/new-frame", {open: "true"});
let {editor} = new_frame;
return [
new_frame.add("children", [
record("editor/new-frame/type", "ui/button", {editor, text: "Query", type: "query", class: "flat"}),
record("editor/new-frame/type", "ui/button", {editor, text: "Output", type: "output", class: "flat"}),
])
];
})
.commit("Clicking a new frame type adds a frame of that type and closes the new frame button.", ({find, gather, choose, record}) => {
let new_frame_type = find("editor/new-frame/type");
find("html/event/click", "html/direct-target", {element: new_frame_type});
let {type, editor} = new_frame_type;
let new_frame = find("editor/new-frame", {editor});
let {active_block:block} = editor;
let [ix] = choose(() => gather(block.storyboard).per(block).count() + 1, () => 1);
return [
new_frame.remove("open"),
block.add("storyboard", [
record("frame", {block, type, sort: ix})
])
];
});
}
//--------------------------------------------------------------------
// Node Tree
//--------------------------------------------------------------------
nodeTree() {
this.editor
.bind("Decorate the node tree as a column.", ({find, record}) => {
let tree = find("editor/node-tree");
let side = 21, lineWidth = 1, strokeStyle = "#AAA";
return [tree.add({tag: "ui/column"}).add("children", [
record("editor/node-tree/node", "editor/node-tree/node/new", "ui/row", {sort: Infinity, tree}).add("children", [
record("editor/node-tree/node/hex", "shape/hexagon", {
sort: 0, tree, side, lineWidth, strokeStyle
}).add("content", [
record("ui/button", {icon: "android-add"})
])
])
])];
})
.bind("When the new node is open, it has an input for specifying the tag.", ({find, record}) => {
let new_node = find("editor/node-tree/node/new", {open: "true"});
return [
new_node.add("children", [
record("editor/node-tree/node/new/tag", "ui/autocomplete", "html/trigger-focus", {sort: 2, new_node, placeholder: "tag..."})
])
];
})
.bind("Each root node is an element in the tree.", ({find, record}) => {
let tree = find("editor/node-tree");
let {node} = tree;
node.tag == "root-node";
return [
tree.add("children", [
record("editor/node-tree/node", {tree, node, sort: node.sort})
])
];
})
.bind("A node consists of a hex, and a pattern.", ({find, record}) => {
let tree_node = find("editor/node-tree/node");
let {tree, node} = tree_node;
let {color, label} = node;
let side = 21, lineWidth = 1, strokeStyle = "#AAA";
return [
tree_node.add({tag: "ui/row"}).add("children", [
record("editor/node-tree/node/hex", "shape/hexagon", {sort: 0, tree_node, side, lineWidth, strokeStyle}).add("content", [
record("ui/text", {text: label, style: record({color})})
]),
record("editor/node-tree/node/pattern", {sort: 1, tree_node})
])
];
})
.bind("A node pattern is a column of fields on the node.", ({find, record}) => {
let node_pattern = find("editor/node-tree/node/pattern");
let {tree_node} = node_pattern;
let {name} = tree_node.node;
return [
node_pattern.add({tag: "ui/column"}).add("children", [
record("ui/row", {sort: 0, node_pattern}).add("children", [
record("editor/node-tree/node/pattern/name", "ui/text", {tree_node, text: name})
])
])
];
})
.bind("If a node has attributes, display them in it's pattern.", ({find, not, choose, record}) => {
let node_pattern = find("editor/node-tree/node/pattern");
let {tree_node} = node_pattern;
let {node} = tree_node;
let {attribute} = node;
not(() => {attribute.attribute == "tag"; attribute.value == node.name});
not(() => attribute.value == find("entity"));
let [sort] = choose(() => `z${attribute.sort}`, () => attribute.attribute, () => 999);
return [
node_pattern.add("children", [
record("editor/node-tree/fields", "ui/column", {sort: 1, tree_node, attribute}).add("children", [
record("editor/node-tree/node/pattern/field", "ui/row", {sort, tree_node, attribute})
])
])
];
})
.bind("A node displays attributes as text", ({find, record}) => {
let pattern_field = find("editor/node-tree/node/pattern/field");
let {tree_node, attribute} = pattern_field;
let field = attribute.attribute;
return [
pattern_field.add("children", [
record("ui/text", {sort: 1, text: field})
])
];
})
.bind("If a node's attribute has a value, display them in it's field.", ({find, not, record}) => {
let field = find("editor/node-tree/node/pattern/field");
let {tree_node, attribute} = field;
let {node} = tree_node;
not(() => field.open);
not(() => {attribute.attribute == "tag"; attribute.value == node.name});
return [
field.add("children", [
record("editor/node-tree/node/pattern/value", "ui/text", {sort: 2, tree_node, text: attribute.value})
])
];
})
.bind("An open field has a value cell even if it's attribute lacks one.", ({find, choose, record}) => {
let field = find("editor/node-tree/node/pattern/field", {open: "true"});
let {tree_node, attribute} = field;
let [value] = choose(() => attribute.value, () => "");
return [
field.add("children", [
record("editor/node-tree/node/pattern/value", "ui/input", "html/trigger-focus", "html/autosize-input", {sort: 2, tree_node, attribute, initial: value})
])
];
})
.bind("An open node displays controls beneath itself.", ({find, record}) => {
let tree_node = find("editor/node-tree/node", {open: "true"});
let hex = find("editor/node-tree/node/hex", {tree_node});
return [
hex.add("children", [
record("editor/node-tree/node/controls", "ui/row", {tree_node}).add("children", [
//record("editor/node-tree/node/add-field", "ui/button", {sort: 1, tree_node, icon: "android-add"}),
record("editor/node-tree/node/delete", "ui/button", {sort: 2, tree_node, icon: "android-close"})
])
])
];
})
.bind("An open node displays delete buttons on its fields.", ({find, choose, record}) => {
let field = find("editor/node-tree/node/pattern/field");
let {tree_node, attribute} = field;
tree_node.open;
return [
field.add("children", [
record("editor/node-tree/node/field/delete", "ui/button", {sort: 0, tree_node, attribute, icon: "android-close"})
])
];
})
.bind("An open node displays a plus field button in its pattern.", ({find, record}) => {
let tree_node = find("editor/node-tree/node", {open: "true"});
let node_pattern = find("editor/node-tree/node/pattern", {tree_node});
return [
node_pattern.add("children", [
record("ui/column", {sort: 2, node_pattern, class: "editor-node-tree-new-field"}).add("children", [
record("editor/node-tree/node/pattern/new-field", "ui/row", {tree_node}).add("children", [
record("editor/node-tree/node/field/new", "ui/button", {sort: 1, tree_node, icon: "android-add"}),
record("editor/node-tree/node/field/new/attribute", "ui/autocomplete", {sort: 2, tree_node, placeholder: "field..."}),
])
])
])
];
})
.bind("Non root nodes are children of their parent's pattern.", ({find, record}) => {
let node = find("node");
let {parent} = node;
let tree_node = find("editor/node-tree/node", {node: parent});
let node_pattern = find("editor/node-tree/node/pattern", {tree_node});
let {tree} = tree_node;
tree.node == node;
return [
node_pattern.add("children", [
record("ui/column", {sort: 3, node_pattern: node_pattern, class: "editor-node-tree-subnodes"}).add("children", [
record("editor/node-tree/node", {tree, node, sort: node.sort})
])
])
];
})
.bind("Fill tag completions.", ({find, record}) => {
let new_tag = find("editor/node-tree/node/new/tag");
let completion = find("editor/existing-tag");
return [new_tag.add("completion", completion)];
})
.bind("Fill attribute completions.", ({find, record}) => {
let new_attribute = find("editor/node-tree/node/field/new/attribute");
let {tree_node} = new_attribute;
let completion = find("editor/existing-node-attribute", {node: tree_node.node});
return [new_attribute.add("completion", completion)];
})
.bind("An open tree node require completions.", ({find}) => {
let tree_node = find("editor/node-tree/node", {open: "true"});
let {node} = tree_node;
return [node.add("completing", "true")];
})
//--------------------------------------------------------------------
// Node Tree Interaction
//--------------------------------------------------------------------
this.editor
.commit("Clicking a node's hex opens it.", ({find, not}) => {
let hex = find("editor/node-tree/node/hex");
find("html/event/click", {element: hex});
let {tree_node} = hex;
not(() => tree_node.open);
return [tree_node.add("open", "true")];
})
.commit("Clicking a node's name opens it.", ({find, not}) => {
let name_elem = find("editor/node-tree/node/pattern/name");
find("html/event/click", {element: name_elem});
let {tree_node} = name_elem;
not(() => tree_node.open);
return [tree_node.add("open", "true")];
})
.commit("Clicking an open node's hex closes it.", ({find}) => {
let hex = find("editor/node-tree/node/hex");
find("html/event/click", {element: hex});
let {tree_node} = hex;
tree_node.open;
return [tree_node.remove("open")];
})
.commit("Clicking outside an open tree node closes it.", ({find, not}) => {
let tree_node = find("editor/node-tree/node", {open: "true"});
find("html/event/click");
not(() => find("html/event/click", {element: tree_node}));
return [tree_node.remove("open")];
})
.commit("Clicking inside a child node of an open tree node closes it.", ({find}) => {
let tree_node = find("editor/node-tree/node", {open: "true"});
let child_node = find("editor/node-tree/node");
child_node.node.parent == tree_node.node;
find("html/event/click", {element: child_node});
return [tree_node.remove("open")];
})
.bind("Clicking the delete node button removes its node from the block.", ({find, record}) => {
let delete_node = find("editor/node-tree/node/delete");
find("html/event/click", {element: delete_node})
let {tree_node} = delete_node;
let {node} = tree_node;
return [record("editor/event/delete-node", {node})];
})
.bind("Deleting a node deletes its children.", ({find, choose, gather, record}) => {
let {node:parent} = find("editor/event/delete-node");
let node = find("node", {parent});
return [record("editor/event/delete-node", {node})];
})
.commit("Deleting a node nukes it and removes it from it's blocks.", ({find, choose, gather, record}) => {
let {node} = find("editor/event/delete-node");
let {block} = find("editor/root");
return [
block.remove("node", node),
node.remove()
];
})
.commit("Deleting a node removes it from its parent.", ({find, choose, gather, record}) => {
let {node:child} = find("editor/event/delete-node");
let node = find("node");
let {attribute} = node;
attribute.value == child.entity;
return [
node.remove("attribute", attribute),
//attribute.remove()
];
})
.commit("Clicking the new node button opens it.", ({find, not, record}) => {
let new_node = find("editor/node-tree/node/new");
not(() => new_node.open);
find("html/event/click", {element: new_node})
return [new_node.add("open", "true")];
})
.commit("Clicking outside an open new node closes it.", ({find, not, record}) => {
let new_node = find("editor/node-tree/node/new", {open: "true"});
find("html/event/click");
not(() => find("html/event/click", {element: new_node}));
return [new_node.remove("open")];
})
.bind("Clicking the new node save button saves it.", ({find, not, record}) => {
let save_new = find("editor/node-tree/node/new/save");
find("html/event/click", {element: save_new});
let {new_node} = save_new;
return [record("editor/event/save-node", {new_node})];
})
.bind("selecting a tag in the new node autocomplete saves it.", ({find, not, record}) => {
let tag_autocomplete = find("editor/node-tree/node/new/tag");
let {new_node, selected} = tag_autocomplete;
return [record("editor/event/save-node", {new_node})];
})
.commit("Saving a new node commits, resets, and closes it.", ({find, not, record}) => {
let {new_node} = find("editor/event/save-node");
let tag_autocomplete = find("editor/node-tree/node/new/tag");
let {value} = tag_autocomplete;
let tag_input = find("ui/autocomplete/input", {autocomplete: tag_autocomplete});
value != "";
let {tree} = new_node;
let {active_block} = tree.editor;
let sort = active_block.next_node_sort;
return [
active_block.add("node", [
record("node", {sort, attribute: record({sort, attribute: "tag", value})})
]),
new_node.remove("open"),
tag_input.remove("value")
];
})
.commit("Clicking a field opens it.", ({find, not}) => {
let field = find("editor/node-tree/node/pattern/field");
find("html/event/click", {element: field});
not(() => field.open);
return [field.add("open", "true")];
})
.commit("Clicking outside an open field closes it.", ({find, not}) => {
let field = find("editor/node-tree/node/pattern/field", {open: "true"});
find("html/event/click");
not(() => find("html/event/click", {element: field}));
return [field.remove("open")];
})
.commit("Clicking the new field save button focuses it's autocomplete.", ({find}) => {
let add_field = find("editor/node-tree/node/field/new");
let {tree_node} = add_field;
let event = find("html/event/click", {element: add_field})
let field_autocomplete = find("editor/node-tree/node/field/new/attribute", {tree_node});
return [field_autocomplete.add("tag", "html/trigger-focus")];
})
.bind("Clicking the new field save button saves it.", ({find, record}) => {
let add_field = find("editor/node-tree/node/field/new");
let event = find("html/event/click", {element: add_field})
let {tree_node} = add_field;
let field_autocomplete = find("editor/node-tree/node/field/new/attribute", {tree_node});
field_autocomplete.value != "";
return [
record("editor/event/save-field", {node: tree_node.node, attribute: field_autocomplete.value}),
record("ui/event/clear", {autocomplete: field_autocomplete})
];
})
.bind("Selecting a completion in the new field autocomplete saves it.", ({find, not, record}) => {
let field_autocomplete = find("editor/node-tree/node/field/new/attribute");
let {tree_node, selected} = field_autocomplete;
return [
record("editor/event/save-field", {node: tree_node.node, attribute: selected.text}),
record("ui/event/clear", {autocomplete: field_autocomplete})
];
})
.commit("Saving a new field adds a new attribute to the node.", ({find, choose, gather, record}) => {
let {node, attribute} = find("editor/event/save-field");
attribute != "";
// @FIXME: busted as frig...
// let [count] = choose(() => {
// let {attribute} = node;
// 1 == gather(attribute.sort).per(node).sort("down");
// return attribute.sort + 1;
// }, () => 1);
return [node.add("attribute", record("node/attribute", {sort: "@FIXME", attribute}))];
})
.commit("Clicking the delete field button removes its attribute from the node.", ({find, choose, gather, record}) => {
let delete_field = find("editor/node-tree/node/field/delete");
find("html/event/click", {element: delete_field})
let {tree_node, attribute} = delete_field;
let {node} = tree_node;
return [
node.remove("attribute", attribute),
attribute.remove()
];
})
.bind("Blurring a field's value input saves it.", ({find, record}) => {
let field_value = find("editor/node-tree/node/pattern/value");
let {value} = find("html/event/blur", {element: field_value});
let {tree_node, attribute} = field_value;
return [record("editor/event/save-value", {tree_node, attribute, value})];
})
.commit("Saving a field value commits it to the attribute.", ({find, record}) => {
let {attribute, value} = find("editor/event/save-value");
return [attribute.remove("value").add("value", value)];
})
}
//--------------------------------------------------------------------
// Query Editor
//--------------------------------------------------------------------
queryEditor() {
this.editor
.bind("Display a node tree for the active block.", ({find, record}) => {
let content = find("editor/block/content", {type: "query"});
let {editor} = content;
return [
content.add("children", [
record("editor/node-tree", "editor/query-tree", {sort: 1, editor}),
record("editor/molecule-list", "editor/query-molecules", {sort: 2, editor})
])
]
})
.bind("Fill the tree with the active block's nodes.", ({find, record}) => {
let node_tree = find("editor/query-tree");
let {editor} = node_tree;
return [node_tree.add("node", editor.active_block.node)];
})
.bind("Fill the list with the active block's molecules.", ({find, record}) => {
let molecule_list = find("editor/query-molecules");
let {editor} = molecule_list;
let molecule = find("editor/molecule", {block: editor.active_block})
return [molecule_list.add("molecule", molecule)];
})
}
//--------------------------------------------------------------------
// Molecule Generator
//--------------------------------------------------------------------
moleculeGenerator() {
this.editor
.bind("Create a molecule generator for the active block if it has any nodes.", ({find, record}) => {
let editor = find("editor/root");
let {active_block:block} = editor;
block.node.attribute;
return [
block.add("molecule_generator", [
record("editor/molecule/generator", "eve/compiler/block", {block, name: "Generate molecules.", type: "watch", watcher: "send-to-editor"})
])
];
})
.bind("Create an atom record and output for each node of the block with attributes.", ({find, record}) => {
let generator = find("editor/molecule/generator");
let {block} = generator;
let {node} = block;
return [
node.entity.add("tag", "eve/compiler/var"),
generator.add("constraint", [
record("editor/atom/record", "eve/compiler/record", {generator, node, record: node.entity}).add("attribute", [
//@FIXME: Bogus scan to hint to the compiler watcher that it shouldn't try to gen an id.
record({attribute: "tag", value: record("editor/bogus-var", "eve/compiler/var", {node})})
]),
record("editor/atom/output", "eve/compiler/output", {
generator, node, record: record("editor/atom/output/entity", "eve/compiler/var", {node})
}).add("attribute", [
record({attribute: "tag", value: "editor/atom"}),
record({attribute: "record", value: node.entity}),
record({attribute: "node", value: node})
]),
record("editor/record/output", "eve/compiler/output", {generator, node, record: node.entity}).add("attribute", [
record({attribute: "tag", value: "editor/record"})
])
])
];
})
.bind("Attributes with no value are free fields.", ({find, not, record}) => {
let generator = find("editor/molecule/generator");
let {block} = generator;
let {node} = block;
let {attribute} = node;
not(() => attribute.value);
return [record("editor/molecule/free-field", "eve/compiler/var", {node, attribute})];
})
.bind("Attach attributes to atom records and outputs.", ({find, choose, record}) => {
let atom_record = find("editor/atom/record");
let {generator, node} = atom_record;
let record_output = find("editor/record/output", {node});
let {attribute} = node;
let [value] = choose(
() => attribute.value,
() => find("editor/molecule/free-field", {node, attribute})
);
let [identifying] = choose(
() => { attribute.value == find("node").entity; return "eve/compiler/attribute/non-identity"; },
() => "eve/compiler/attribute/identity"
);
return [
atom_record.add("attribute", record({attribute: attribute.attribute, value})),
record_output.add("attribute", [
record({tag: identifying, attribute: attribute.attribute, value}),
])
];
})
.bind("Create a molecule output for each root node.", ({find, record}) => {
let generator = find("editor/molecule/generator");
let {block} = generator;
let {node} = block;
node.tag == "root-node";
let atom_output_entity = find("editor/atom/output/entity", {node});
let molecule_entity;
return [
molecule_entity = record("editor/molecule/entity", "eve/compiler/var", {node}),
generator.add("constraint", [
record("editor/molecule/output", "eve/compiler/output", {generator, node, record: molecule_entity})
.add("parent", node)
.add("attribute", [
record({attribute: "atom", value: atom_output_entity}),
record({attribute: "tag", value: "editor/molecule"}),
record({attribute: "block", value: block}),
record("editor/mol-av", {attribute: "node", value: node}),
])
])
];
})
.bind("Attach subnode atoms to their parent's molecules.", ({find, record}) => {
let molecule = find("editor/molecule/output");
let {generator} = molecule;
let {block} = generator;
let {node} = block;
node.parent == molecule.parent;
let atom_output_entity = find("editor/atom/output/entity", {node});
return [
molecule.add({
parent: node,
attribute: record("eve/compiler/attribute/non-identity", {attribute: "atom", value: atom_output_entity})
})
];
})
}
//--------------------------------------------------------------------
// Molecule Layout
//--------------------------------------------------------------------
moleculeLayout() {
this.editor
.bind("Decorate a molecule list.", ({find}) => {
let molecule_list = find("editor/molecule-list");
return [molecule_list.add({tag: "ui/row"})];
})
.bind("Draw some molecules.", ({find, record}) => {
let molecule_list = find("editor/molecule-list");
let {molecule} = molecule_list;
let {atom} = molecule;
let side = 21;
let molecule_cell;
return [
molecule_list.add("children", [
molecule_cell = record("editor/molecule-list/molecule", "html/element", "html/listener/hover", {tagname: "div", molecule_list, molecule}),
molecule_cell.add("children", [
record("editor/molecule-list/molecule/grid", "shape/hex-grid", {molecule_cell, molecule, side, gap: 5})
]),
])
];
})
.bind("Add cells to molecules.", ({find, record}) => {
let molecule_grid = find("editor/molecule-list/molecule/grid");
let {molecule_cell} = molecule_grid;
let {molecule} = molecule_cell;
let {atom} = molecule;
let side = 21;
return [
molecule_grid.add("cell", [
record("editor/molecule-list/molecule/cell", {molecule_cell, molecule, atom, side})
])
];
})
.bind("A molecule's size is it's largest atom sort.", ({find, not, record}) => {
let cell = find("editor/molecule-list/molecule/cell");
let {molecule_cell} = cell;
not(() => {
let other_cell = find("editor/molecule-list/molecule/cell", {molecule_cell});
other_cell.sort > cell.sort
});
return [
molecule_cell.add("size", cell.sort),
];
})
.bind("HACK: workaround double choose bug offset + mag.", ({find, lib:{math}, choose, record}) => {
let molecule_cell = find("editor/molecule-list/molecule");
let {size} = molecule_cell;
// @FIXME: This isn't quite right due to 0,0 offset
let offset = math.mod(size - 1, 6);
// @FIXME: this measure doesn't take into account the fact that shell size increases...
let mag = math.floor((size - 1) / 7) + 1;
return [
molecule_cell.add({offset, mag}),
];
})
.bind("A molecule's width and height are derived from it's size.", ({find, choose, record}) => {
let molecule_cell = find("editor/molecule-list/molecule");
let {offset, mag} = molecule_cell;
let cell_width = 39 + 5;
let cell_height = 44 + 5;
let width = cell_width * 3 * mag;
let height = cell_height * 3 * mag;
let padLeft = width / 2 - cell_width / 2;
let padTop = height / 2 - cell_height / 2;
return [
molecule_cell.add("style", record({width: `${width}px`, height: `${height}px`, "padding-left": `${padLeft}px`, "padding-top": `${padTop}px`}))
];
})
.bind("Populate atom cells from their atoms.", ({find, choose, record}) => {
let atom_cell = find("editor/molecule-list/molecule/cell");
let {molecule_cell, molecule, atom, side, x, y} = atom_cell;
let {node} = atom;
let lineWidth = 1; //, strokeStyle = "#AAA";
let [strokeStyle] = choose(
() => {atom_cell.open; return "#4444ff"},
() => {atom_cell.tag == "html/hovered"; return "#4444ff"},
() => {molecule_cell.tag == "html/hovered"; return "#aaaaff"},
() => "#aaa"
);
return [
atom_cell.add({tag: ["shape/hexagon", "html/listener/hover"], side, lineWidth, strokeStyle, x, y}).add("content", [
record("ui/text", {atom_cell, text: node.label, style: record({color: node.color})})
])
];
})
.bind("Sort atoms by id.", ({find, gather, record}) => {
let atom = find("editor/atom");
let molecule = find("editor/molecule", {atom});
let {node} = atom;
let ix = gather(atom).per(molecule, node).sort();
return [atom.add("sort", ix)];
})
.bind("Sort atom cells by id.", ({find, gather, record}) => {
let atom_cell = find("editor/molecule-list/molecule/cell");
let {molecule, atom} = atom_cell;
let ix = gather(atom_cell.atom.node.sort, atom_cell).per(molecule).sort();
return [atom_cell.add("sort", ix)];
})
.bind("Position atom cells in a spiral.", ({find, choose, record}) => {
let atom_cell = find("editor/molecule-list/molecule/cell");
let {molecule, atom} = atom_cell;
let {x, y} = find("spiral", {row: 0, sort: atom_cell.sort});
return [atom_cell.add({x, y})];
})
.bind("When a molecule is open, display it's infobox.", ({find, record}) => {
let molecule_cell = find("editor/molecule-list/molecule", {open: "true"});
let {molecule} = molecule_cell;
return [molecule_cell.add("children", [
record("editor/infobox", {molecule, molecule_cell})
])];
})
//--------------------------------------------------------------------
// Molecule Interactions
//--------------------------------------------------------------------
this.editor
.commit("Clicking a molecule opens it.", ({find}) => {
let molecule_cell = find("editor/molecule-list/molecule");
find("html/event/click", {element: molecule_cell});
return [molecule_cell.add("open", "true")];
})
.commit("Clicking outside an open molecule closes it.", ({find, not}) => {
let molecule_cell = find("editor/molecule-list/molecule", {open: "true"});
find("html/event/click");
not(() => find("html/event/click", {element: molecule_cell}));
return [molecule_cell.remove("open")];
})
.commit("Clicking an atom opens it.", ({find}) => {
let atom_cell = find("editor/molecule-list/molecule/cell");
find("html/event/click", {element: atom_cell});
return [atom_cell.add("open", "true")];
})
.commit("Clicking an atom closes any other open atoms.", ({find}) => {
let atom_cell = find("editor/molecule-list/molecule/cell");
find("html/event/click", {element: atom_cell});
let other = find("editor/molecule-list/molecule/cell", {open: "true"});
other != atom_cell;
return [other.remove("open")];
})
.commit("Close any open atoms of closed molecules.", ({find, not}) => {
let atom_cell = find("editor/molecule-list/molecule/cell", {open: "true"});
not(() => atom_cell.molecule_cell.open);
return [atom_cell.remove("open")];
})
}
//--------------------------------------------------------------------
// Infobox
//--------------------------------------------------------------------
infobox() {
this.editor
.bind("A molecule infobox is a column of node infoboxes.", ({find, record}) => {
let infobox = find("editor/infobox");
return [infobox.add("tag", "ui/column")];
})
.bind("A molecule infobox has a node infobox for each unique node.", ({find, record}) => {
let infobox = find("editor/infobox");
let {molecule} = infobox;
let {atom} = molecule;
let {node} = atom;
return [infobox.add("children", [
record("editor/infobox/node", {sort: node.sort, infobox, node}).add("atom", atom)
])];
})
.bind("A node infobox has the node name, a plus field button.", ({find, record}) => {
let node_infobox = find("editor/infobox/node");
let {node} = node_infobox;
return [
node_infobox.add("tag", "ui/column").add("children", [
record("editor/infobox/node/header", "ui/row", {sort: 1, node_infobox}).add("children", [
record("editor/infobox/node/name", "ui/text", {sort: 1, node_infobox, text: node.name}),
]),
record("ui/row", {sort: 3, node_infobox}).add("children", [
record("editor/infobox/field/new", "ui/button", {sort: 1, node_infobox, icon: "android-add"}),
record("editor/infobox/field/attribute", "ui/autocomplete", {sort: 2, node_infobox}) // , placeholder: "field..."
])
])
];
})
.bind("A node infobox with multiple atoms shows a paginator in it's name row.", ({find, gather, record}) => {
let node_infobox = find("editor/infobox/node");
let infobox_header = find("editor/infobox/node/header", {node_infobox});
let {node, count} = node_infobox;
count > 1;
return [
infobox_header.add("children", [
record("ui/row", {sort: 2, node_infobox, class: "editor-paginator"}).add("children", [
// record("ui/button", {sort: 1, node_infobox, icon: "arrow-left-b"}),
record("ui/text", {sort: 2, text: `(1/${count})`}),
// record("ui/button", {sort: 3, node_infobox, icon: "arrow-right-b"}),
])
])
];
})
.bind("A node infobox's count is the number of atoms it has that match.", ({find, gather, record}) => {
let node_infobox = find("editor/infobox/node");
let {node, infobox} = node_infobox;
let {molecule} = infobox;
let {atom} = molecule;
atom.node == node;
let count = gather(atom).per(node).count();
return [node_infobox.add("count", count)];
})
.bind("A molecule infobox atom's fields are derived from its record AVs. Show the greatest if there are multiple and none are open.", ({find, lookup, gather, not, record}) => {
let node_infobox = find("editor/infobox/node");
let {node, atom} = node_infobox;
let {attribute, value} = lookup(atom.record);
// @FIXME: Strongly coupled to molecule list here. Instead, pass in an `active` attribute on the infobox.
not(() => find("editor/molecule-list/molecule/cell", {open: "true"}).atom.node == node);
// @FIXME: This bug isn't not related, it's due to atom sharing.
// not(() => {
// let other_atom = find("editor/atom", {node});
// node_infobox.atom == other_atom;
// other_atom.sort > atom.sort;
// })
// 2 < gather(atom).per(node).sort();
// @FIXME: This will be sad with reused atoms.
atom.sort < 2;
attribute != "tag";
not(() => value.tag);
return [
node_infobox.add("children", [
record("editor/infobox/atom", "ui/field-table", {sort: 2, node_infobox, atom, record: atom.record}).add("field", [
record({node_infobox, record: atom.record, attribute}).add("value", value)
])
])
];
})
.bind("A molecule infobox atom's fields are derived from its record AVs. Show the open atom if it exists.", ({find, lookup, not, record}) => {
let node_infobox = find("editor/infobox/node");
let {node, atom, infobox} = node_infobox;
// @FIXME: Strongly coupled to molecule list here.
let atom_cell = find("editor/molecule-list/molecule/cell", {molecule_cell: infobox.molecule_cell, open: "true"});
atom_cell.atom == atom;
let {attribute, value} = lookup(atom.record);
attribute != "tag";
not(() => value.tag);
return [
node_infobox.add("children", [
record("editor/infobox/atom", "ui/field-table", {sort: 2, node_infobox, atom, record: atom.record}).add("field", [
record({node_infobox, record: atom.record, attribute}).add("value", value)
])
])
];
})
.bind("Fill infobox attribute completions.", ({find, record}) => {
let new_attribute = find("editor/infobox/field/attribute");
let {node_infobox} = new_attribute;
let completion = find("editor/existing-node-attribute", {node: node_infobox.node});
return [new_attribute.add("completion", completion)];
})
.bind("An infobox require completions.", ({find}) => {
let node_infobox = find("editor/infobox/node");
let {node} = node_infobox;
return [node.add("completing", "true")];
})
;
//--------------------------------------------------------------------
// Infobox Interactions
//--------------------------------------------------------------------
this.editor
.commit("Clicking the infobox new field button focuses it's autocomplete.", ({find}) => {
let add_field = find("editor/infobox/field/new");
let {node_infobox} = add_field;
let event = find("html/event/click", {element: add_field})
let field_autocomplete = find("editor/infobox/field/attribute", {node_infobox});
return [field_autocomplete.add("tag", "html/trigger-focus")];
})
.bind("Selecting a completion in the new field autocomplete saves it.", ({find, not, record}) => {
let field_autocomplete = find("editor/infobox/field/attribute");
let {node_infobox, selected} = field_autocomplete;
return [
record("editor/event/save-field", {node: node_infobox.node, attribute: selected.text}),
record("ui/event/clear", {autocomplete: field_autocomplete})
];
})
}
//--------------------------------------------------------------------
// Completion Generator
//--------------------------------------------------------------------
completionGenerator() {
//--------------------------------------------------------------------
// Tag completions
//--------------------------------------------------------------------
this.program
.watch("Make existing tags in the program available to the editor.", ({find, record}) => {
let rec = find();
return [record("editor/existing-tag", {text: rec.tag})];
})
.asDiffs(forwardDiffs(this.editor, "Send tags to editor.", false));
//--------------------------------------------------------------------
// Node -> Attribute completions
//--------------------------------------------------------------------
this.editor
.bind("Create a completion generator for node -> attribute.", ({find, record}) => {
let node = find("node", {completing: "true"});
return [
record("editor/node/attribute/completer", "eve/compiler/block", {node, name: "Node attribute completer.", type: "watch", watcher: "send-to-editor"})
.add("joined_node", node)
];
})
.bind("Create a record for each node.", ({find, record}) => {
// @NOTE: This is intentionally local. Do we want it to be block-level filtering vs node-level?
let completer = find("editor/node/attribute/completer");
let {joined_node:node} = completer;
return [
node.entity.add("tag", "eve/compiler/var"),
completer.add("constraint", [
record("editor/node/record", "eve/compiler/record", {completer, node, record: node.entity}).add("attribute", [
//@FIXME: Bogus scan to hint to the compiler watcher that it shouldn't try to gen an id.
record({attribute: "tag", value: record("editor/bogus-var", "eve/compiler/var", {node})})
])
])
];
})
.bind("Attributes with no value are free fields.", ({find, not, record}) => {
let completer = find("editor/node/attribute/completer");
let {joined_node:node} = completer;
let {attribute} = node;
not(() => attribute.value);
return [record("editor/molecule/free-field", "eve/compiler/var", {node, attribute})]; // @FIXME: Rename this tag something more generic.
})
.bind("Attach attributes to node record.", ({find, choose, record}) => {
let node_record = find("editor/node/record");
let {completer, node} = node_record;
let {attribute} = node;
let [value] = choose(
() => attribute.value,
() => find("editor/molecule/free-field", {node, attribute})
);
let [identifying] = choose(
() => { attribute.value == find("node").entity; return "eve/compiler/attribute/non-identity"; },
() => "eve/compiler/attribute/identity"
);
return [node_record.add("attribute", record({attribute: attribute.attribute, value}))];
})
.bind("Parent nodes are joined nodes.", ({find, choose, record}) => {
let completer = find("editor/node/attribute/completer");
let {joined_node:node} = completer;
return [completer.add("joined_node", node.parent)];
})
.bind("The completions are the attributes of any records that still match.", ({find, record}) => {
let completer = find("editor/node/attribute/completer");
let {node} = completer;
let output_var;
let attr_match;
let val_match;
return [
output_var = record("eve/compiler/var", "editor/node/attribute/completer/output", {node}),
attr_match = record("eve/compiler/var", "editor/node/attribute/completer/attribute", {node}),
val_match = record("eve/compiler/var", "editor/node/attribute/completer/value", {node}),
completer.add("constraint", [
record("eve/compiler/output", {node, record: output_var}).add("attribute", [
record({attribute: "tag", value: "editor/existing-node-attribute"}),
record({attribute: "node", value: node}),
record({attribute: "text", value: attr_match}),
// @FIXME: We can't gen a choose so we have to send it over and figure out is_record editor-side.
record("eve/compiler/attribute/non-identity", {attribute: "value", value: val_match}),
]),
record("eve/compiler/lookup", {record: node.entity, attribute: attr_match, value: val_match}),
])
];
})
.bind("Compute is_record based on the values of existing node attributes.", ({find, lib:{string}}) => {
let existing = find("editor/existing-node-attribute");
string["index-of"](existing.value, "|"); // @FIXME: hacky gen id detection.
return [existing.add("is_record", "true")];
})
}
}
Watcher.register("editor", EditorWatcher); | the_stack |
module WinJSTests {
"use strict";
var COUNT = 6;
var JUMPSCOUNT = 10;
var FlipView = <typeof WinJS.UI.PrivateFlipView> WinJS.UI.FlipView;
function narratorScrollChangedTest(element, flipview, rawData, complete) {
var tests = [
function () {
LiveUnit.Assert.areEqual(0, flipview.currentPage);
if (flipview.orientation === "horizontal") {
var scrollPosition = WinJS.Utilities.getScrollPosition(flipview._panningDivContainer);
scrollPosition.scrollLeft += 400;
WinJS.Utilities.setScrollPosition(flipview._panningDivContainer, scrollPosition);
} else {
flipview._panningDivContainer.scrollTop += 400;
}
// This should trigger a scroll position changed, and eventually
// a pageselected event. This simulates the 1-finger swipe
// scenario with the narrator touch
},
function () {
LiveUnit.Assert.areEqual(1, flipview.currentPage);
flipview.currentPage = 0;
},
function () {
LiveUnit.Assert.areEqual(0, flipview.currentPage);
complete();
}
];
runFlipViewTests(flipview, tests);
}
function verifyDisplayedItem(flipView, rawData) {
LiveUnit.LoggingCore.logComment("Verifying displayed page is correct");
LiveUnit.Assert.isTrue(currentPageInView(flipView));
flipView.itemTemplate.verifyOutput(getDisplayedElement(flipView), rawData);
}
function navigationTest(element, flipView, rawData, complete) {
var tests = [];
for (var i = 0; i < COUNT - 1; i++) {
var getWrappedNext = function getWrappedNext(targetIndex) {
return function () {
LiveUnit.LoggingCore.logComment("Should be at " + targetIndex);
LiveUnit.Assert.areEqual(targetIndex, flipView.currentPage);
verifyDisplayedItem(flipView, rawData[targetIndex]);
LiveUnit.LoggingCore.logComment("Flipping ahead");
LiveUnit.Assert.isTrue(flipView.next());
}
};
tests.push(getWrappedNext(i));
}
tests.push(function () {
LiveUnit.LoggingCore.logComment("Should now be at end, flipView.next should fail");
LiveUnit.Assert.areEqual(COUNT - 1, flipView.currentPage);
verifyDisplayedItem(flipView, rawData[COUNT - 1]);
LiveUnit.Assert.isFalse(flipView.next());
return true;
});
for (var i = COUNT - 1; i > 0; i--) {
var getWrappedPrevious = function getWrappedPrevious(targetIndex) {
return function () {
LiveUnit.LoggingCore.logComment("Should be at " + targetIndex);
LiveUnit.Assert.areEqual(targetIndex, flipView.currentPage);
verifyDisplayedItem(flipView, rawData[targetIndex]);
LiveUnit.LoggingCore.logComment("Flipping back");
LiveUnit.Assert.isTrue(flipView.previous());
}
};
tests.push(getWrappedPrevious(i));
}
tests.push(function () {
LiveUnit.LoggingCore.logComment("Should now be at beginning, flipView.previous should fail");
LiveUnit.Assert.areEqual(0, flipView.currentPage);
verifyDisplayedItem(flipView, rawData[0]);
LiveUnit.Assert.isFalse(flipView.previous());
complete();
});
runFlipViewTests(flipView, tests);
}
function jumpToTest(element, flipView, rawData, complete) {
var tests = [],
lastIndex = 0;
for (var i = 0; i < JUMPSCOUNT; i++) {
var getWrappedJump = function getWrappedJump(targetIndex, lastIndex) {
return function () {
// Validate aria-flowto attributes
var curr = flipView._pageManager._currentPage;
LiveUnit.Assert.areEqual(flipView._pageManager._bufferAriaStartMarker.getAttribute("aria-flowto"), curr.element.id);
var next = curr.next;
if (next && next.element) {
LiveUnit.Assert.areEqual(curr.element.getAttribute("aria-flowto"), next.element.id);
LiveUnit.Assert.areEqual(next.element.getAttribute("x-ms-aria-flowfrom"), curr.element.id);
var nextOfNext = curr.next.next;
if (nextOfNext && nextOfNext.element) {
LiveUnit.Assert.areEqual(next.element.getAttribute("aria-flowto"), nextOfNext.element.id);
LiveUnit.Assert.areEqual(nextOfNext.element.getAttribute("x-ms-aria-flowfrom"), next.element.id);
LiveUnit.Assert.areEqual(nextOfNext.element.getAttribute("aria-flowto"), flipView._pageManager._bufferAriaEndMarker.id);
}
}
var prev = curr.prev;
if (prev && prev.element) {
LiveUnit.Assert.areEqual(prev.element.getAttribute("aria-flowto"), curr.element.id);
LiveUnit.Assert.areEqual(curr.element.getAttribute("x-ms-aria-flowfrom"), prev.element.id);
var prevOfPrev = curr.prev.prev;
if (prevOfPrev && prevOfPrev.element) {
LiveUnit.Assert.areEqual(prevOfPrev.element.getAttribute("aria-flowto"), prev.element.id);
LiveUnit.Assert.areEqual(prev.element.getAttribute("x-ms-aria-flowfrom"), prevOfPrev.element.id);
}
}
LiveUnit.LoggingCore.logComment("Should be at " + lastIndex);
LiveUnit.Assert.areEqual(lastIndex, flipView.currentPage);
verifyDisplayedItem(flipView, rawData[lastIndex]);
LiveUnit.LoggingCore.logComment("Flipping to " + targetIndex);
flipView.currentPage = targetIndex;
return targetIndex === lastIndex;
}
};
var nextIndex = pseudorandom(COUNT);
tests.push(getWrappedJump(nextIndex, lastIndex));
lastIndex = nextIndex;
}
tests.push(function () {
if (flipView.currentPage === 0) {
return true;
}
flipView.currentPage = 0;
});
tests.push(function () {
flipView.currentPage = COUNT + 1;
});
tests.push(function () {
LiveUnit.Assert.areEqual(COUNT - 1, flipView.currentPage);
verifyDisplayedItem(flipView, rawData[COUNT - 1]);
flipView.currentPage = -9999;
});
tests.push(function () {
LiveUnit.Assert.areEqual(0, flipView.currentPage);
verifyDisplayedItem(flipView, rawData[0]);
complete();
});
runFlipViewTests(flipView, tests);
}
export class FlipViewNavigationTests {
setUp() {
LiveUnit.LoggingCore.logComment("In setup");
var newNode = document.createElement("div");
newNode.id = "BasicFlipView";
newNode.style.width = "400px";
newNode.style.height = "400px";
document.body.appendChild(newNode);
}
tearDown() {
LiveUnit.LoggingCore.logComment("In tearDown");
var element = document.getElementById("BasicFlipView");
if (element) {
WinJS.Utilities.disposeSubTree(element);
document.body.removeChild(element);
}
}
testZoombieFlipViewDuringNavigation(complete) {
var element = document.getElementById("BasicFlipView"),
testData = createArraySource(COUNT, ["400px"], ["400px"]),
rawData = testData.rawData,
flipView = new WinJS.UI.FlipView(element, { itemDataSource: testData.dataSource, itemTemplate: basicInstantRenderer });
flipView.addEventListener("pageselected", function pageSelectedHandler() {
flipView.removeEventListener("pageselected", pageSelectedHandler);
LiveUnit.Assert.areEqual(0, flipView.currentPage);
flipView.currentPage = 3;
flipView.element.textContent = null;
//Ensure that we don't get a JS exception when the animation completes
setTimeout(complete, WinJS.UI._animationTimeAdjustment(1000));
});
}
testCurrentPageDuringNavigationAnimation(complete) {
var element = document.getElementById("BasicFlipView"),
testData = createArraySource(COUNT, ["400px"], ["400px"]),
rawData = testData.rawData,
flipView = new FlipView(element, { itemDataSource: testData.dataSource, itemTemplate: basicInstantRenderer });
flipView.addEventListener("pageselected", function pageSelectedHandler() {
flipView.removeEventListener("pageselected", pageSelectedHandler);
LiveUnit.Assert.areEqual(0, flipView.currentPage);
// Go to the next page, and while it is animating, go back to the previous page. We should
// end up in the first page.
flipView.next();
});
var pageVisibleCount = 0,
pageInvisibleCount = 0;
flipView.addEventListener("pagevisibilitychanged", function pageVisibilityHandler(ev) {
ev.detail.visible ? pageVisibleCount++ : pageInvisibleCount++;
if (pageInvisibleCount === 2) {
LiveUnit.Assert.areEqual(0, flipView.currentPage, "Flipview did not end in the first page");
flipView.removeEventListener("pagevisibilitychanged", pageVisibilityHandler);
complete();
}
WinJS.Utilities.Scheduler.schedule(function () {
if (pageVisibleCount === 1) {
LiveUnit.Assert.isTrue(flipView._animating);
LiveUnit.Assert.areEqual(1, flipView.currentPage);
LiveUnit.Assert.isTrue(flipView._animating);
flipView.previous();
}
}, WinJS.Utilities.Scheduler.Priority.normal);
});
}
};
function generate(name, testFunction) {
function generateTest(orientation) {
FlipViewNavigationTests.prototype[name + "_" + orientation] = function (complete) {
var element = document.getElementById("BasicFlipView"),
testData = createArraySource(COUNT, ["4200px"], ["4200px"]),
rawData = testData.rawData,
flipView;
element.style.width = "4200px";
element.style.height = "4200px";
flipView = new WinJS.UI.FlipView(element, { itemDataSource: testData.dataSource, itemTemplate: basicInstantRenderer, orientation: orientation });
setupQuickAnimations(flipView);
testFunction(element, flipView, rawData, complete);
};
}
generateTest("horizontal");
generateTest("vertical");
}
generate("testFlipViewOn4KDisplay", navigationTest);
function generate2(name, testFunction) {
function generateTest(orientation) {
FlipViewNavigationTests.prototype[name + "_" + orientation] = function (complete) {
var element = document.getElementById("BasicFlipView"),
testData = createArraySource(COUNT, ["400px"], ["400px"]),
rawData = testData.rawData,
flipView = new WinJS.UI.FlipView(element, { itemDataSource: testData.dataSource, itemTemplate: basicInstantRenderer, orientation: orientation });
setupQuickAnimations(flipView);
testFunction(element, flipView, rawData, complete);
};
}
generateTest("horizontal");
generateTest("vertical");
}
generate2("testBasicFlipViewNavigation", navigationTest);
generate2("testJumpToNavigation", jumpToTest);
generate2("testScrollChangedByNarrator", narratorScrollChangedTest);
}
LiveUnit.registerTestClass("WinJSTests.FlipViewNavigationTests"); | the_stack |
import { Component } from '@angular/core';
import {
CustomInsightsWidget,
IBaseStyleConfig,
ICustomColorElement,
ICustomData,
ICustomElement,
ICustomInsightsWidgetConfig,
IEmotion,
ITopic,
IInsightsWidgetConfig,
IWidgetStyle,
InsightsWidget
} from '@azure/video-analyzer-for-media-widgets';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
public insightsWidget: InsightsWidget;
public ngAfterViewInit(): void {
const insightsStyleConfig2: IBaseStyleConfig = {
primary: 'yellow',
dividers: 'rgba(134,28,173,1)'
};
const style: IWidgetStyle = {
customStyle: insightsStyleConfig2,
theme: 'Dark'
};
const config: IInsightsWidgetConfig = {
accountId: '00000000-0000-0000-0000-000000000000',
videoId: 'd9d4860279',
// accessToken: '<ACCESS-TOKEN>',
locale: 'es-es',
tab: 'timeline',
components: ['emotions', 'sentiments', 'transcript', 'keywords'],
style: style
};
this.insightsWidget = new InsightsWidget(
'container',
{
height: 780,
width: 580
},
config
);
this.insightsWidget.render();
// Custom insights widget
const emotions: IEmotion[] = [
{
id: 1,
type: 'Joy',
instances: [
{
adjustedEnd: '0:06:46.15',
adjustedStart: '0:06:42.086',
confidence: 0.6808,
end: '0:06:46.15',
start: '0:06:42.086'
}
]
},
{
id: 2,
type: 'Sad',
instances: [
{
adjustedEnd: '0:10:18.957',
adjustedStart: '0:09:59.306',
confidence: 0.8383,
end: '0:10:18.957',
start: '0:09:59.306'
}
]
}
];
const sentiments = [
{
averageScore: 0.5,
id: 1,
sentimentType: 'Neutral',
instances: [
{
adjustedEnd: '0:06:42.086',
adjustedStart: '0:00:00',
end: '0:06:42.086',
start: '0:00:00'
}
]
},
{
id: 2,
sentimentType: 'Positive',
averageScore: 0.9521,
instances: [
{
adjustedEnd: '0:06:46.15',
adjustedStart: '0:06:42.086',
end: '0:06:46.15',
start: '0:06:42.086'
}
]
},
{
id: 3,
sentimentType: 'Negative',
averageScore: 0.1677,
instances: [
{
adjustedEnd: '0:10:18.957',
adjustedStart: '0:09:59.306',
end: '0:10:18.957',
start: '0:09:59.306'
}
]
}
];
const topics: ITopic[] = [
{
confidence: 0.7577,
id: 1,
name: 'Brand Audit',
referenceId: 'Brand Audit',
language: 'en-US',
instances: [
{
adjustedEnd: '0:01:52.838',
adjustedStart: '0:00:13.712',
end: '0:01:52.838',
start: '0:00:13.712'
},
{
adjustedEnd: '0:03:16.21',
adjustedStart: '0:02:08.093',
end: '0:03:16.21',
start: '0:02:08.093'
}
]
},
{
confidence: 0.4893,
iabName: 'News and Politics',
id: 23,
instances: [
{
adjustedEnd: '0:02:59.015',
adjustedStart: '0:00:08.421',
end: '0:02:59.015',
start: '0:00:08.421'
}
],
iptcName: 'Politics/election',
language: 'en-US',
name: 'Political Campaigns and Elections',
referenceId: 'Politics and Government/Political Campaigns and Elections',
referenceType: 'VideoIndexer'
},
{
confidence: 0.6453,
iabName: 'Business and Finance',
id: 14,
instances: [
{
adjustedEnd: '0:02:37.644',
adjustedStart: '0:00:00',
end: '0:02:37.644',
start: '0:00:00'
},
{
adjustedEnd: '0:04:01.497',
adjustedStart: '0:03:39.322',
end: '0:04:01.497',
start: '0:03:39.322'
},
{
adjustedEnd: '0:05:00.968',
adjustedStart: '0:04:36.6',
end: '0:05:00.968',
start: '0:04:36.6'
}
],
iptcName: 'Economy, Business and Finance/business (general)',
language: 'en-US',
name: 'Brand Strategy',
referenceId: 'Business/Product Development/Brand Strategy',
referenceType: 'VideoIndexer'
}
];
const customElement2 = {
id: 1,
text: 'Hello',
instances: [
{
adjustedEnd: '0:00:12.44',
adjustedStart: '0:00:11.54',
end: '0:00:12.44',
start: '0:00:11.54'
},
{
adjustedEnd: '0:05:27.96',
adjustedStart: '0:05:19.89',
end: '0:05:27.96',
start: '0:05:19.89'
},
{
adjustedEnd: '0:02:06.443',
adjustedStart: '0:02:00.83',
end: '0:02:06.443',
start: '0:02:00.83'
},
{
adjustedEnd: '0:03:45.44',
adjustedStart: '0:03:43.21',
end: '0:03:45.44',
start: '0:03:43.21'
}
]
};
const customElement: ICustomElement = {
id: 1,
text: 'What',
instances: [
{
adjustedEnd: '0:02:37.644',
adjustedStart: '0:00:00',
end: '0:02:37.644',
start: '0:00:00'
},
{
adjustedEnd: '0:04:01.497',
adjustedStart: '0:03:39.322',
end: '0:04:01.497',
start: '0:03:39.322'
},
{
adjustedEnd: '0:05:00.968',
adjustedStart: '0:04:36.6',
end: '0:05:00.968',
start: '0:04:36.6'
}
]
};
const customColorElement: ICustomColorElement = {
id: 1,
text: 'Hello!!!!!',
color: 'blue',
instances: [
{
adjustedEnd: '0:02:37.644',
adjustedStart: '0:00:00',
end: '0:02:37.644',
start: '0:00:00'
},
{
adjustedEnd: '0:04:01.497',
adjustedStart: '0:03:39.322',
end: '0:04:01.497',
start: '0:03:39.322'
},
{
adjustedEnd: '0:05:00.968',
adjustedStart: '0:04:36.6',
end: '0:05:00.968',
start: '0:04:36.6'
}
]
};
const customColorElement2 = {
id: 2,
text: 'Second color',
color: 'darkmagenta',
instances: [
{
adjustedEnd: '0:06:46.15',
adjustedStart: '0:06:42.086',
end: '0:06:46.15',
start: '0:06:42.086'
}
]
};
const customColorElement3 = {
id: 3,
text: 'Should show white',
color: '#FFFFF',
instances: [
{
adjustedEnd: '0:10:18.957',
adjustedStart: '0:09:59.306',
confidence: 0.8383,
end: '0:10:18.957',
start: '0:09:59.306'
}
]
};
const customColorData: ICustomData = {
title: 'Nofar Color',
key: 'nofarColor',
presets: ['all', 'accessibility'],
type: 'color-map',
items: [customColorElement, customColorElement2, customColorElement3]
};
const customData: ICustomData = {
title: 'Nofar Data',
key: 'nofar',
presets: ['all', 'captioning'],
type: 'capsule',
items: [customElement, customElement2]
};
const insightsStyleConfig = {
primary: 'rgba(255,59,209,1)',
componentFill: 'rgba(33,59,209,1)',
headerActions: 'rgba(26,188,156,1)',
dividers: 'rgba(134,28,173,1)',
bgSecondary: 'rgba(189,224,255,0.4)',
bgPrimary: 'rgba(255,144,144,1)'
};
const lowKeyStyle = {
highlight: 'rgba(14,182,255,1)',
primary: 'rgba(13,11,0,1)',
primaryHover: 'rgba(64,55,55,1)',
primaryPress: 'rgba(91,78,78,1)',
primaryDisable: 'rgba(0,0,0,0.050)',
secondaryFill: 'rgba(0,0,0,0.050)',
secondaryFillHover: 'rgba(0,0,0,0.080)',
secondaryFillPress: 'rgba(91,78,78,0.2)',
secondaryStroke: 'rgba(91,78,78,0.6)',
componentFill: 'rgba(255,255,255,1)',
componentStroke: 'rgba(91,78,78,0.6)',
componentStrokeAlt: 'rgba(91,78,78,0.8)',
playStatus: 'rgba(13,167,234,0.200)',
playStatusAlt: 'rgba(14,182,255,0.750)',
headerActions: 'rgba(255,255,255,1)',
headerHovers: 'rgba(255,255,255,0.380)',
headerHoversAlt: 'rgba(255,255,255,0.760)',
headerBg: 'rgba(28,28,28,1)',
dividers: 'rgba(91,78,78,0.1)',
dividersAlt: 'rgba(91,78,78,0.1)',
dividersPanel: 'rgba(91,78,78,0.2)',
bgPrimary: 'rgba(250,249,247,1)',
bgSecondary: 'rgba(246,245,243,1)',
typePrimary: 'rgba(64,55,55,1)',
typeSecondary: 'rgba(64,55,55,0.700)',
typeDisabled: 'rgba(64,55,55,0.420)',
typeDisabledAlt: 'rgba(64,55,55,0.300)',
emotionJoy: 'rgba(242,97,12,1)',
emotionFear: 'rgba(166,8,148,1)',
emotionSadness: 'rgba(0,120,212,1)',
emotionAnger: 'rgba(227,0,140,1)',
sentimentPositive: 'rgba(18,134,110,1)',
sentimentNegative: 'rgba(235,0,27,1)',
videoMenuBg: 'rgba(0,0,0,0.800)',
videoShade: 'rgba(255,255,255,0.380)',
errorType: 'rgba(168,0,0,1)',
errorArea: 'rgba(208,46,0,1)',
errorAreaTint: 'rgba(253,231,233,1)',
warningArea: 'rgba(255,244,206,1)',
shadow: 'rgba(64,55,55,0.140)'
};
const midnightStyle = {
highlight: 'rgba(80,230,255,1)',
primary: 'rgba(80,230,255,1)',
primaryHover: 'rgba(67,214,238,1)',
primaryPress: 'rgba(64,199,222,1)',
primaryDisable: 'rgba(255,255,255,0.120)',
secondaryFill: 'rgba(8,18,34,1)',
secondaryFillHover: 'rgba(255,255,255,0.080)',
secondaryFillPress: 'rgba(255,255,255,0.120)',
secondaryStroke: 'rgba(255,255,255,0.540)',
componentFill: 'rgba(36,36,36,1)',
componentStroke: 'rgba(255,255,255,0.620)',
componentStrokeAlt: 'rgba(255,255,255,0.760)',
playStatus: 'rgba(80,230,255,0.250)',
playStatusAlt: 'rgba(80,230,255,1)',
headerActions: 'rgba(255,255,255,1)',
headerHovers: 'rgba(255,255,255,0.380)',
headerHoversAlt: 'rgba(255,255,255,0.760)',
headerBg: 'rgba(28,28,28,1)',
dividers: 'rgba(255,255,255,0.080)',
dividersAlt: 'rgba(255,255,255,0.120)',
dividersPanel: 'rgba(255,255,255,0.200)',
bgPrimary: 'rgba(8,18,34,1)',
bgSecondary: 'rgba(8,18,34,1)',
typePrimary: 'rgba(255,250,209,1)',
typeSecondary: 'rgba(255,250,209,0.760)',
typeDisabled: 'rgba(255,250,209,0.380)',
typeDisabledAlt: 'rgba(255,250,209,0.220)',
emotionJoy: 'rgba(242,124,74,1)',
emotionFear: 'rgba(192,125,255,1)',
emotionSadness: 'rgba(77,157,255,1)',
emotionAnger: 'rgba(255,107,107,1)',
sentimentPositive: 'rgba(80,230,255,1)',
sentimentNegative: 'rgba(255,107,107,1)',
videoMenuBg: 'rgba(0,0,0,0.800)',
videoShade: 'rgba(255,255,255,0.380)',
errorType: 'rgba(241,112,123,1)',
errorArea: 'rgba(208,46,0,1)',
errorAreaTint: 'rgba(62,29,34,1)',
warningArea: 'rgba(62,59,29,1)',
shadow: 'rgba(0,0,0,0.760)'
};
const royalBlue = {
highlight: 'rgba(209,0,209,1)',
primary: 'rgba(209,0,209,1)',
primaryHover: 'rgba(192,7,192,1)',
primaryPress: 'rgba(180,13,180,1)',
primaryDisable: 'rgba(110,150,181,0.200)',
secondaryFill: 'rgba(241,249,255,1)',
secondaryFillHover: 'rgba(209,234,255,0.500)',
secondaryFillPress: 'rgba(209,234,255,0.700)',
secondaryStroke: 'rgba(33,72,209,0.700)',
componentFill: 'rgba(246,251,255,1)',
componentStroke: 'rgba(33,72,209,0.800)',
componentStrokeAlt: 'rgba(33,72,209,0.900)',
playStatus: 'rgba(192,7,192,0.100)',
playStatusAlt: 'rgba(192,7,192,0.600)',
headerActions: 'rgba(255,255,255,1)',
headerHovers: 'rgba(255,255,255,0.380)',
headerHoversAlt: 'rgba(255,255,255,0.760)',
headerBg: 'rgba(28,28,28,1)',
dividers: 'rgba(37,151,255,0.100)',
dividersAlt: 'rgba(37,151,255,0.200)',
dividersPanel: 'rgba(37,151,255,0.200)',
bgPrimary: 'rgba(255,255,255,1)',
bgSecondary: 'rgba(248,248,248,1)',
typePrimary: 'rgba(0,57,255,1)',
typeSecondary: 'rgba(33,72,209,0.800)',
typeDisabled: 'rgba(33,72,209,0.500)',
typeDisabledAlt: 'rgba(33,72,209,0.250)',
emotionJoy: 'rgba(242,97,12,1)',
emotionFear: 'rgba(166,8,148,1)',
emotionSadness: 'rgba(0,120,212,1)',
emotionAnger: 'rgba(227,0,140,1)',
sentimentPositive: 'rgba(8,170,136,1)',
sentimentNegative: 'rgba(227,0,140,1)',
videoMenuBg: 'rgba(33,72,209,0.800)',
videoShade: 'rgba(33,72,209,0.400)',
errorType: 'rgba(203,14,14,1)',
errorArea: 'rgba(222,75,33,1)',
errorAreaTint: 'rgba(248,219,211,1)',
warningArea: 'rgba(255,241,191,1)',
shadow: 'rgba(122,137,188,0.200)'
};
const insightsConfig: ICustomInsightsWidgetConfig = {
duration: 634,
rawInsightsData: [
{
rawInsightsKey: 'emotions',
insightsItems: emotions
},
{
rawInsightsKey: 'sentiments',
insightsItems: sentiments
},
{
rawInsightsKey: 'topics',
insightsItems: topics
}
],
customData: [customData, customColorData],
viInsightsKeys: ['brands', 'keywords', 'scenes', 'blocks'],
accountId: '244dffb2-d95f-4f9f-a90b-698de871a14b',
videoId: '37075bedb4',
style: {
// customStyle: midnightStyle,
customStyle: royalBlue
// customStyle: lowKeyStyle,
// customStyle: insightsStyleConfig,
// theme: 'Dark'
}
};
const customInsightsWidget = new CustomInsightsWidget(
'custom-widget-container',
{
width: 800,
height: 1000
},
insightsConfig
);
customInsightsWidget.render();
}
public get apiVersion() {
return this.insightsWidget?.apiVersion;
}
} | the_stack |
import { Component, Input, Directive } from '@angular/core';
import { ComponentFixture, TestBed, fakeAsync, tick, inject, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { IdentityComponent } from './identity.component';
import { IssueIdentityComponent } from './issue-identity';
import { AlertService } from '../basic-modals/alert.service';
import { ClientService } from '../services/client.service';
import { IdentityCardService } from '../services/identity-card.service';
import { AdminService } from '../services/admin.service';
import { BusinessNetworkConnection, ParticipantRegistry } from 'composer-client';
import { IdCard, Resource } from 'composer-common';
import { LocalStorageService } from 'angular-2-local-storage';
import * as fileSaver from 'file-saver';
import * as chai from 'chai';
import * as sinon from 'sinon';
import { WSAEINVALIDPROVIDER } from 'constants';
let should = chai.should();
@Component({
selector: 'app-footer',
template: ''
})
class MockFooterComponent {
}
@Directive({
selector: '[ngbTooltip]'
})
class MockToolTipDirective {
@Input() public ngbTooltip: string;
@Input() public placement: string;
@Input() public container: string;
}
describe(`IdentityComponent`, () => {
let component: IdentityComponent;
let fixture: ComponentFixture<IdentityComponent>;
let mockModal;
let mockClientService;
let mockBusinessNetworkConnection;
let mockAdminService;
let mockLocalStorage;
let currentCardRef;
let currentIdCard;
let cardOne;
let networkAdmin;
beforeEach(() => {
mockModal = sinon.createStubInstance(NgbModal);
mockAdminService = sinon.createStubInstance(AdminService);
mockLocalStorage = sinon.createStubInstance(LocalStorageService);
mockClientService = sinon.createStubInstance(ClientService);
mockBusinessNetworkConnection = sinon.createStubInstance(BusinessNetworkConnection);
mockAdminService.importCard.resolves();
mockAdminService.deleteCard.resolves();
mockClientService.ensureConnected.resolves(true);
mockClientService.revokeIdentity.resolves();
mockBusinessNetworkConnection.getIdentityRegistry.resolves({
getAll: sinon.stub().returns([{
name: 'bob', participant: {
$namespace: 'bob-namespace',
$type: 'bob-type',
getType: () => { return 'bob-type'; },
getNamespace: () => { return 'bob-namespace'; },
getIdentifier: () => { return 'pingu'; }
},
}, {
name: 'fred', participant: {
$namespace: 'fred-namespace',
$type: 'fred-type',
getType: () => { return 'fred-type'; },
getNamespace: () => { return 'fred-namespace'; },
getIdentifier: () => { return 'pinga'; }
}
}, {
name: 'jim', participant: {
$namespace: 'jim-namespace',
$type: 'jim-type',
getType: () => { return 'NetworkAdmin'; },
getNamespace: () => { return 'jim-namespace'; },
getIdentifier: () => { return 'pingo'; }
}
}, {
name: 'tony', participant: {
$namespace: 'tony-namespace',
$type: 'tony-type',
getType: () => { return 'tony-type'; },
getNamespace: () => { return 'tony-namespace'; },
getIdentifier: () => { return 'pinga'; }
}
}])
});
mockClientService.getBusinessNetworkConnection.returns(mockBusinessNetworkConnection);
mockClientService.getBusinessNetwork.returns({getName: sinon.stub().returns('penguin-network')});
TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [
IdentityComponent,
MockFooterComponent,
MockToolTipDirective
],
providers: [
AlertService, IdentityCardService,
{provide: NgbModal, useValue: mockModal},
{provide: AdminService, useValue: mockAdminService},
{provide: LocalStorageService, useValue: mockLocalStorage},
{provide: ClientService, useValue: mockClientService},
]
});
fixture = TestBed.createComponent(IdentityComponent);
component = fixture.componentInstance;
});
beforeEach(fakeAsync(inject([IdentityCardService], (identityCardService: IdentityCardService) => {
currentIdCard = new IdCard({userName: 'bob', businessNetwork: 'penguin-network'}, {
name: 'mycp',
type: 'hlfv1'
});
cardOne = new IdCard({userName: 'fred', businessNetwork: 'penguin-network'}, {
name: 'mycp',
type: 'hlfv1'
});
networkAdmin = new IdCard({userName: 'jim', businessNetwork: 'penguin-network'}, {
name: 'mycp',
type: 'hlfv1'
});
identityCardService.addIdentityCard(currentIdCard, null).then((cardRef) => {
currentCardRef = cardRef;
return identityCardService.setCurrentIdentityCard(cardRef);
}).then(() => {
return identityCardService.addIdentityCard(cardOne, 'cardOne');
}).then(() => {
return identityCardService.addIdentityCard(networkAdmin, 'networkAdmin');
});
tick();
})));
describe('ngOnInit', () => {
it('should create the component', () => {
component.should.be.ok;
});
it('should load the identities', fakeAsync(() => {
let myLoadIdentitiesMock = sinon.stub(component, 'loadAllIdentities');
myLoadIdentitiesMock.returns(Promise.resolve());
fixture.detectChanges();
tick();
}));
it('should give an alert if there is an error', fakeAsync(inject([AlertService], (alertService: AlertService) => {
mockBusinessNetworkConnection.getIdentityRegistry.rejects('some error');
let alertSpy = sinon.spy(alertService.errorStatus$, 'next');
fixture.detectChanges();
tick();
alertSpy.should.have.been.called;
})));
});
describe('loadAllIdentities', () => {
it('should load all the identities and handle those bound to participants not found', fakeAsync(() => {
let myLoadParticipantsMock = sinon.stub(component, 'loadParticipants');
let myGetParticipantMock = sinon.stub(component, 'getParticipant');
myLoadParticipantsMock.returns(Promise.resolve());
myGetParticipantMock.onFirstCall().returns(true);
myGetParticipantMock.onSecondCall().returns(false);
myGetParticipantMock.onThirdCall().returns(true);
component.loadAllIdentities();
tick();
component['businessNetworkName'].should.equal('penguin-network');
myLoadParticipantsMock.should.have.been.called;
component['allIdentities'].length.should.deep.equal(4);
component['allIdentities'][0]['ref'].should.deep.equal('bob@penguin-network');
component['allIdentities'][0].should.not.have.property('state');
component['allIdentities'][1]['ref'].should.deep.equal('cardOne');
component['allIdentities'][1]['state'].should.deep.equal('BOUND PARTICIPANT NOT FOUND');
component['allIdentities'][2]['ref'].should.deep.equal('networkAdmin');
component['allIdentities'][2].should.not.have.property('state');
component['allIdentities'][3]['name'].should.deep.equal('tony');
component['allIdentities'][3].should.not.have.property('state');
component['currentIdentity'].should.deep.equal(currentCardRef);
component['identityCards'].size.should.deep.equal(3);
component['identityCards'].get(currentCardRef).should.deep.equal(currentIdCard);
component['identityCards'].get('cardOne').should.deep.equal(cardOne);
component['myIDs'].length.should.deep.equal(3);
component['myIDs'][0]['ref'].should.deep.equal('bob@penguin-network');
component['myIDs'][0]['usable'].should.deep.equal(true);
component['myIDs'][1]['ref'].should.deep.equal('cardOne');
component['myIDs'][1]['usable'].should.deep.equal(false);
component['myIDs'][2]['ref'].should.deep.equal('networkAdmin');
component['myIDs'][2]['usable'].should.deep.equal(true);
}));
it('should give an alert if there is an error', fakeAsync(inject([AlertService], (alertService: AlertService) => {
mockBusinessNetworkConnection.getIdentityRegistry.rejects('some error');
let alertSpy = sinon.spy(alertService.errorStatus$, 'next');
component.loadAllIdentities();
tick();
alertSpy.should.have.been.called;
})));
});
describe('issueNewId', () => {
let sandbox = sinon.sandbox.create();
let saveAsStub;
beforeEach(fakeAsync(() => {
mockModal.open.reset();
saveAsStub = sandbox.stub(fileSaver, 'saveAs');
}));
afterEach(() => {
sandbox.restore();
});
it('should show the new id', fakeAsync(inject([AlertService], (alertService: AlertService) => {
mockModal.open.onFirstCall().returns({
componentInstance: {},
result: Promise.resolve({userID: 'fred', userSecret: 'mySecret'})
});
mockModal.open.onSecondCall().returns({
componentInstance: {},
result: Promise.resolve({cardRef: 'cardOne', choice: 'add'})
});
let loadAllSpy = sinon.spy(component, 'loadAllIdentities');
let alertSpy = sinon.spy(alertService.successStatus$, 'next');
alertService.successStatus$.subscribe((message) => {
if (message) {
message.should.deep.equal({
title: 'ID Card added to wallet',
text: 'The ID card fred was successfully added to your wallet',
icon: '#icon-role_24'
});
}
});
fixture.detectChanges();
tick();
let issuedIdElement = fixture.debugElement.query(By.css('.flex-container button.secondary'));
issuedIdElement.triggerEventHandler('click', null);
tick();
alertSpy.should.have.been.called;
loadAllSpy.should.have.been.called;
})));
it('should export the new id', fakeAsync(() => {
// TODO: make this work with the real toArchive - can't get the promise to resolve properly
let expectedFile = new Blob(['card data'], {type: 'application/octet-stream'});
sinon.stub(cardOne, 'toArchive').resolves(expectedFile);
mockModal.open.onFirstCall().returns({
componentInstance: {},
result: Promise.resolve({userID: 'fred', userSecret: 'mySecret'})
});
mockModal.open.onSecondCall().returns({
componentInstance: {},
result: Promise.resolve({card: cardOne, choice: 'export'})
});
let loadAllSpy = sinon.spy(component, 'loadAllIdentities');
fixture.detectChanges();
tick();
let issuedIdElement = fixture.debugElement.query(By.css('.flex-container button.secondary'));
issuedIdElement.triggerEventHandler('click', null);
tick();
saveAsStub.should.have.been.calledWith(expectedFile, 'fred.card');
loadAllSpy.should.have.been.called;
}));
it('should add id to wallet when using the web profile', fakeAsync(inject([IdentityCardService, AlertService], (identityCardService: IdentityCardService, alertService: AlertService) => {
let myLoadParticipantsMock = sinon.stub(component, 'loadParticipants');
let myGetParticipantMock = sinon.stub(component, 'getParticipant');
myLoadParticipantsMock.returns(Promise.resolve());
myGetParticipantMock.returns(true);
let newCurrentIdCard = new IdCard({userName: 'penguinWeb', businessNetwork: 'igloo-network'}, {
'name': 'mycp',
'x-type': 'web'
});
identityCardService.addIdentityCard(newCurrentIdCard, 'webCard').then((cardRef) => {
currentCardRef = cardRef;
return identityCardService.setCurrentIdentityCard(cardRef);
});
tick();
mockModal.open.onFirstCall().returns({
componentInstance: {},
result: Promise.resolve({userID: 'snowMan', userSecret: 'mySecret'})
});
let alertSpy = sinon.spy(alertService.successStatus$, 'next');
alertService.successStatus$.subscribe((message) => {
if (message) {
message.should.deep.equal({
title: 'ID Card added to wallet',
text: 'The ID card snowMan was successfully added to your wallet',
icon: '#icon-role_24'
});
}
});
fixture.detectChanges();
tick();
let issuedIdElement = fixture.debugElement.query(By.css('.flex-container button.secondary'));
issuedIdElement.triggerEventHandler('click', null);
tick();
alertSpy.should.have.been.called;
component['identityCards'].size.should.equal(2);
component['identityCards'].get('snowMan@igloo-network').getUserName().should.equal('snowMan');
})));
it('should handle error with issuing id', fakeAsync(inject([AlertService], (alertService: AlertService) => {
let myLoadParticipantsMock = sinon.stub(component, 'loadParticipants');
let myGetParticipantMock = sinon.stub(component, 'getParticipant');
myLoadParticipantsMock.returns(Promise.resolve());
myGetParticipantMock.returns(true);
fixture.detectChanges();
tick();
mockModal.open.onFirstCall().returns({
componentInstance: {},
result: Promise.reject('some error')
});
let alertSpy = sinon.spy(alertService.errorStatus$, 'next');
alertService.errorStatus$.subscribe((message) => {
if (message) {
message.should.deep.equal('some error');
}
});
let issuedIdElement = fixture.debugElement.query(By.css('.flex-container button.secondary'));
issuedIdElement.triggerEventHandler('click', null);
tick();
alertSpy.should.have.been.called;
})));
it('should handle esc being pressed', fakeAsync(inject([AlertService], (alertService: AlertService) => {
let myLoadParticipantsMock = sinon.stub(component, 'loadParticipants');
let myGetParticipantMock = sinon.stub(component, 'getParticipant');
myLoadParticipantsMock.returns(Promise.resolve());
myGetParticipantMock.returns(true);
fixture.detectChanges();
tick();
mockModal.open.onFirstCall().returns({
componentInstance: {},
result: Promise.reject(1)
});
let alertSpy = sinon.spy(alertService.errorStatus$, 'next');
let issuedIdElement = fixture.debugElement.query(By.css('.flex-container button.secondary'));
issuedIdElement.triggerEventHandler('click', null);
tick();
alertSpy.should.not.have.been.called;
})));
it('should handle error with reloading', fakeAsync(inject([AlertService], (alertService: AlertService) => {
let myLoadParticipantsMock = sinon.stub(component, 'loadParticipants');
let myGetParticipantMock = sinon.stub(component, 'getParticipant');
myLoadParticipantsMock.returns(Promise.resolve());
myGetParticipantMock.returns(true);
fixture.detectChanges();
tick();
mockModal.open.onFirstCall().returns({
componentInstance: {},
result: Promise.resolve({userID: 'fred', userSecret: 'mySecret'})
});
mockModal.open.onSecondCall().returns({
componentInstance: {},
result: Promise.resolve({cardRef: 'cardOne', choice: 'add'})
});
let loadAllSpy = sinon.stub(component, 'loadAllIdentities').returns(Promise.reject('some error'));
let alertSpy = sinon.spy(alertService.errorStatus$, 'next');
alertService.errorStatus$.subscribe((message) => {
if (message) {
message.should.deep.equal('some error');
}
});
let issuedIdElement = fixture.debugElement.query(By.css('.flex-container button.secondary'));
issuedIdElement.triggerEventHandler('click', null);
tick();
alertSpy.should.have.been.called;
loadAllSpy.should.have.been.called;
})));
});
describe('setCurrentIdentity', () => {
it('should set the current identity', fakeAsync(inject([AlertService], (alertService: AlertService) => {
let myLoadParticipantsMock = sinon.stub(component, 'loadParticipants');
let myGetParticipantMock = sinon.stub(component, 'getParticipant');
myLoadParticipantsMock.returns(Promise.resolve());
myGetParticipantMock.returns(true);
fixture.detectChanges();
tick();
fixture.detectChanges();
tick();
let identityElements = fixture.debugElement.queryAll(By.css('.identity'));
let identityToChangeToElement = identityElements[1];
let alertSpy = sinon.spy(alertService.busyStatus$, 'next');
let loadAllIdentitiesSpy = sinon.spy(component, 'loadAllIdentities');
alertService.busyStatus$.subscribe((message) => {
if (message) {
message.should.deep.equal({
title: 'Reconnecting...',
text: 'Using identity cardOne'
});
}
});
identityToChangeToElement.triggerEventHandler('dblclick', null);
fixture.detectChanges();
tick();
alertSpy.should.have.been.called;
loadAllIdentitiesSpy.should.have.been.called;
})));
it('should do nothing if the new identity matches the current identity', fakeAsync(inject([AlertService], (alertService: AlertService) => {
let myLoadParticipantsMock = sinon.stub(component, 'loadParticipants');
let myGetParticipantMock = sinon.stub(component, 'getParticipant');
myLoadParticipantsMock.returns(Promise.resolve());
myGetParticipantMock.returns(true);
fixture.detectChanges();
tick();
fixture.detectChanges();
tick();
let identityElements = fixture.debugElement.queryAll(By.css('.identity'));
let identityToChangeToElement = identityElements[0];
let alertSpy = sinon.spy(alertService.busyStatus$, 'next');
let loadAllIdentitiesSpy = sinon.spy(component, 'loadAllIdentities');
identityToChangeToElement.triggerEventHandler('dblclick', null);
fixture.detectChanges();
tick();
alertSpy.should.not.have.been.called;
loadAllIdentitiesSpy.should.not.have.been.called;
})));
it('should do nothing if the new identity is not usable', fakeAsync(inject([AlertService], (alertService: AlertService) => {
let myLoadParticipantsMock = sinon.stub(component, 'loadParticipants');
let myGetParticipantMock = sinon.stub(component, 'getParticipant');
myLoadParticipantsMock.returns(Promise.resolve());
myGetParticipantMock.onFirstCall().returns(true);
myGetParticipantMock.onSecondCall().returns(false);
fixture.detectChanges();
tick();
fixture.detectChanges();
tick();
let identityElements = fixture.debugElement.queryAll(By.css('.identity'));
let identityToChangeToElement = identityElements[1];
let alertSpy = sinon.spy(alertService.busyStatus$, 'next');
let loadAllIdentitiesSpy = sinon.spy(component, 'loadAllIdentities');
identityToChangeToElement.triggerEventHandler('dblclick', null);
fixture.detectChanges();
tick();
alertSpy.should.not.have.been.called;
loadAllIdentitiesSpy.should.not.have.been.called;
})));
it('should handle errors and revert to previous on error', fakeAsync(inject([AlertService], (alertService: AlertService) => {
let myLoadParticipantsMock = sinon.stub(component, 'loadParticipants');
let myGetParticipantMock = sinon.stub(component, 'getParticipant');
myLoadParticipantsMock.returns(Promise.resolve());
myGetParticipantMock.returns(true);
fixture.detectChanges();
tick();
fixture.detectChanges();
tick();
let identityElements = fixture.debugElement.queryAll(By.css('.identity'));
let identityToChangeToElement = identityElements[1];
let alertSpy = sinon.spy(alertService.errorStatus$, 'next');
alertService.errorStatus$.subscribe((message) => {
if (message) {
message.should.deep.equal('some error');
}
});
mockClientService.ensureConnected.returns(Promise.reject('some error'));
identityToChangeToElement.triggerEventHandler('dblclick', null);
fixture.detectChanges();
tick();
alertSpy.should.have.been.called;
})));
});
describe('openRemoveModal', () => {
it('should open the delete-confirm modal and handle error', fakeAsync(inject([AlertService], (alertService: AlertService) => {
let myLoadParticipantsMock = sinon.stub(component, 'loadParticipants');
let myGetParticipantMock = sinon.stub(component, 'getParticipant');
myLoadParticipantsMock.returns(Promise.resolve());
myGetParticipantMock.returns(true);
fixture.detectChanges();
tick();
fixture.detectChanges();
tick();
mockModal.open = sinon.stub().returns({
componentInstance: {},
result: Promise.reject('some error')
});
let alertSpy = sinon.spy(alertService.errorStatus$, 'next');
alertService.errorStatus$.subscribe((message) => {
if (message) {
message.should.equal('some error');
}
});
let identityElement = fixture.debugElement.queryAll(By.css('.identity'))[1];
let removeButton = identityElement.queryAll(By.css('button'))[1];
removeButton.triggerEventHandler('click', {stopPropagation : sinon.stub()});
tick();
alertSpy.should.have.been.called;
})));
it('should open the delete-confirm modal and handle cancel', fakeAsync(inject([AlertService], (alertService: AlertService) => {
let myLoadParticipantsMock = sinon.stub(component, 'loadParticipants');
let myGetParticipantMock = sinon.stub(component, 'getParticipant');
myLoadParticipantsMock.returns(Promise.resolve());
myGetParticipantMock.returns(true);
fixture.detectChanges();
tick();
fixture.detectChanges();
tick();
mockModal.open = sinon.stub().returns({
componentInstance: {},
result: Promise.reject(1)
});
let alertSpy = sinon.spy(alertService.errorStatus$, 'next');
let identityElement = fixture.debugElement.queryAll(By.css('.identity'))[1];
let removeButton = identityElement.queryAll(By.css('button'))[1];
removeButton.triggerEventHandler('click', {stopPropagation : sinon.stub()});
tick();
alertSpy.should.not.have.been.called;
})));
it('should open the delete-confirm modal and handle remove press', fakeAsync(inject([AlertService], (alertService: AlertService) => {
let myLoadParticipantsMock = sinon.stub(component, 'loadParticipants');
let myGetParticipantMock = sinon.stub(component, 'getParticipant');
myLoadParticipantsMock.returns(Promise.resolve());
myGetParticipantMock.returns(true);
fixture.detectChanges();
tick();
fixture.detectChanges();
tick();
mockModal.open = sinon.stub().returns({
componentInstance: {},
result: Promise.resolve()
});
let alertSpy = sinon.spy(alertService.successStatus$, 'next');
alertService.successStatus$.subscribe((message) => {
if (message) {
message.should.deep.equal({
title: 'Removal Successful',
text: 'fred was successfully removed.',
icon: '#icon-bin_icon'
});
}
});
let identityElement = fixture.debugElement.queryAll(By.css('.identity'))[1];
let removeButton = identityElement.queryAll(By.css('button'))[1];
removeButton.triggerEventHandler('click', {stopPropagation: sinon.stub()});
tick();
alertSpy.should.have.been.called;
should.not.exist(component['identityCards'].get('cardOne'));
})));
it('should handle error on trying to remove', fakeAsync(inject([AlertService, IdentityCardService], (alertService: AlertService, identityCardService: IdentityCardService) => {
let myLoadParticipantsMock = sinon.stub(component, 'loadParticipants');
let myGetParticipantMock = sinon.stub(component, 'getParticipant');
myLoadParticipantsMock.returns(Promise.resolve());
myGetParticipantMock.returns(true);
fixture.detectChanges();
tick();
fixture.detectChanges();
tick();
sinon.stub(identityCardService, 'deleteIdentityCard').returns(Promise.reject('some error'));
mockModal.open = sinon.stub().returns({
componentInstance: {},
result: Promise.resolve()
});
let alertSpy = sinon.spy(alertService.errorStatus$, 'next');
alertService.errorStatus$.subscribe((message) => {
if (message) {
message.should.deep.equal('some error');
}
});
let identityElement = fixture.debugElement.queryAll(By.css('.identity'))[1];
let removeButton = identityElement.queryAll(By.css('button'))[1];
removeButton.triggerEventHandler('click', {stopPropagation: sinon.stub()});
tick();
alertSpy.should.have.been.called;
should.exist(component['identityCards'].get('cardOne'));
})));
});
describe('revokeIdentity', () => {
it('should open the delete-confirm modal and revoke the id', fakeAsync(inject([AlertService], (alertService: AlertService) => {
let myLoadParticipantsMock = sinon.stub(component, 'loadParticipants');
let myGetParticipantMock = sinon.stub(component, 'getParticipant');
myLoadParticipantsMock.returns(Promise.resolve());
myGetParticipantMock.returns(true);
fixture.detectChanges();
tick();
fixture.detectChanges();
tick();
mockModal.open = sinon.stub().returns({
componentInstance: {},
result: Promise.resolve()
});
let alertSpy = sinon.spy(alertService.successStatus$, 'next');
alertService.successStatus$.subscribe((message) => {
if (message) {
message.should.deep.equal({
title: 'Revoke Successful',
text: 'fred was successfully revoked.',
icon: '#icon-bin_icon'
});
}
});
let revokeElement = fixture.debugElement.queryAll(By.css('.identity'))[4];
let revokeButton = revokeElement.query(By.css('button'));
revokeButton.triggerEventHandler('click', null);
tick();
alertSpy.should.have.been.called;
should.not.exist(component['identityCards'].get('cardOne'));
})));
it('should open the delete-confirm modal and revoke the id and handle not being in wallet', fakeAsync(inject([AlertService, IdentityCardService], (alertService: AlertService, identityCardService: IdentityCardService) => {
let myLoadParticipantsMock = sinon.stub(component, 'loadParticipants');
let myGetParticipantMock = sinon.stub(component, 'getParticipant');
myLoadParticipantsMock.returns(Promise.resolve());
myGetParticipantMock.returns(true);
fixture.detectChanges();
tick();
fixture.detectChanges();
tick();
fixture.detectChanges();
mockModal.open = sinon.stub().returns({
componentInstance: {},
result: Promise.resolve()
});
let deleteSpy = sinon.spy(identityCardService, 'deleteIdentityCard');
let alertSpy = sinon.spy(alertService.successStatus$, 'next');
alertService.successStatus$.subscribe((message) => {
if (message) {
message.should.deep.equal({
title: 'Revoke Successful',
text: 'jim was successfully revoked.',
icon: '#icon-bin_icon'
});
}
});
let revokeElement = fixture.debugElement.queryAll(By.css('.identity'))[6];
// NEED TO MAKE A NEW PARTICIPANT (AFTER JIM) WHO WILL NOT BE ADDED TO THE WALLET
let revokeButton = revokeElement.query(By.css('button'));
revokeButton.triggerEventHandler('click', null);
tick();
alertSpy.should.have.been.called;
deleteSpy.should.not.have.been.called;
})));
it('should open the delete-confirm modal and handle error', fakeAsync(inject([AlertService], (alertService: AlertService) => {
let myLoadParticipantsMock = sinon.stub(component, 'loadParticipants');
let myGetParticipantMock = sinon.stub(component, 'getParticipant');
myLoadParticipantsMock.returns(Promise.resolve());
myGetParticipantMock.returns(true);
fixture.detectChanges();
tick();
fixture.detectChanges();
tick();
fixture.detectChanges();
mockModal.open = sinon.stub().returns({
componentInstance: {},
result: Promise.reject('some error')
});
let alertSpy = sinon.spy(alertService.errorStatus$, 'next');
alertService.errorStatus$.subscribe((message) => {
if (message) {
message.should.deep.equal('some error');
}
});
let revokeElement = fixture.debugElement.queryAll(By.css('.identity'))[4];
let revokeButton = revokeElement.query(By.css('button'));
revokeButton.triggerEventHandler('click', null);
tick();
alertSpy.should.have.been.called;
should.exist(component['identityCards'].get('cardOne'));
})));
it('should open the delete-confirm modal and handle cancel', fakeAsync(inject([AlertService], (alertService: AlertService) => {
let myLoadParticipantsMock = sinon.stub(component, 'loadParticipants');
let myGetParticipantMock = sinon.stub(component, 'getParticipant');
myLoadParticipantsMock.returns(Promise.resolve());
myGetParticipantMock.returns(true);
fixture.detectChanges();
tick();
fixture.detectChanges();
tick();
fixture.detectChanges();
mockModal.open = sinon.stub().returns({
componentInstance: {},
result: Promise.reject(1)
});
let alertSpy = sinon.spy(alertService.errorStatus$, 'next');
let revokeElement = fixture.debugElement.queryAll(By.css('.identity'))[4];
let revokeButton = revokeElement.query(By.css('button'));
revokeButton.triggerEventHandler('click', null);
tick();
alertSpy.should.not.have.been.called;
should.exist(component['identityCards'].get('cardOne'));
})));
it('should handle error', fakeAsync(inject([AlertService], (alertService: AlertService) => {
let myLoadParticipantsMock = sinon.stub(component, 'loadParticipants');
let myGetParticipantMock = sinon.stub(component, 'getParticipant');
myLoadParticipantsMock.returns(Promise.resolve());
myGetParticipantMock.returns(true);
fixture.detectChanges();
tick();
fixture.detectChanges();
tick();
fixture.detectChanges();
mockModal.open = sinon.stub().returns({
componentInstance: {},
result: Promise.resolve()
});
let alertSpy = sinon.spy(alertService.errorStatus$, 'next');
alertService.errorStatus$.subscribe((message) => {
if (message) {
message.should.deep.equal('some error');
}
});
mockClientService.revokeIdentity.returns(Promise.reject('some error'));
let revokeElement = fixture.debugElement.queryAll(By.css('.identity'))[4];
let revokeButton = revokeElement.query(By.css('button'));
revokeButton.triggerEventHandler('click', null);
tick();
alertSpy.should.have.been.called;
})));
});
describe('#loadParticipants', () => {
it('should create a map of participants', fakeAsync(() => {
let mockParticpantRegistry = sinon.createStubInstance(ParticipantRegistry);
let mockParticipant1 = sinon.createStubInstance(Resource);
mockParticipant1.getFullyQualifiedIdentifier.returns('org.animals.Penguin#Emperor');
let mockParticipant2 = sinon.createStubInstance(Resource);
mockParticipant2.getFullyQualifiedIdentifier.returns('org.animals.Penguin#King');
mockParticpantRegistry.getAll.returns([mockParticipant2, mockParticipant1]);
mockBusinessNetworkConnection.getAllParticipantRegistries.returns(Promise.resolve([mockParticpantRegistry]));
component['loadParticipants']();
tick();
let expected = new Map();
expected.set('org.animals.Penguin#Emperor', new Resource());
expected.set('org.animals.Penguin#King', new Resource());
component['participants'].should.deep.equal(expected);
}));
it('should alert if there is an error', fakeAsync(inject([AlertService], (alertService: AlertService) => {
mockBusinessNetworkConnection.getAllParticipantRegistries.returns(Promise.reject('some error'));
let alertSpy = sinon.spy(alertService.errorStatus$, 'next');
alertService.errorStatus$.subscribe((message) => {
if (message) {
message.should.deep.equal('some error');
}
});
component['loadParticipants']();
tick();
alertSpy.should.have.been.called;
})));
});
describe('#getParticipant', () => {
it('should get the specified participant', () => {
let mockParticipant1 = sinon.createStubInstance(Resource);
mockParticipant1.getFullyQualifiedIdentifier.returns('org.animals.Penguin#Emperor');
mockParticipant1.getIdentifier.returns('Emperor');
mockParticipant1.getType.returns('org.animals.Penguin');
let mockParticipant2 = sinon.createStubInstance(Resource);
mockParticipant2.getFullyQualifiedIdentifier.returns('org.animals.Penguin#King');
mockParticipant2.getIdentifier.returns('King');
mockParticipant2.getType.returns('org.animals.Penguin');
let mockParticipant3 = sinon.createStubInstance(Resource);
mockParticipant3.getFullyQualifiedIdentifier.returns('org.animals.Penguin#Macaroni');
mockParticipant3.getIdentifier.returns('Macaroni');
mockParticipant3.getType.returns('org.animals.Penguin');
component['participants'].set('Emperor', mockParticipant1);
component['participants'].set('King', mockParticipant2);
component['participants'].set('Macaroni', mockParticipant2);
let participant = component['getParticipant']('King');
participant.getIdentifier().should.equal('King');
participant.getType().should.equal('org.animals.Penguin');
});
});
}); | the_stack |
import {
TextRange, Position, TextProcessor, TextProcessingOptions,
TextResult, KeyCode
} from "./common"
import { Deasciifier, Asciifier } from "./deasciifier"
import { CorrectionCallback, CorrectionMenu } from "./correction_menu"
import { KeyboardCallback, Keyboard } from "./keyboard"
import { TextHelper } from "./text_helper"
import { DomElementImpl, DomFactoryImpl } from "./dom";
import { DomFactory, DomElement } from "./view";
import { KeyboardLayout } from "./keyboard_layout_turkish"
class AppOptions {
public constructor(public highlightChanges: boolean,
public enableCorrectionMenu: boolean,
public enableAutoConvert: boolean) { }
}
interface TextEditor {
getText(): string;
setText(text: string, range?: TextRange): void;
getSelection(): TextRange;
setSelection(range: TextRange): void;
highlight(range: TextRange, cssName: string): any;
// Use this for multiple markers.
highlightMultiple(ranges: TextRange[], cssName: string): void;
clearHighlights(range: TextRange): void;
// Returns absolute coordinates of the character at |index|.
getPosition(index: number): Position;
// Returns the line height in pixel.
getLineHeight(): number;
// Simulates typing |text| at the cursor position.
putAtCursor(text: string): void;
// Simulates pressing backspace key at the cursor position.
deleteCursor(): void;
// Set focus to the editor.
focus(): void;
}
interface TextEditorEventListener {
onKeyUp(keyCode: number): void;
onClick(): void;
}
class CodeMirrorEditor implements TextEditor {
constructor(
private editor: any, private eventListener: TextEditorEventListener) {
editor.getWrapperElement().onkeyup = function (e: any) {
eventListener.onKeyUp(e.keyCode);
}
editor.getWrapperElement().onclick = function (e: any) {
eventListener.onClick();
}
}
public setText(text: string, range?: TextRange) {
if (range) {
let rangeStart = this.editor.posFromIndex(range.start);
let rangeEnd = this.editor.posFromIndex(range.end);
this.editor.replaceRange(text, rangeStart, rangeEnd);
} else {
this.editor.setValue(text);
}
}
public getText(): string {
return this.editor.getValue();
}
public getSelection(): TextRange {
let start = this.editor.indexFromPos(this.editor.getCursor(true));
let end = this.editor.indexFromPos(this.editor.getCursor(false));
return new TextRange(start, end);
}
public setSelection(range: TextRange) {
let rangeStart = this.editor.posFromIndex(range.start);
let rangeEnd = this.editor.posFromIndex(range.end);
this.editor.setSelection(rangeStart, rangeEnd);
}
public highlight(range: TextRange, cssName: string) {
let rangeStart = this.editor.posFromIndex(range.start);
let rangeEnd = this.editor.posFromIndex(range.end);
return this.editor.markText(
rangeStart, rangeEnd,
{ readOnly: false, className: cssName });
}
public highlightMultiple(ranges: TextRange[], cssName: string) {
let self = this;
this.editor.operation(function () {
for (let range of ranges) {
self.highlight(range, cssName);
}
});
}
public clearHighlights(range: TextRange) {
let rangeStart = this.editor.posFromIndex(range.start);
let rangeEnd = this.editor.posFromIndex(range.end);
let marks = this.editor.findMarks(rangeStart, rangeEnd);
for (let mark of marks) {
mark.clear();
}
}
public getPosition(index: number): Position {
let linech = this.editor.posFromIndex(index);
let coords = this.editor.charCoords(linech);
return <Position>{ left: coords.left, top: coords.top };
}
public getLineHeight(): number {
return this.editor.defaultTextHeight();
}
public putAtCursor(text: string) {
let selection = this.getSelection();
this.setText(text, selection);
}
public deleteCursor(): void {
this.editor.execCommand("delCharBefore");
}
public focus(): void {
this.editor.focus();
}
}
enum TextProcessorMode {
DEASCIIFY,
ASCIIFY
}
class DeasciifyProcessor implements TextProcessor {
private processor: TextProcessor;
constructor(
private deasciifier: Deasciifier, private asciifier: Asciifier) {
this.processor = deasciifier;
}
public setMode(mode: TextProcessorMode) {
if (mode == TextProcessorMode.DEASCIIFY)
this.processor = this.deasciifier;
else
this.processor = this.asciifier;
}
public processRange(
text: string, range: TextRange,
options: TextProcessingOptions): TextResult {
return this.processor.processRange(text, range, options);
}
public process(text: string, options: TextProcessingOptions): TextResult {
return this.processor.process(text, options);
}
}
class CorrectionCallbackImpl implements CorrectionCallback {
constructor(private box: DeasciiBox) { }
onchange(text: string) {
this.box.oncorrectiontextchange(text);
}
}
class DeasciiBox {
private app_options_: AppOptions;
private processing_options_ : TextProcessingOptions;
private correctionMenu: CorrectionMenu;
private correctionMenuSelection: TextRange;
private correctionMenuHighlight: any;
constructor(
parent: DomElement,
domFactory: DomFactory,
private textEditor: TextEditor,
private textProcessor: DeasciifyProcessor) {
this.app_options_ = new AppOptions(true, true, true);
// Skip URLs etc.
this.processing_options_ = new TextProcessingOptions(true);
this.correctionMenuSelection = null;
let correctionElement = domFactory.createDiv();
this.correctionMenu =
new CorrectionMenu(correctionElement, new CorrectionCallbackImpl(this), domFactory);
parent.appendChild(correctionElement);
}
public oncorrectiontextchange(text: string) {
this.textEditor.setText(text, this.correctionMenuSelection);
}
public onKeyUp(keyCode: number) {
if (!this.app_options_.enableAutoConvert) {
return;
}
if (TextHelper.isSeparatorChar(String.fromCharCode(keyCode))) {
this.deasciifyCursor();
}
}
public onClick() {
this.hideCorrectionMenu();
if (!this.app_options_.enableCorrectionMenu) {
return;
}
let selectionRange = this.textEditor.getSelection();
// If the user double clicks on a word, the word will be selected and start
// and end will be different. Don't do anything in that case.
if (selectionRange.start != selectionRange.end) {
return;
}
let cursorPos = selectionRange.start;
let text: string = this.textEditor.getText();
// Only show the menu if we are in the middle of a word
if (!TextHelper.isCursorInsideWord(text, cursorPos)) {
return;
}
let wordBoundary = TextHelper.getWordAtCursor(text, cursorPos);
let wordText = text.substring(wordBoundary.start, wordBoundary.end);
// Don't show menu if there is nothing to suggest
if (!CorrectionMenu.hasCorrections(wordText)) {
return;
}
let startCoords = this.textEditor.getPosition(wordBoundary.start);
let endCoords = this.textEditor.getPosition(wordBoundary.end);
let middleX = (startCoords.left + endCoords.left) / 2;
let menuCoords = <Position>{
left: middleX,
top: startCoords.top + this.textEditor.getLineHeight()
}
this.correctionMenuSelection = wordBoundary;
this.correctionMenu.show(menuCoords, wordText);
this.correctionMenuHighlight =
this.textEditor.highlight(wordBoundary, "correction-menu-selection");
}
private deasciifyCursor() {
let selectionRange = this.textEditor.getSelection();
let rangeToDeasciify: TextRange = null;
let text = this.textEditor.getText();
if (selectionRange.start == selectionRange.end) {
// No text selected. Get the boundaries of the last word that is
// separated by space, enter etc.
rangeToDeasciify =
TextHelper.getWordBeforeCursor(text, selectionRange.start);
} else {
// A portion of the text is already selected. Deasciify only the
// selected part.
rangeToDeasciify = selectionRange;
}
// Deasciify the range.
let result =
this.textProcessor.processRange(text, rangeToDeasciify, this.processing_options_);
// Highlight the results.
this.displayResult(result);
// Restore cursor.
this.textEditor.setSelection(selectionRange);
}
/** Displays the conversion results in the textbox and highlights the
* converted characters if necessary.
*/
private displayResult(result: TextResult) {
if (result && result.text) {
this.textEditor.setText(result.text);
this.highlightChanges(result.changedPositions, false);
}
}
private highlightChanges(
changedPositions: Array<number>, forceClear: boolean) {
// Highlight results.
if (!this.app_options_.highlightChanges) {
return;
}
if ((!changedPositions || changedPositions.length == 0) && !forceClear) {
return;
}
//this.textEditor.clearHighlights();
let ranges: TextRange[] = [];
for (let i = 0; i < changedPositions.length; i++) {
ranges.push(new TextRange(changedPositions[i], changedPositions[i] + 1));
}
this.textEditor.highlightMultiple(ranges, "deasciifier-highlight");
}
public hideCorrectionMenu() {
this.correctionMenu.hide();
if (this.correctionMenuSelection) {
this.textEditor.clearHighlights(this.correctionMenuSelection);
}
if (this.correctionMenuHighlight) {
this.correctionMenuHighlight.clear();
}
}
public processSelection(mode: TextProcessorMode) {
let range = this.textEditor.getSelection();
if (range.start == range.end) {
range = <TextRange>{ start: 0, end: this.textEditor.getText().length };
}
this.textProcessor.setMode(mode);
let result =
this.textProcessor.processRange(this.textEditor.getText(), range, this.processing_options_);
this.textEditor.setText(
result.text.substring(range.start, range.end), range);
this.highlightChanges(result.changedPositions, false);
return result;
}
public setEnableCorrectionMenu(enabled: boolean) {
if (!enabled) {
this.hideCorrectionMenu();
}
this.app_options_.enableCorrectionMenu = enabled;
}
public setEnableAutoConvert(enabled: boolean) {
this.app_options_.enableAutoConvert = enabled;
}
}
class KeyboardHandler implements KeyboardCallback {
constructor(private app: App, private editor: TextEditor) { }
onKey(key: string) {
this.app.hideCorrectionMenu();
this.editor.focus();
if (key == "backspace") {
this.editor.deleteCursor();
return;
}
this.editor.putAtCursor(key);
}
}
// The actual app.
export class App implements TextEditorEventListener {
private textEditor: TextEditor;
private deasciiBox: DeasciiBox;
private keyboardHandler: KeyboardHandler;
private deasciifier_instance: Deasciifier;
private asciifier_instance: Asciifier;
private keyboard: Keyboard;
constructor(
codemirror: any,
pattern_list: any,
parentContainer: HTMLElement,
keyboardContainer: HTMLElement,
domFactory: DomFactory = new DomFactoryImpl()) {
this.deasciifier_instance = new Deasciifier();
this.deasciifier_instance.init(pattern_list);
this.asciifier_instance = new Asciifier();
let parent: DomElement = new DomElementImpl(parentContainer);
this.textEditor = new CodeMirrorEditor(codemirror, this);
this.deasciiBox =
new DeasciiBox(
parent,
domFactory,
this.textEditor,
new DeasciifyProcessor(
this.deasciifier_instance, this.asciifier_instance));
let keyboard_container = new DomElementImpl(keyboardContainer);
this.keyboard = new Keyboard(
KeyboardLayout['TR_Q'],
keyboard_container, domFactory);
parent.appendChild(keyboard_container);
this.keyboardHandler = new KeyboardHandler(this, this.textEditor);
this.keyboard.create(this.keyboardHandler);
}
public deasciifySelection() {
return this.deasciiBox.processSelection(TextProcessorMode.DEASCIIFY);
}
public asciifySelection() {
return this.deasciiBox.processSelection(TextProcessorMode.ASCIIFY);
}
public hideCorrectionMenu() {
this.deasciiBox.hideCorrectionMenu();
}
public onKeyUp(keyCode: number) {
this.deasciiBox.onKeyUp(keyCode);
}
public onClick() {
this.deasciiBox.onClick();
}
public setEnableCorrectionMenu(enabled: boolean) {
this.deasciiBox.setEnableCorrectionMenu(enabled);
}
public setEnableAutoConvert(enabled: boolean) {
this.deasciiBox.setEnableAutoConvert(enabled);
}
} | the_stack |
import { promises as fs } from 'fs'
import path from 'path'
import { isArray, isBoolean, isEmptyObject, isString } from '@intlify/shared'
import { createFilter } from '@rollup/pluginutils'
import {
generateJSON,
generateYAML,
checkInstallPackage
} from '@intlify/bundle-utils'
import fg from 'fast-glob'
import createDebug from 'debug'
import { normalizePath } from 'vite'
import { RawSourceMap } from 'source-map'
import { parseVueRequest } from './query'
import type { Plugin, ResolvedConfig, UserConfig } from 'vite'
import type { CodeGenOptions, DevEnv } from '@intlify/bundle-utils'
import type { VitePluginVueI18nOptions } from './options'
const debug = createDebug('vite-plugin-vue-i18n:index')
const INTLIFY_BUNDLE_IMPORT_ID = '@intlify/vite-plugin-vue-i18n/messages'
const installedPkg = checkInstallPackage('@intlify/vite-plugin-vue-i18n', debug)
function pluginI18n(
options: VitePluginVueI18nOptions = { forceStringify: false }
): Plugin {
debug('plugin options:', options)
// use `normalizePath` for `options.include`
let include = options.include
if (include) {
if (isArray(include)) {
include = include.map(item => normalizePath(item))
} else if (isString(include)) {
include = normalizePath(include)
}
}
const filter = createFilter(include)
const runtimeOnly = isBoolean(options.runtimeOnly)
? options.runtimeOnly
: true
// prettier-ignore
const compositionOnly = installedPkg === 'vue-i18n'
? isBoolean(options.compositionOnly)
? options.compositionOnly
: true
: true
// prettier-ignore
const fullIinstall = installedPkg === 'vue-i18n'
? isBoolean(options.fullInstall)
? options.fullInstall
: true
: false
const defaultSFCLang = isString(options.defaultSFCLang)
? options.defaultSFCLang
: undefined
const globalSFCScope = !!options.globalSFCScope
const useVueI18nImportName = options.useVueI18nImportName
if (useVueI18nImportName != null) {
console.warn(
`[vite-plugin-vue-i18n]: 'useVueI18nImportName' option is experimental`
)
}
const getAliasName = () =>
installedPkg === 'petite-vue-i18n' &&
isBoolean(useVueI18nImportName) &&
useVueI18nImportName
? 'vue-i18n'
: `${installedPkg}`
const forceStringify = !!options.forceStringify
let isProduction = false
let sourceMap = false
return {
name: 'vite-plugin-vue-i18n',
/**
* NOTE:
* If we have json (including SFC's custom block),
* transform it first because it will be transformed into javascript code by `vite:json` plugin.
*/
enforce: 'pre',
config(config: UserConfig, { command }) {
if (command === 'build' && runtimeOnly) {
normalizeConfigResolveAlias(config)
if (isArray(config.resolve!.alias)) {
config.resolve!.alias.push({
find: getAliasName(),
replacement: `${installedPkg}/dist/${installedPkg}.runtime.esm-bundler.js`
})
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(config.resolve!.alias as any)[
getAliasName()
] = `${installedPkg}/dist/${installedPkg}.runtime.esm-bundler.js`
}
debug(`alias name: ${getAliasName()}`)
debug(
`set ${installedPkg} runtime only: ${installedPkg}/dist/${installedPkg}.runtime.esm-bundler.js`
)
} else if (
command === 'serve' &&
installedPkg === 'petite-vue-i18n' &&
useVueI18nImportName
) {
normalizeConfigResolveAlias(config)
if (isArray(config.resolve!.alias)) {
config.resolve!.alias.push({
find: 'vue-i18n',
replacement: `petite-vue-i18n/dist/petite-vue-i18n.esm-bundler.js`
})
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(config.resolve!.alias as any)[
'vue-i18n'
] = `petite-vue-i18n/dist/petite-vue-i18n.esm-bundler.js`
}
debug(`alias name: ${getAliasName()}`)
}
config.define = config.define || {}
config.define['__VUE_I18N_LEGACY_API__'] = !compositionOnly
debug(
`set __VUE_I18N_LEGACY_API__ is '${config.define['__VUE_I18N_LEGACY_API__']}'`
)
config.define['__VUE_I18N_FULL_INSTALL__'] = fullIinstall
debug(
`set __VUE_I18N_FULL_INSTALL__ is '${config.define['__VUE_I18N_FULL_INSTALL__']}'`
)
config.define['__VUE_I18N_PROD_DEVTOOLS__'] = false
},
configResolved(config: ResolvedConfig) {
isProduction = config.isProduction
sourceMap = config.command === 'build' ? !!config.build.sourcemap : false
// json transform handling
const jsonPlugin = config.plugins.find(p => p.name === 'vite:json')
if (jsonPlugin) {
const orgTransform = jsonPlugin.transform // backup @rollup/plugin-json
jsonPlugin.transform = async function (code: string, id: string) {
if (!/\.json$/.test(id)) {
return null
}
/**
* NOTE:
* `vite:json` plugin will be handled if the query generated from the result of parse SFC
* with `vite:vue` plugin contains json as follows.
* e.g src/components/HelloI18n.vue?vue&type=i18n&index=1&lang.json
*
* To avoid this, return the result that has already been processed (`enforce: 'pre'`) in the wrapped json plugin.
*/
const { query } = parseVueRequest(id)
if (query.vue) {
return Promise.resolve({
code,
map: sourceMap ? this.getCombinedSourcemap() : { mappings: '' }
})
}
if (filter(id)) {
const map = this.getCombinedSourcemap()
debug('override json plugin', code, map)
return Promise.resolve({
code,
map
})
} else {
debug('org json plugin')
return orgTransform!.apply(this, [code, id])
}
}
}
},
resolveId(id: string) {
if (id === INTLIFY_BUNDLE_IMPORT_ID) {
return id
}
},
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async load(id: string, ssr: boolean) {
if (id === INTLIFY_BUNDLE_IMPORT_ID && include) {
let resourcePaths = [] as string[]
const includePaths = isArray(include) ? include : [include]
for (const inc of includePaths) {
resourcePaths = [...(await fg(inc))]
}
const code = await generateBundleResources(
resourcePaths,
isProduction,
forceStringify
)
return Promise.resolve({
code,
map: { mappings: '' }
})
}
},
async handleHotUpdate({ file, server }) {
if (/\.(json5?|ya?ml)$/.test(file)) {
const module = server.moduleGraph.getModuleById(
INTLIFY_BUNDLE_IMPORT_ID
)
if (module) {
server.moduleGraph.invalidateModule(module)
return [module!]
}
}
},
async transform(code: string, id: string) {
const { filename, query } = parseVueRequest(id)
debug('transform', id, JSON.stringify(query))
let langInfo = 'json'
let inSourceMap: RawSourceMap | undefined
if (!query.vue) {
if (/\.(json5?|ya?ml)$/.test(id) && filter(id)) {
langInfo = path.parse(filename).ext
const generate = /\.?json5?/.test(langInfo)
? generateJSON
: generateYAML
const parseOptions = getOptions(
filename,
isProduction,
query as Record<string, unknown>,
sourceMap,
inSourceMap,
globalSFCScope,
forceStringify
) as CodeGenOptions
debug('parseOptions', parseOptions)
const { code: generatedCode, map } = generate(code, parseOptions)
debug('generated code', generatedCode, id)
debug('sourcemap', map, id)
return Promise.resolve({
code: generatedCode,
map: (sourceMap ? map : { mappings: '' }) as any // eslint-disable-line @typescript-eslint/no-explicit-any
})
} else {
return Promise.resolve({
code,
map: sourceMap ? this.getCombinedSourcemap() : { mappings: '' }
})
}
} else {
// for Vue SFC
if (isCustomBlock(query as Record<string, unknown>)) {
if (isString(query.lang)) {
langInfo = query.src
? query.lang === 'i18n'
? 'json'
: query.lang
: query.lang
} else if (defaultSFCLang) {
langInfo = defaultSFCLang
}
const generate = /\.?json5?/.test(langInfo)
? generateJSON
: generateYAML
const parseOptions = getOptions(
filename,
isProduction,
query as Record<string, unknown>,
sourceMap,
inSourceMap,
globalSFCScope,
forceStringify
) as CodeGenOptions
debug('parseOptions', parseOptions)
const { code: generatedCode, map } = generate(code, parseOptions)
debug('generated code', generatedCode, id)
debug('sourcemap', map, id)
return Promise.resolve({
code: generatedCode,
map: (sourceMap ? map : { mappings: '' }) as any // eslint-disable-line @typescript-eslint/no-explicit-any
})
} else {
return Promise.resolve({
code,
map: sourceMap ? this.getCombinedSourcemap() : { mappings: '' }
})
}
}
}
}
}
function normalizeConfigResolveAlias(config: UserConfig): void {
// NOTE: cannot resolve Optional Chaining in jest E2E ...
if (config.resolve && config.resolve.alias) {
return
}
if (!config.resolve) {
config.resolve = { alias: [] }
} else if (!config.resolve.alias) {
config.resolve.alias = []
}
}
async function getRaw(path: string): Promise<string> {
return fs.readFile(path, { encoding: 'utf-8' })
}
function isCustomBlock(query: Record<string, unknown>): boolean {
// NOTE: should be more improvement. difference query type and blocktype in some environment ...
return (
!isEmptyObject(query) &&
'vue' in query &&
(query['type'] === 'custom' ||
query['type'] === 'i18n' ||
query['blockType'] === 'i18n')
)
}
function getOptions(
filename: string,
isProduction: boolean,
query: Record<string, unknown>,
sourceMap: boolean,
inSourceMap: RawSourceMap | undefined,
isGlobal = false,
forceStringify = false
): Record<string, unknown> {
const mode: DevEnv = isProduction ? 'production' : 'development'
const baseOptions = {
filename,
sourceMap,
inSourceMap,
forceStringify,
env: mode,
onWarn: (msg: string): void => {
console.warn(`[vite-plugin-vue-i18n]: ${filename} ${msg}`)
},
onError: (msg: string): void => {
console.error(`[vite-plugin-vue-i18n]: ${filename} ${msg}`)
}
}
if (isCustomBlock(query)) {
return Object.assign(baseOptions, {
type: 'sfc',
locale: isString(query.locale) ? query.locale : '',
isGlobal: isGlobal || query.global != null
})
} else {
return Object.assign(baseOptions, {
type: 'plain',
isGlobal: false
})
}
}
async function generateBundleResources(
resources: string[],
isProduction: boolean,
forceStringify: boolean,
isGlobal = false
) {
const codes = []
for (const res of resources) {
debug(`${res} bundle loading ...`)
if (/\.(json5?|ya?ml)$/.test(res)) {
const { ext, name } = path.parse(res)
const source = await getRaw(res)
const generate = /json5?/.test(ext) ? generateJSON : generateYAML
const parseOptions = getOptions(
res,
isProduction,
{},
false,
undefined,
isGlobal,
forceStringify
) as CodeGenOptions
parseOptions.type = 'bare'
const { code } = generate(source, parseOptions)
debug('generated code', code)
codes.push(`${JSON.stringify(name)}: ${code}`)
}
}
return `export default {
${codes.join(`,\n`)}
}`
}
// overwrite for cjs require('...')() usage
export default pluginI18n
export const vueI18n = pluginI18n | the_stack |
import * as http from "http";
import * as path from "path";
import * as fs from "fs";
import * as url from "url";
import {
File,
BCVE,
CVEString,
CommitID,
CommitDescription,
ToolID,
RuleID,
CWEString
} from "../../../../../src/persistent-types";
import * as ClientTypes from "../shared/shared-types";
function makePermalink(repository: string, commit: CommitID) {
let githubRepoPattern = /^https:\/\/github.com\/([^/]+)\/([^/]+)\.git$/;
let github = repository.match(githubRepoPattern);
if (github) {
let [, owner, repo] = github;
return `https://github.com/${owner}/${repo}/commit/${commit}`;
}
return undefined; // TODO support non-github.com URLs
}
function makeCommitData(
cve: CVEString,
repository: string,
commit: CommitDescription
): ClientTypes.CommitData {
return {
CVE: cve,
commitID: commit.commit,
permalink: makePermalink(repository, commit.commit)
};
}
function buildTargetsMap(bcves: BCVE[]): TargetsMap {
let weaknessLocations = bcves
.flatMap(bcve =>
[bcve.prePatch, bcve.postPatch].map(c => ({
CVE: bcve.CVE,
commit: c.commit,
weaknesses: c.weaknesses
}))
)
.flatMap(g =>
(g.weaknesses || [])
.filter(w => !!w.location)
.map(w => ({
CVE: g.CVE,
commit: g.commit,
file: w.location.file,
line: w.location.line
}))
);
let targets = new Map();
weaknessLocations.forEach(l => {
if (!targets.has(l.CVE)) {
targets.set(l.CVE, new Map());
}
let byCVE = targets.get(l.CVE);
if (!byCVE.has(l.commit)) {
byCVE.set(l.commit, new Map());
}
let byCVEAndCommit = byCVE.get(l.commit);
if (!byCVEAndCommit.has(l.file)) {
byCVEAndCommit.set(l.file, new Set());
}
let byCVEAndCommitAndFile = byCVEAndCommit.get(l.file);
byCVEAndCommitAndFile.add(l.line);
});
return targets;
}
function buildRulesOnATargetMap(
bcves: BCVE[],
targets: TargetsMap
): RulesOnTargetMap {
let unmapped = bcves.flatMap(bcve =>
(bcve.prePatch.runs || []).flatMap(r =>
(r.alerts || [])
.filter(
a =>
a.location &&
isOnTarget(
bcve.CVE,
bcve.prePatch.commit,
a.location.file,
a.location.line,
targets
)
)
.map(a => ({
CVE: bcve.CVE,
toolID: r.toolID,
ruleID: a.ruleID
}))
)
);
let rulesOnATarget = new Map();
unmapped.forEach(u => {
if (!rulesOnATarget.has(u.CVE)) {
rulesOnATarget.set(u.CVE, new Map());
}
let byCVE = rulesOnATarget.get(u.CVE);
if (!byCVE.has(u.toolID)) {
byCVE.set(u.toolID, new Set());
}
let byCVEAndToolID = byCVE.get(u.toolID);
byCVEAndToolID.add(u.ruleID);
});
return rulesOnATarget;
}
function isOnTarget(
cve: CVEString,
commit: CommitID,
file: File,
line: number,
targets: TargetsMap
): boolean {
return !!targets.get(cve)?.get(commit)?.get(file)?.has(line);
}
function isForRuleOnATarget(
cve: CVEString,
toolID: ToolID,
ruleID: RuleID,
rulesOnATarget: RulesOnTargetMap
): boolean {
return !!rulesOnATarget.get(cve)?.get(toolID)?.has(ruleID);
}
type TargetsMap = Map<CVEString, Map<CommitID, Map<File, Set<number>>>>;
type RulesOnTargetMap = Map<CVEString, Map<ToolID, Set<RuleID>>>;
export default class ExploreServer {
private targets: TargetsMap = new Map();
private rulesOnATarget: RulesOnTargetMap = new Map();
constructor(private bcves: BCVE[], private port: number) {
this.targets = buildTargetsMap(bcves);
this.rulesOnATarget = buildRulesOnATargetMap(bcves, this.targets);
}
resolveSourceFileRequest(CVE: CVEString, commit: CommitID, file: File) {
if (file === undefined) {
return undefined;
}
let bcve = this.bcves.find(bcve => bcve.CVE === CVE);
if (bcve === undefined) {
console.warn(`Could not find ${CVE} among the hosted CVEs.`);
return undefined;
}
let localSourceDirectory;
if (bcve.prePatch?.commit === commit) {
localSourceDirectory = bcve.prePatch.localSourceDirectory;
} else if (bcve.postPatch?.commit === commit) {
localSourceDirectory = bcve.postPatch.localSourceDirectory;
} else {
console.warn(
`Could not find commit ${commit} for ${CVE} among the hosted CVEs.`
);
return undefined;
}
if (localSourceDirectory === undefined) {
console.warn(`No local sources for commit ${commit} of ${CVE}.`);
return undefined;
}
let resolved = path.resolve(path.join(localSourceDirectory, file));
if (!resolved.startsWith(localSourceDirectory)) {
console.warn(
`The ${file} for ${commit} of ${CVE} does not reside in ${localSourceDirectory}.`
);
return undefined;
}
if (!fs.existsSync(resolved)) {
console.warn(
`The file ${resolved} for ${commit} of ${CVE} does not exist.`
);
return undefined;
}
return resolved;
}
getCommits(bcves: BCVE[]): ClientTypes.CommitData[] {
return bcves.flatMap(bcve => {
let commits: ClientTypes.CommitData[] = [];
if (bcve.prePatch) {
commits.push(makeCommitData(bcve.CVE, bcve.repository, bcve.prePatch));
}
if (bcve.postPatch) {
commits.push(makeCommitData(bcve.CVE, bcve.repository, bcve.postPatch));
}
return commits;
});
}
getBCVE(cve: CVEString) {
return this.bcves.find(bcve => bcve.CVE === cve);
}
getFiles(cve: CVEString, commit: CommitID): ClientTypes.FileData[] {
function getFiles(commitDescription: CommitDescription): string[] {
let alerts = (commitDescription.runs || []).flatMap(r =>
(r.alerts || []).map(a => a.location?.file).filter(f => f !== undefined)
);
return alerts;
}
let bcve = this.getBCVE(cve);
let files = [];
if (bcve.prePatch && bcve.prePatch.commit === commit) {
files.push(...getFiles(bcve.prePatch));
}
if (bcve.postPatch && bcve.postPatch.commit === commit) {
files.push(...getFiles(bcve.postPatch));
}
files = Array.from(new Set(files));
return files.map(f => ({ file: f }));
}
getAlertsForBCVE(bcve: BCVE): ClientTypes.Alert[] {
let targets = this.targets,
rulesOnATarget = this.rulesOnATarget;
function getAlerts(
commitDescription: CommitDescription
): ClientTypes.Alert[] {
let alerts = (commitDescription.runs || []).flatMap(r =>
(r.alerts || [])
.filter(a => !!a.location)
.map(a => ({
CVE: bcve.CVE,
commit: makeCommitData(
bcve.CVE,
bcve.repository,
commitDescription
),
file: a.location.file,
line: a.location.line,
toolID: r.toolID,
ruleID: a.ruleID,
isOnTarget: isOnTarget(
bcve.CVE,
commitDescription.commit,
a.location.file,
a.location.line,
targets
),
isForRuleOnATarget: isForRuleOnATarget(
bcve.CVE,
r.toolID,
a.ruleID,
rulesOnATarget
),
url: a.url
}))
);
return alerts;
}
let alerts = [];
if (bcve.prePatch) {
alerts.push(...getAlerts(bcve.prePatch));
}
if (bcve.postPatch) {
alerts.push(...getAlerts(bcve.postPatch));
}
return alerts;
}
getAlerts(cve: CVEString): ClientTypes.Alert[] {
let bcve = this.getBCVE(cve);
if (!bcve) {
console.warn(`No BCVE for ${cve}`);
return [];
}
return this.getAlertsForBCVE(bcve);
}
getWeaknesses(): { [cve: string]: ClientTypes.Weakness[] } {
function getWeaknesses(
cve: CVEString,
repository: string,
commitDescription: CommitDescription
): ClientTypes.Weakness[] {
let weaknesses = (commitDescription.weaknesses || [])
.filter(w => w.location)
.map(w => ({
CVE: cve,
commit: makeCommitData(cve, repository, commitDescription),
file: w.location.file,
line: w.location.line,
explanation: w.explanation
}));
return weaknesses;
}
let mapped: { [cve: string]: ClientTypes.Weakness[] } = {};
this.bcves.forEach(bcve => {
let weaknesses = [];
if (bcve.prePatch) {
weaknesses.push(
...getWeaknesses(bcve.CVE, bcve.repository, bcve.prePatch)
);
}
if (bcve.postPatch) {
weaknesses.push(
...getWeaknesses(bcve.CVE, bcve.repository, bcve.postPatch)
);
}
mapped[bcve.CVE] = weaknesses;
});
return mapped;
}
getCVEWeaknesses(cve: CVEString): ClientTypes.Weakness[] {
function getWeaknesses(
kind: "prePatch" | "postPatch",
commitDescription: CommitDescription
): ClientTypes.Weakness[] {
let weaknesses = (commitDescription.weaknesses || [])
.filter(w => !!w.location)
.map(w => ({
CVE: cve,
commitKind: kind,
commit: makeCommitData(bcve.CVE, bcve.repository, commitDescription),
file: w.location.file,
line: w.location.line,
explanation: w.explanation
}));
return weaknesses;
}
let bcve = this.getBCVE(cve);
if (!bcve) {
console.warn(`No BCVE for ${cve}`);
return [];
}
let weaknesses = [];
if (bcve.prePatch) {
weaknesses.push(...getWeaknesses("prePatch", bcve.prePatch));
}
if (bcve.postPatch) {
weaknesses.push(...getWeaknesses("postPatch", bcve.postPatch));
}
return weaknesses;
}
getAlertCounts(
cve: CVEString,
commit: CommitID,
file?: File
): ClientTypes.AlertCounts {
function getAlertCounts(
commitDescription: CommitDescription
): ClientTypes.AlertCounts {
let counts: ClientTypes.AlertCounts = {};
(commitDescription.runs || []).forEach(r => {
counts[r.toolID] = counts[r.toolID] || 0;
counts[r.toolID] += (r.alerts || []).filter(a =>
file === undefined ? true : a.location.file === file
).length;
});
return counts;
}
let bcve = this.getBCVE(cve);
if (!bcve) {
console.warn(`No BCVE for ${cve}`);
return {};
}
if (bcve.prePatch && bcve.prePatch.commit === commit) {
return getAlertCounts(bcve.prePatch);
}
if (bcve.postPatch && bcve.postPatch.commit === commit) {
return getAlertCounts(bcve.postPatch);
}
}
listen(req: http.IncomingMessage, res: http.ServerResponse) {
try {
console.log(`Got request: ${req.url}`);
let parsedUrl = url.parse(req.url, true);
switch (parsedUrl.pathname) {
case "/": {
res.setHeader("Content-Type", "text/html");
res.end(`
<!doctype html>
<html>
<head>
</head>
<body>
<div id="main"></div>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
`);
break;
}
case "/main.js": {
res.setHeader("Content-Type", "text/javascript");
fs.createReadStream(
path.join(__dirname, "../../../../../../webpack/dist/main.js")
).pipe(res);
break;
}
case "/main.css": {
res.setHeader("Content-Type", "text/css");
res.writeHead(200);
fs.createReadStream("../../dist/main.css").pipe(res);
break;
}
case "/sources": /*?CVE=...&commit=...&file=...*/ {
let file;
try {
file = this.resolveSourceFileRequest(
parsedUrl.query.CVE as string,
parsedUrl.query.commit as string,
parsedUrl.query.file as string
);
} catch (e) {
console.error("Ignoring `resolveSourceFileRequest` error:");
console.error(e);
file = undefined;
}
if (file === undefined) {
// TODO support downloading on the fly
res.writeHead(404);
res.end();
} else {
let src = fs.readFileSync(file);
res.setHeader("Content-Type", "text/plain");
res.writeHead(200);
res.end(src);
}
break;
}
case "/data/getBenchmarkSource": /* CVE=... */ {
let cvesDir = path.resolve(
path.join(__dirname, "../../../../../../../CVEs/")
);
let cve = parsedUrl.query.CVE;
let file = path.resolve(path.join(cvesDir, `${cve}.json`));
res.setHeader("Content-Type", "text/plain");
if (!file.startsWith(cvesDir)) {
console.warn(
`The ${file} for ${cve} does not reside in ${cvesDir}.`
);
res.writeHead(404);
res.end();
return;
}
res.writeHead(200);
fs.createReadStream(file).pipe(res);
break;
}
case "/data/getCommits": /* */ {
res.setHeader("Content-Type", "application/json");
res.writeHead(200);
res.end(JSON.stringify(this.getCommits(this.bcves)));
break;
}
case "/data/getCVECommits": /* CVE=... */ {
let bcve = this.getBCVE(parsedUrl.query.CVE as string);
res.setHeader("Content-Type", "application/json");
res.writeHead(200);
res.end(
JSON.stringify({
unpatchedCommit: makeCommitData(
bcve.CVE,
bcve.repository,
bcve.prePatch
),
patchCommit: makeCommitData(
bcve.CVE,
bcve.repository,
bcve.postPatch
)
})
);
break;
}
case "/data/getAllCVECommits": /* */ {
res.setHeader("Content-Type", "application/json");
res.writeHead(200);
res.end(
JSON.stringify(
this.bcves.map(bcve => ({
unpatchedCommit: makeCommitData(
bcve.CVE,
bcve.repository,
bcve.prePatch
),
patchCommit: makeCommitData(
bcve.CVE,
bcve.repository,
bcve.postPatch
)
}))
)
);
break;
}
case "/data/getCVERepository": /* CVE=... */ {
res.setHeader("Content-Type", "application/json");
res.writeHead(200);
res.end(this.getBCVE(parsedUrl.query.CVE as string).repository);
break;
}
case "/data/getToolIds": /* */ {
res.setHeader("Content-Type", "application/json");
let toolIDs = this.bcves.flatMap(bcve =>
[bcve.prePatch, bcve.postPatch].flatMap(c =>
(c.runs || []).map(r => r.toolID)
)
);
res.writeHead(200);
res.end(JSON.stringify(Array.from(new Set(toolIDs))));
break;
}
case "/data/getCVEs": /* */ {
let list = this.bcves.map(bcve => bcve.CVE);
res.setHeader("Content-Type", "application/json");
res.writeHead(200);
res.end(JSON.stringify(list));
break;
}
case "/data/getCVE2CWEs": /* */ {
let map: { [cve: string]: CWEString[] } = {};
this.bcves.forEach(bcve => (map[bcve.CVE] = bcve.CWEs));
res.setHeader("Content-Type", "application/json");
res.writeHead(200);
res.end(JSON.stringify(map));
break;
}
case "/data/getFiles": /* CVE=...&commit=...*/ {
res.setHeader("Content-Type", "application/json");
res.writeHead(200);
res.end(
JSON.stringify(
this.getFiles(
parsedUrl.query.CVE as string,
parsedUrl.query.commit as string
)
)
);
break;
}
case "/data/getCVEAlertCounts": /* CVE=...&commit=...*/ {
res.setHeader("Content-Type", "application/json");
res.writeHead(200);
res.end(
JSON.stringify(
this.getAlertCounts(
parsedUrl.query.CVE as string,
parsedUrl.query.commit as string
)
)
);
break;
}
case "/data/getFileAlertCounts": /* CVE=...&commit=...&file=...*/ {
res.setHeader("Content-Type", "application/json");
res.writeHead(200);
res.end(
JSON.stringify(
this.getAlertCounts(
parsedUrl.query.CVE as string,
parsedUrl.query.commit as string,
parsedUrl.query.file as string
)
)
);
break;
}
case "/data/getAllAlerts": /* */ {
let response = this.bcves.flatMap(bcve =>
this.getAlertsForBCVE(bcve)
);
res.setHeader("Content-Type", "application/json");
res.writeHead(200);
res.end(JSON.stringify(response));
break;
}
case "/data/getAlerts": /* CVE=...*/ {
res.setHeader("Content-Type", "application/json");
res.writeHead(200);
res.end(
JSON.stringify(this.getAlerts(parsedUrl.query.CVE as string))
);
break;
}
case "/data/getAllWeaknesses": {
res.setHeader("Content-Type", "application/json");
res.writeHead(200);
res.end(
JSON.stringify(
Object.values(this.getWeaknesses()).flatMap(id => id)
)
);
break;
}
case "/data/getAllToolRuns": {
let runs = this.bcves.flatMap(bcve =>
[bcve.prePatch, bcve.postPatch].flatMap(c =>
(c.runs || []).map(r => ({
CVE: bcve.CVE,
toolID: r.toolID,
commit: c.commit
}))
)
);
res.setHeader("Content-Type", "application/json");
res.writeHead(200);
res.end(JSON.stringify(runs));
break;
}
case "/data/getCWENames": {
// TODO fetch this data from somewhere
res.setHeader("Content-Type", "application/json");
res.writeHead(200);
res.end(
JSON.stringify({
"CWE-0020": "Improper Input Validation",
"CWE-0022":
"Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')",
"CWE-0023": "Relative Path Traversal",
"CWE-0036": "Absolute Path Traversal",
"CWE-0073": "External Control of File Name or Path",
"CWE-0074":
"Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')",
"CWE-0078":
"Improper Sanitization of Special Elements used in an OS Command ('OS Command Injection')",
"CWE-0079":
"Failure to Preserve Web Page Structure ('Cross-site Scripting')",
"CWE-0088": "Argument Injection or Modification",
"CWE-0089":
"Improper Sanitization of Special Elements used in an SQL Command ('SQL Injection')",
"CWE-0094":
"Failure to Control Generation of Code ('Code Injection')",
"CWE-0099":
"Improper Control of Resource Identifiers ('Resource Injection')",
"CWE-0116": "Improper Encoding or Escaping of Output",
"CWE-0200": "Information Exposure",
"CWE-0250": "Execution with Unnecessary Privileges",
"CWE-0290": "Authentication Bypass by Spoofing",
"CWE-0312": "Cleartext Storage of Sensitive Information"
})
);
break;
}
case "/data/getCVEWeaknesses": /* CVE=...*/ {
res.setHeader("Content-Type", "application/json");
res.writeHead(200);
res.end(
JSON.stringify(this.getCVEWeaknesses(parsedUrl.query.CVE as string))
);
break;
}
default:
res.writeHead(404);
res.end(JSON.stringify({ error: "Resource not found" }));
}
} catch (e) {
console.error(e);
}
}
public async start(): Promise<void> {
return new Promise((resolve, reject) => {
try {
const server = http.createServer((req, res) => this.listen(req, res)),
host = "localhost";
server.listen(this.port, host, () => {
console.log(`Server is running on http://${host}:${this.port}`);
server.on("close", () => {
console.log("Server closed");
resolve();
});
});
} catch (e) {
reject(e);
}
});
}
} | the_stack |
import {
getQuickJS,
QuickJSVm,
QuickJSHandle,
InterruptHandler,
QuickJSDeferredPromise,
} from './quickjs'
import { it, describe } from 'mocha'
import assert from 'assert'
import { VmCallResult } from './vm-interface'
import fs from 'fs'
describe('QuickJSVm', async () => {
let vm: QuickJSVm = undefined as any
beforeEach(async () => {
const quickjs = await getQuickJS()
vm = quickjs.createVm()
})
afterEach(() => {
vm.dispose()
vm = undefined as any
})
describe('primitives', () => {
it('can round-trip a number', () => {
const jsNumber = 42
const numHandle = vm.newNumber(jsNumber)
assert.equal(vm.getNumber(numHandle), jsNumber)
})
it('can round-trip a string', () => {
const jsString = 'an example 🤔 string with unicode 🎉'
const stringHandle = vm.newString(jsString)
assert.equal(vm.getString(stringHandle), jsString)
})
it('can round-trip undefined', () => {
assert.strictEqual(vm.dump(vm.undefined), undefined)
})
it('can round-trip true', () => {
assert.strictEqual(vm.dump(vm.true), true)
})
it('can round-trip false', () => {
assert.strictEqual(vm.dump(vm.false), false)
})
it('can round-trip null', () => {
assert.strictEqual(vm.dump(vm.null), null)
})
})
describe('functions', () => {
it('can wrap a Javascript function and call it', () => {
const some = 9
const fnHandle = vm.newFunction('addSome', num => {
return vm.newNumber(some + vm.getNumber(num))
})
const result = vm.callFunction(fnHandle, vm.undefined, vm.newNumber(1))
if (result.error) {
assert.fail('calling fnHandle must succeed')
}
assert.equal(vm.getNumber(result.value), 10)
fnHandle.dispose()
})
it('passes through native exceptions', () => {
const fnHandle = vm.newFunction('jsOops', () => {
throw new Error('oops')
})
const result = vm.callFunction(fnHandle, vm.undefined)
if (!result.error) {
assert.fail('function call must return error')
}
assert.deepEqual(vm.dump(result.error), {
name: 'Error',
message: 'oops',
})
result.error.dispose()
fnHandle.dispose()
})
it('can return undefined twice', () => {
const fnHandle = vm.newFunction('returnUndef', () => {
return vm.undefined
})
vm.unwrapResult(vm.callFunction(fnHandle, vm.undefined)).dispose()
const result = vm.unwrapResult(vm.callFunction(fnHandle, vm.undefined))
assert.equal(vm.typeof(result), 'undefined')
result.dispose()
fnHandle.dispose()
})
it('can see its arguments being cloned', () => {
let value: QuickJSHandle | undefined
const fnHandle = vm.newFunction('doSomething', arg => {
value = arg.dup()
})
const argHandle = vm.newString('something')
const callHandle = vm.callFunction(fnHandle, vm.undefined, argHandle)
argHandle.dispose()
vm.unwrapResult(callHandle).dispose()
if (!value) throw new Error(`Value unset`)
assert.equal(vm.getString(value), 'something')
value.dispose()
fnHandle.dispose()
})
})
describe('properties', () => {
it('defining a property does not leak', () => {
vm.defineProp(vm.global, 'Name', {
enumerable: false,
configurable: false,
get: () => vm.newString('World'),
})
const result = vm.unwrapResult(vm.evalCode('"Hello " + Name'))
assert.equal(vm.dump(result), 'Hello World')
result.dispose()
})
})
describe('objects', () => {
it('can set and get properties by native string', () => {
const object = vm.newObject()
const value = vm.newNumber(42)
vm.setProp(object, 'propName', value)
const value2 = vm.getProp(object, 'propName')
assert.equal(vm.getNumber(value2), 42)
object.dispose()
value.dispose()
value2.dispose()
})
it('can set and get properties by handle string', () => {
const object = vm.newObject()
const key = vm.newString('prop as a QuickJS string')
const value = vm.newNumber(42)
vm.setProp(object, key, value)
const value2 = vm.getProp(object, key)
assert.equal(vm.getNumber(value2), 42)
object.dispose()
key.dispose()
value.dispose()
value2.dispose()
})
it('can create objects with a prototype', () => {
const defaultGreeting = vm.newString('SUP DAWG')
const greeterPrototype = vm.newObject()
vm.setProp(greeterPrototype, 'greeting', defaultGreeting)
defaultGreeting.dispose()
const greeter = vm.newObject(greeterPrototype)
// Gets something from the prototype
const getGreeting = vm.getProp(greeter, 'greeting')
assert.equal(vm.getString(getGreeting), 'SUP DAWG')
getGreeting.dispose()
// But setting a property from the prototype does not modify the prototype
const newGreeting = vm.newString('How do you do?')
vm.setProp(greeter, 'greeting', newGreeting)
newGreeting.dispose()
const originalGreeting = vm.getProp(greeterPrototype, 'greeting')
assert.equal(vm.getString(originalGreeting), 'SUP DAWG')
originalGreeting.dispose()
greeterPrototype.dispose()
greeter.dispose()
})
})
describe('arrays', () => {
it('can set and get entries by native number', () => {
const array = vm.newArray()
const val1 = vm.newNumber(101)
vm.setProp(array, 0, val1)
const val2 = vm.getProp(array, 0)
assert.strictEqual(vm.getNumber(val2), 101)
array.dispose()
val1.dispose()
val2.dispose()
})
it('adding items sets array.length', () => {
const vals = [vm.newNumber(0), vm.newNumber(1), vm.newString('cow')]
const array = vm.newArray()
for (let i = 0; i < vals.length; i++) {
vm.setProp(array, i, vals[i])
}
const length = vm.getProp(array, 'length')
assert.strictEqual(vm.getNumber(length), 3)
array.dispose()
vals.forEach(val => val.dispose())
})
})
describe('.unwrapResult', () => {
it('successful result: returns the value', () => {
const handle = vm.newString('OK!')
const result: VmCallResult<QuickJSHandle> = {
value: handle,
}
assert.strictEqual(vm.unwrapResult(result), handle)
})
it('error result: throws the error as a Javascript value', () => {
const handle = vm.newString('ERROR!')
const result: VmCallResult<QuickJSHandle> = {
error: handle,
}
try {
vm.unwrapResult(result)
assert.fail('vm.unwrapResult(error) must throw')
} catch (error) {
assert.strictEqual(error, 'ERROR!')
}
})
})
describe('.evalCode', () => {
it('on success: returns { value: success }', () => {
const value = vm.unwrapResult(vm.evalCode(`["this", "should", "work"].join(' ')`))
assert.equal(vm.getString(value), 'this should work')
value.dispose()
})
it('on failure: returns { error: exception }', () => {
const result = vm.evalCode(`["this", "should", "fail].join(' ')`)
if (!result.error) {
assert.fail('result should be an error')
}
assert.deepEqual(vm.dump(result.error), {
name: 'SyntaxError',
message: 'unexpected end of string',
stack: ' at eval.js:1\n',
})
result.error.dispose()
})
it('runs in the global context', () => {
vm.unwrapResult(vm.evalCode(`var declaredWithEval = 'Nice!'`)).dispose()
const declaredWithEval = vm.getProp(vm.global, 'declaredWithEval')
assert.equal(vm.getString(declaredWithEval), 'Nice!')
declaredWithEval.dispose()
})
it('can access assigned globals', () => {
let i = 0
const fnHandle = vm.newFunction('nextId', () => {
return vm.newNumber(++i)
})
vm.setProp(vm.global, 'nextId', fnHandle)
fnHandle.dispose()
const nextId = vm.unwrapResult(vm.evalCode(`nextId(); nextId(); nextId()`))
assert.equal(i, 3)
assert.equal(vm.getNumber(nextId), 3)
})
})
describe('.executePendingJobs', () => {
it('runs pending jobs', () => {
let i = 0
const fnHandle = vm.newFunction('nextId', () => {
return vm.newNumber(++i)
})
vm.setProp(vm.global, 'nextId', fnHandle)
fnHandle.dispose()
const result = vm.unwrapResult(
vm.evalCode(`(new Promise(resolve => resolve())).then(nextId).then(nextId).then(nextId);1`)
)
assert.equal(i, 0)
vm.executePendingJobs()
assert.equal(i, 3)
assert.equal(vm.getNumber(result), 1)
})
})
describe('.hasPendingJob', () => {
it('returns true when job pending', () => {
let i = 0
const fnHandle = vm.newFunction('nextId', () => {
return vm.newNumber(++i)
})
vm.setProp(vm.global, 'nextId', fnHandle)
fnHandle.dispose()
vm.unwrapResult(vm.evalCode(`(new Promise(resolve => resolve(5)).then(nextId));1`)).dispose()
assert.strictEqual(vm.hasPendingJob(), true, 'has a pending job after creating a promise')
const executed = vm.unwrapResult(vm.executePendingJobs())
assert.strictEqual(executed, 1, 'executed exactly 1 job')
assert.strictEqual(vm.hasPendingJob(), false, 'no longer any jobs after execution')
})
})
describe('.dump', () => {
function dumpTestExample(val: unknown) {
const json = typeof val === 'undefined' ? 'undefined' : JSON.stringify(val)
const nativeType = typeof val
it(`supports ${nativeType} (${json})`, () => {
const handle = vm.unwrapResult(vm.evalCode(`(${json})`))
assert.deepEqual(vm.dump(handle), val)
handle.dispose()
})
}
dumpTestExample(1)
dumpTestExample('hi')
dumpTestExample(true)
dumpTestExample(false)
dumpTestExample(undefined)
dumpTestExample(null)
dumpTestExample({ cow: true })
dumpTestExample([1, 2, 3])
})
describe('.typeof', () => {
function typeofTestExample(val: unknown, toCode = JSON.stringify) {
const json = toCode(val)
const nativeType = typeof val
it(`supports ${nativeType} (${json})`, () => {
const handle = vm.unwrapResult(vm.evalCode(`(${json})`))
assert.equal(vm.typeof(handle), nativeType)
handle.dispose()
})
}
typeofTestExample(1)
typeofTestExample('hi')
typeofTestExample(true)
typeofTestExample(false)
typeofTestExample(undefined)
typeofTestExample(null)
typeofTestExample({ cow: true })
typeofTestExample([1, 2, 3])
typeofTestExample(
function() {},
(val: any) => val.toString()
)
})
describe('interrupt handler', () => {
it('is called with the expected VM', () => {
let calls = 0
const interruptHandler: InterruptHandler = interruptVm => {
assert.strictEqual(interruptVm, vm, 'ShouldInterruptHandler callback VM is the vm')
calls++
return false
}
vm.setInterruptHandler(interruptHandler)
vm.unwrapResult(vm.evalCode('1 + 1')).dispose()
assert(calls > 0, 'interruptHandler called at least once')
})
it('interrupts infinite loop execution', () => {
let calls = 0
const interruptHandler: InterruptHandler = interruptVm => {
if (calls > 10) {
return true
}
calls++
return false
}
vm.setInterruptHandler(interruptHandler)
const result = vm.evalCode('i = 0; while (1) { i++ }')
// Make sure we actually got to interrupt the loop.
const iHandle = vm.getProp(vm.global, 'i')
const i = vm.getNumber(iHandle)
iHandle.dispose()
assert(i > 10, 'incremented i')
assert(i > calls, 'incremented i more than called the interrupt handler')
// console.log('Javascript loop iterrations:', i, 'interrupt handler calls:', calls)
if (result.error) {
const errorJson = vm.dump(result.error)
result.error.dispose()
assert.equal(errorJson.name, 'InternalError')
assert.equal(errorJson.message, 'interrupted')
} else {
result.value.dispose()
assert.fail('Should have returned an interrupt error')
}
})
})
describe('.computeMemoryUsage', () => {
it('returns an object with JSON memory usage info', () => {
const result = vm.computeMemoryUsage()
const resultObj = vm.dump(result)
result.dispose()
const example = {
array_count: 1,
atom_count: 414,
atom_size: 13593,
binary_object_count: 0,
binary_object_size: 0,
c_func_count: 46,
fast_array_count: 1,
fast_array_elements: 0,
js_func_code_size: 0,
js_func_count: 0,
js_func_pc2line_count: 0,
js_func_pc2line_size: 0,
js_func_size: 0,
malloc_count: 665,
malloc_limit: 4294967295,
memory_used_count: 665,
memory_used_size: 36305,
obj_count: 97,
obj_size: 4656,
prop_count: 654,
prop_size: 5936,
shape_count: 50,
shape_size: 10328,
str_count: 0,
str_size: 0,
}
assert.deepEqual(Object.keys(resultObj).sort(), Object.keys(example).sort())
})
})
describe('.setMemoryLimit', () => {
it('sets an enforced limit', () => {
vm.setMemoryLimit(100)
const result = vm.evalCode(`new Uint8Array(101); "ok"`)
if (!result.error) {
result.value.dispose()
throw new Error('should be an error')
}
vm.setMemoryLimit(-1) // so we can dump
const error = vm.dump(result.error)
result.error.dispose()
assert.strictEqual(error, null)
})
it('removes limit when set to -1', () => {
vm.setMemoryLimit(100)
vm.setMemoryLimit(-1)
const result = vm.unwrapResult(vm.evalCode(`new Uint8Array(101); "ok"`))
const value = vm.dump(result)
result.dispose()
assert.strictEqual(value, 'ok')
})
})
describe('.dumpMemoryUsage()', () => {
it('logs memory usage', () => {
assert(
vm.dumpMemoryUsage().endsWith('per fast array)\n'),
'should end with "per fast array)\\n"'
)
})
})
describe('.newPromise()', () => {
it('dispose does not leak', () => {
vm.newPromise().dispose()
})
it('passes an end-to-end test', async () => {
const expectedValue = Math.random()
let deferred: QuickJSDeferredPromise = undefined as any
function timeout(ms: number) {
return new Promise(resolve => {
setTimeout(() => resolve(), ms)
})
}
const asyncFuncHandle = vm.newFunction('getThingy', () => {
deferred = vm.newPromise()
timeout(5).then(() => vm.newNumber(expectedValue).consume(val => deferred.resolve(val)))
return deferred.handle
})
asyncFuncHandle.consume(func => vm.setProp(vm.global, 'getThingy', func))
vm.unwrapResult(
vm.evalCode(`
var globalThingy = 'not set by promise';
getThingy().then(thingy => { globalThingy = thingy })
`)
).dispose()
// Wait for the promise to settle
await deferred.settled
// Execute promise callbacks inside the VM
vm.executePendingJobs()
// Check that the promise executed.
const vmValue = vm.unwrapResult(vm.evalCode(`globalThingy`)).consume(x => vm.dump(x))
assert.equal(vmValue, expectedValue)
})
})
describe('memory pressure', () => {
it('can pass a large string to a C function', async () => {
const jsonString = await fs.promises.readFile(
`${__dirname}/../test/json-generator-dot-com-1024-rows.json`,
'utf-8'
)
const stringHandle = vm.newString(jsonString)
stringHandle.dispose()
})
})
}) | the_stack |
import * as React from 'react';
import { Box as ReakitBox } from 'reakit';
import ConditionalWrap from 'conditional-wrap';
import { Size } from '../types';
import {
useClassName,
createComponent,
createElement,
createHook,
mergeRefs,
pickCSSProps,
omitCSSProps,
useLabelPlaceholder,
useUniqueId,
} from '../utils';
import { Box, BoxProps } from '../Box';
import { FieldWrapper, FieldWrapperProps } from '../FieldWrapper';
import { Group } from '../Group';
import { Icon } from '../Icon';
import { Spinner } from '../Spinner';
import { Text } from '../Text';
import * as styles from './Select.styles';
export type LocalSelectProps = {
/** Automatically focus on the input */
autoFocus?: boolean;
/** If the `label` prop is supplied, is it contained inside the select? */
containLabel?: boolean;
/** Default value of the input */
defaultValue?: string;
/** Disables the input */
disabled?: boolean;
/** Adds a cute loading indicator to the input field */
isLoading?: boolean;
/** Makes the input required and sets aria-invalid to true */
isRequired?: boolean;
label?: string;
/** Name of the input field */
name?: string;
options: Array<{ label: string; value: any; disabled?: boolean }>;
/** Alters the size of the input. Can be "small", "medium" or "large" */
size?: Size;
/** Hint text to display */
placeholder?: string;
selectProps?: Partial<SelectProps>;
selectRef?: React.Ref<any>;
/** State of the input. Can be any color in the palette. */
state?: string;
/** Value of the input */
value?: any;
/** Function to invoke when focus is lost */
onBlur?: React.FocusEventHandler<HTMLInputElement>;
/** Function to invoke when input has changed */
onChange?: React.FormEventHandler<HTMLInputElement>;
/** Function to invoke when input is focused */
onFocus?: React.FocusEventHandler<HTMLInputElement>;
};
export type SelectProps = Omit<BoxProps, 'onBlur' | 'onChange' | 'onFocus'> & LocalSelectProps;
const useProps = createHook<SelectProps>(
(props, { themeKey }) => {
const {
containLabel,
disabled,
isLoading,
isRequired,
label,
onChange,
options,
placeholder: _placeholder,
selectProps,
selectRef,
state,
...restProps
} = props;
const ref = React.useRef();
const uid = useUniqueId();
const { isFocused, inputProps: labelPlaceholderInputProps } = useLabelPlaceholder({
enabled: Boolean(label),
...props,
});
let placeholder = _placeholder;
if (isLoading && options.length === 0) {
placeholder = 'Loading...';
}
const [isPlaceholderSelected, setIsPlaceholderSelected] = React.useState(
Boolean(!props.defaultValue && !props.value && (label || placeholder))
);
const handleChange = React.useCallback(
(e) => {
setIsPlaceholderSelected(false);
onChange && onChange(e);
},
[onChange]
);
const wrapperClassName = useClassName({
style: styles.SelectWrapper,
styleProps: props,
themeKey,
themeKeySuffix: 'Wrapper',
prevClassName: restProps.className,
});
const iconClassName = useClassName({
style: styles.SelectIcon,
styleProps: props,
themeKey,
themeKeySuffix: 'Icon',
});
const spinnerClassName = useClassName({
style: styles.SelectSpinner,
styleProps: props,
themeKey,
themeKeySuffix: 'Spinner',
});
const labelWrapperClassName = useClassName({
style: styles.LabelWrapper,
styleProps: { ...props, isFocused: isFocused || !isPlaceholderSelected },
themeKey,
themeKeySuffix: 'LabelWrapper',
});
const labelWrapperBackgroundClassName = useClassName({
style: styles.LabelWrapperBackground,
styleProps: { ...props, isFocused: isFocused || !isPlaceholderSelected },
themeKey,
themeKeySuffix: 'LabelWrapperBackground',
});
const boxProps = Box.useProps({
...omitCSSProps(restProps),
id: uid,
...selectProps,
...labelPlaceholderInputProps,
className: undefined,
elementRef: mergeRefs(ref, selectRef, props.elementRef),
wrapElement: (children) => (
<Box className={wrapperClassName} {...pickCSSProps(props)}>
{label && (
<>
{!containLabel && (
<Box className={labelWrapperBackgroundClassName}>
<Text opacity="0">{label}</Text>
</Box>
)}
{/*
// @ts-ignore */}
<Box className={labelWrapperClassName}>
{/*
// @ts-ignore */}
<Text use="label" htmlFor={selectProps?.id || uid}>
{label}
</Text>
</Box>
</>
)}
{children}
{isLoading ? (
<Spinner className={spinnerClassName} color="text" />
) : (
<Icon className={iconClassName} icon="chevron-down" />
)}
</Box>
),
});
let color = 'text';
if (isPlaceholderSelected) {
color = 'gray300';
if (label) {
color = 'transparent';
}
}
const className = useClassName({
style: styles.Select,
styleProps: { ...props, color, hasIcon: true, isPlaceholderSelected },
themeKey,
prevClassName: boxProps.className,
});
return {
...boxProps,
className,
'aria-invalid': state === 'danger',
'aria-required': isRequired,
disabled,
onChange: handleChange,
children: (
<React.Fragment>
{(label || placeholder) && (
<option disabled={typeof restProps.value !== 'undefined' || !isPlaceholderSelected} value="">
{label || placeholder}
</option>
)}
{/*
// @ts-ignore */}
{options.map((option, i) => (
<option
key={i} // eslint-disable-line
disabled={disabled || option.disabled}
value={option.value}
>
{option.label}
</option>
))}
</React.Fragment>
),
};
},
{ defaultProps: { variant: 'bordered' }, themeKey: 'Select' }
);
export const Select = createComponent<SelectProps>(
(props) => {
const selectProps = useProps(props);
return createElement({
children: props.children,
component: ReakitBox,
use: props.use,
htmlProps: selectProps,
});
},
{
attach: {
useProps,
displayName: 'Select',
},
defaultProps: {
use: 'select',
},
themeKey: 'Select',
}
);
////////////////////////////////////////////////////////////////
export type LocalSelectFieldProps = {
/** Addon component to the input (before). Similar to the addon components in Input. */
addonBefore?: React.ReactElement<any>;
/** Addon component to the input (after). Similar to the addon components in Input. */
addonAfter?: React.ReactElement<any>;
/** Additional props for the Select component */
selectProps?: SelectProps;
/** If addonBefore or addonAfter exists, then the addons will render vertically. */
orientation?: 'vertical' | 'horizontal';
};
export type SelectFieldProps = BoxProps & FieldWrapperProps & SelectProps & LocalSelectFieldProps;
const useSelectFieldProps = createHook<SelectFieldProps>(
(props, { themeKey }) => {
const {
addonAfter,
addonBefore,
children,
containLabel,
autoFocus,
defaultValue,
description,
disabled,
hint,
selectProps,
isLoading,
isOptional,
isRequired,
orientation,
label,
name,
options,
size,
placeholder,
state,
tooltip,
tooltipTriggerComponent,
value,
onBlur,
onChange,
onFocus,
overrides,
selectRef,
validationText,
variant,
...restProps
} = props;
const boxProps = Box.useProps(restProps);
const className = useClassName({
style: styles.SelectField,
styleProps: props,
themeKey,
prevClassName: boxProps.className,
});
return {
...boxProps,
className,
children: (
<FieldWrapper
description={description}
hint={hint}
isOptional={isOptional}
isRequired={isRequired}
label={label}
overrides={overrides}
state={state}
tooltip={tooltip}
tooltipTriggerComponent={tooltipTriggerComponent}
validationText={validationText}
variant={variant}
>
{({ elementProps }) => (
<ConditionalWrap
condition={Boolean(addonBefore || addonAfter)}
wrap={(children: React.ReactNode) => (
<Group orientation={orientation} overrides={overrides}>
{children}
</Group>
)}
>
<React.Fragment>
{addonBefore}
<Select
autoFocus={autoFocus}
containLabel={containLabel}
defaultValue={defaultValue}
disabled={disabled}
isLoading={isLoading}
isRequired={isRequired}
name={name}
size={size}
options={options}
placeholder={placeholder}
selectProps={selectProps}
selectRef={selectRef}
state={state}
value={value}
onBlur={onBlur}
onChange={onChange}
onFocus={onFocus}
overrides={overrides}
variant={variant}
{...elementProps}
/>
{addonAfter}
</React.Fragment>
</ConditionalWrap>
)}
</FieldWrapper>
),
};
},
{ themeKey: 'SelectField' }
);
export const SelectField = createComponent<SelectFieldProps>(
(props) => {
const SelectFieldProps = useSelectFieldProps(props);
return createElement({
children: props.children,
component: ReakitBox,
use: props.use,
htmlProps: SelectFieldProps,
});
},
{
attach: {
useProps,
displayName: 'SelectField',
},
themeKey: 'SelectField',
}
); | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [macie2](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonmacie.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Macie2 extends PolicyStatement {
public servicePrefix = 'macie2';
/**
* Statement provider for service [macie2](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonmacie.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Grants permission to accept an Amazon Macie membership invitation
*
* Access Level: Write
*
* https://docs.aws.amazon.com/macie/latest/APIReference/invitations-accept.html
*/
public toAcceptInvitation() {
return this.to('AcceptInvitation');
}
/**
* Grants permission to retrieve information about one or more custom data identifiers
*
* Access Level: Read
*
* https://docs.aws.amazon.com/macie/latest/APIReference/custom-data-identifiers-get.html
*/
public toBatchGetCustomDataIdentifiers() {
return this.to('BatchGetCustomDataIdentifiers');
}
/**
* Grants permission to create and define the settings for a sensitive data discovery job
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/macie/latest/APIReference/jobs.html
*/
public toCreateClassificationJob() {
return this.to('CreateClassificationJob');
}
/**
* Grants permission to create and define the settings for a custom data identifier
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/macie/latest/APIReference/custom-data-identifiers.html
*/
public toCreateCustomDataIdentifier() {
return this.to('CreateCustomDataIdentifier');
}
/**
* Grants permission to create and define the settings for a findings filter
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/macie/latest/APIReference/findingsfilters.html
*/
public toCreateFindingsFilter() {
return this.to('CreateFindingsFilter');
}
/**
* Grants permission to send an Amazon Macie membership invitation
*
* Access Level: Write
*
* https://docs.aws.amazon.com/macie/latest/APIReference/invitations.html
*/
public toCreateInvitations() {
return this.to('CreateInvitations');
}
/**
* Grants permission to associate an account with an Amazon Macie administrator account
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/macie/latest/APIReference/members.html
*/
public toCreateMember() {
return this.to('CreateMember');
}
/**
* Grants permission to create sample findings
*
* Access Level: Write
*
* https://docs.aws.amazon.com/macie/latest/APIReference/findings-sample.html
*/
public toCreateSampleFindings() {
return this.to('CreateSampleFindings');
}
/**
* Grants permission to decline Amazon Macie membership invitations
*
* Access Level: Write
*
* https://docs.aws.amazon.com/macie/latest/APIReference/invitations-decline.html
*/
public toDeclineInvitations() {
return this.to('DeclineInvitations');
}
/**
* Grants permission to delete a custom data identifier
*
* Access Level: Write
*
* https://docs.aws.amazon.com/macie/latest/APIReference/custom-data-identifiers-id.html
*/
public toDeleteCustomDataIdentifier() {
return this.to('DeleteCustomDataIdentifier');
}
/**
* Grants permission to delete a findings filter
*
* Access Level: Write
*
* https://docs.aws.amazon.com/macie/latest/APIReference/findingsfilters-id.html
*/
public toDeleteFindingsFilter() {
return this.to('DeleteFindingsFilter');
}
/**
* Grants permission to delete Amazon Macie membership invitations
*
* Access Level: Write
*
* https://docs.aws.amazon.com/macie/latest/APIReference/invitations-delete.html
*/
public toDeleteInvitations() {
return this.to('DeleteInvitations');
}
/**
* Grants permission to delete the association between an Amazon Macie administrator account and an account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/macie/latest/APIReference/members-id.html
*/
public toDeleteMember() {
return this.to('DeleteMember');
}
/**
* Grants permission to retrieve statistical data and other information about S3 buckets that Amazon Macie monitors and analyzes
*
* Access Level: Read
*
* https://docs.aws.amazon.com/macie/latest/APIReference/datasources-s3.html
*/
public toDescribeBuckets() {
return this.to('DescribeBuckets');
}
/**
* Grants permission to retrieve information about the status and settings for a sensitive data discovery job
*
* Access Level: Read
*
* https://docs.aws.amazon.com/macie/latest/APIReference/jobs-jobid.html
*/
public toDescribeClassificationJob() {
return this.to('DescribeClassificationJob');
}
/**
* Grants permission to retrieve information about the Amazon Macie configuration settings for an AWS organization
*
* Access Level: Read
*
* https://docs.aws.amazon.com/macie/latest/APIReference/admin-configuration.html
*/
public toDescribeOrganizationConfiguration() {
return this.to('DescribeOrganizationConfiguration');
}
/**
* Grants permission to disable an Amazon Macie account, which also deletes Macie resources for the account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/macie/latest/APIReference/macie.html
*/
public toDisableMacie() {
return this.to('DisableMacie');
}
/**
* Grants permission to disable an account as the delegated Amazon Macie administrator account for an AWS organization
*
* Access Level: Write
*
* https://docs.aws.amazon.com/macie/latest/APIReference/admin.html
*/
public toDisableOrganizationAdminAccount() {
return this.to('DisableOrganizationAdminAccount');
}
/**
* Grants an Amazon Macie member account with permission to disassociate from its Macie administrator account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/macie/latest/APIReference/administrator-disassociate.html
*/
public toDisassociateFromAdministratorAccount() {
return this.to('DisassociateFromAdministratorAccount');
}
/**
* (Deprecated) Grants an Amazon Macie member account with permission to disassociate from its Macie administrator account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/macie/latest/APIReference/master-disassociate.html
*/
public toDisassociateFromMasterAccount() {
return this.to('DisassociateFromMasterAccount');
}
/**
* Grants an Amazon Macie administrator account with permission to disassociate from a Macie member account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/macie/latest/APIReference/members-disassociate-id.html
*/
public toDisassociateMember() {
return this.to('DisassociateMember');
}
/**
* Grants permission to enable and specify the configuration settings for a new Amazon Macie account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/macie/latest/APIReference/macie.html
*/
public toEnableMacie() {
return this.to('EnableMacie');
}
/**
* Grants permission to enable an account as the delegated Amazon Macie administrator account for an AWS organization
*
* Access Level: Write
*
* https://docs.aws.amazon.com/macie/latest/APIReference/admin.html
*/
public toEnableOrganizationAdminAccount() {
return this.to('EnableOrganizationAdminAccount');
}
/**
* Grants permission to retrieve information about the Amazon Macie administrator account for an account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/macie/latest/APIReference/administrator.html
*/
public toGetAdministratorAccount() {
return this.to('GetAdministratorAccount');
}
/**
* Grants permission to retrieve aggregated statistical data for all the S3 buckets that Amazon Macie monitors and analyzes
*
* Access Level: Read
*
* https://docs.aws.amazon.com/macie/latest/APIReference/datasources-s3-statistics.html
*/
public toGetBucketStatistics() {
return this.to('GetBucketStatistics');
}
/**
* Grants permission to retrieve the settings for exporting sensitive data discovery results
*
* Access Level: Read
*
* https://docs.aws.amazon.com/macie/latest/APIReference/classification-export-configuration.html
*/
public toGetClassificationExportConfiguration() {
return this.to('GetClassificationExportConfiguration');
}
/**
* Grants permission to retrieve information about the settings for a custom data identifier
*
* Access Level: Read
*
* https://docs.aws.amazon.com/macie/latest/APIReference/custom-data-identifiers-id.html
*/
public toGetCustomDataIdentifier() {
return this.to('GetCustomDataIdentifier');
}
/**
* Grants permission to retrieve aggregated statistical data about findings
*
* Access Level: Read
*
* https://docs.aws.amazon.com/macie/latest/APIReference/findings-statistics.html
*/
public toGetFindingStatistics() {
return this.to('GetFindingStatistics');
}
/**
* Grants permission to retrieve the details of one or more findings
*
* Access Level: Read
*
* https://docs.aws.amazon.com/macie/latest/APIReference/findings-describe.html
*/
public toGetFindings() {
return this.to('GetFindings');
}
/**
* Grants permission to retrieve information about the settings for a findings filter
*
* Access Level: Read
*
* https://docs.aws.amazon.com/macie/latest/APIReference/findingsfilters-id.html
*/
public toGetFindingsFilter() {
return this.to('GetFindingsFilter');
}
/**
* Grants permission to retrieve the configuration settings for publishing findings to AWS Security Hub
*
* Access Level: Read
*
* https://docs.aws.amazon.com/macie/latest/APIReference/findings-publication-configuration.html
*/
public toGetFindingsPublicationConfiguration() {
return this.to('GetFindingsPublicationConfiguration');
}
/**
* Grants permission to retrieve the count of Amazon Macie membership invitations that were received by an account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/macie/latest/APIReference/invitations-count.html
*/
public toGetInvitationsCount() {
return this.to('GetInvitationsCount');
}
/**
* Grants permission to retrieve information about the status and configuration settings for an Amazon Macie account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/macie/latest/APIReference/macie.html
*/
public toGetMacieSession() {
return this.to('GetMacieSession');
}
/**
* (Deprecated) Grants permission to retrieve information about the Amazon Macie administrator account for an account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/macie/latest/APIReference/master.html
*/
public toGetMasterAccount() {
return this.to('GetMasterAccount');
}
/**
* Grants permission to retrieve information about an account that's associated with an Amazon Macie administrator account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/macie/latest/APIReference/members-id.html
*/
public toGetMember() {
return this.to('GetMember');
}
/**
* Grants permission to retrieve quotas and aggregated usage data for one or more accounts
*
* Access Level: Read
*
* https://docs.aws.amazon.com/macie/latest/APIReference/usage-statistics.html
*/
public toGetUsageStatistics() {
return this.to('GetUsageStatistics');
}
/**
* Grants permission to retrieve aggregated usage data for an account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/macie/latest/APIReference/usage.html
*/
public toGetUsageTotals() {
return this.to('GetUsageTotals');
}
/**
* Grants permission to retrieve a subset of information about the status and settings for one or more sensitive data discovery jobs
*
* Access Level: List
*
* https://docs.aws.amazon.com/macie/latest/APIReference/jobs-list.html
*/
public toListClassificationJobs() {
return this.to('ListClassificationJobs');
}
/**
* Grants permission to retrieve information about all custom data identifiers
*
* Access Level: List
*
* https://docs.aws.amazon.com/macie/latest/APIReference/custom-data-identifiers-list.html
*/
public toListCustomDataIdentifiers() {
return this.to('ListCustomDataIdentifiers');
}
/**
* Grants permission to retrieve a subset of information about one or more findings
*
* Access Level: List
*
* https://docs.aws.amazon.com/macie/latest/APIReference/findings.html
*/
public toListFindings() {
return this.to('ListFindings');
}
/**
* Grants permission to retrieve information about all findings filters
*
* Access Level: List
*
* https://docs.aws.amazon.com/macie/latest/APIReference/findingsfilters.html
*/
public toListFindingsFilters() {
return this.to('ListFindingsFilters');
}
/**
* Grants permission to retrieve information about all the Amazon Macie membership invitations that were received by an account
*
* Access Level: List
*
* https://docs.aws.amazon.com/macie/latest/APIReference/invitations.html
*/
public toListInvitations() {
return this.to('ListInvitations');
}
/**
* Grants permission to retrieve information about managed data identifiers
*
* Access Level: List
*
* https://docs.aws.amazon.com/macie/latest/APIReference/managed-data-identifiers-list.html
*/
public toListManagedDataIdentifiers() {
return this.to('ListManagedDataIdentifiers');
}
/**
* Grants permission to retrieve information about the Amazon Macie member accounts that are associated with a Macie administrator account
*
* Access Level: List
*
* https://docs.aws.amazon.com/macie/latest/APIReference/members.html
*/
public toListMembers() {
return this.to('ListMembers');
}
/**
* Grants permission to retrieve information about the delegated, Amazon Macie administrator account for an AWS organization
*
* Access Level: List
*
* https://docs.aws.amazon.com/macie/latest/APIReference/admin.html
*/
public toListOrganizationAdminAccounts() {
return this.to('ListOrganizationAdminAccounts');
}
/**
* Grants permission to retrieve the tags for an Amazon Macie resource
*
* Access Level: Read
*
* https://docs.aws.amazon.com/macie/latest/APIReference/tags-resourcearn.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to create or update the settings for storing sensitive data discovery results
*
* Access Level: Write
*
* https://docs.aws.amazon.com/macie/latest/APIReference/classification-export-configuration.html
*/
public toPutClassificationExportConfiguration() {
return this.to('PutClassificationExportConfiguration');
}
/**
* Grants permission to update the configuration settings for publishing findings to AWS Security Hub
*
* Access Level: Write
*
* https://docs.aws.amazon.com/macie/latest/APIReference/findings-publication-configuration.html
*/
public toPutFindingsPublicationConfiguration() {
return this.to('PutFindingsPublicationConfiguration');
}
/**
* Grants permission to retrieve statistical data and other information about AWS resources that Amazon Macie monitors and analyzes
*
* Access Level: Read
*
* https://docs.aws.amazon.com/macie/latest/APIReference/datasources-search-resources.html
*/
public toSearchResources() {
return this.to('SearchResources');
}
/**
* Grants permission to add or update the tags for an Amazon Macie resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/macie/latest/APIReference/tags-resourcearn.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to test a custom data identifier
*
* Access Level: Write
*
* https://docs.aws.amazon.com/macie/latest/APIReference/custom-data-identifiers-test.html
*/
public toTestCustomDataIdentifier() {
return this.to('TestCustomDataIdentifier');
}
/**
* Grants permission to remove tags from an Amazon Macie resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/macie/latest/APIReference/tags-resourcearn.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to change the status of a sensitive data discovery job
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/macie/latest/APIReference/jobs-jobid.html
*/
public toUpdateClassificationJob() {
return this.to('UpdateClassificationJob');
}
/**
* Grants permission to update the settings for a findings filter
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/macie/latest/APIReference/findingsfilters-id.html
*/
public toUpdateFindingsFilter() {
return this.to('UpdateFindingsFilter');
}
/**
* Grants permission to suspend or re-enable an Amazon Macie account, or update the configuration settings for a Macie account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/macie/latest/APIReference/macie.html
*/
public toUpdateMacieSession() {
return this.to('UpdateMacieSession');
}
/**
* Grants an Amazon Macie administrator account with permission to suspend or re-enable a Macie member account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/macie/latest/APIReference/macie-members-id.html
*/
public toUpdateMemberSession() {
return this.to('UpdateMemberSession');
}
/**
* Grants permission to update Amazon Macie configuration settings for an AWS organization
*
* Access Level: Write
*
* https://docs.aws.amazon.com/macie/latest/APIReference/admin-configuration.html
*/
public toUpdateOrganizationConfiguration() {
return this.to('UpdateOrganizationConfiguration');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"AcceptInvitation",
"CreateClassificationJob",
"CreateCustomDataIdentifier",
"CreateFindingsFilter",
"CreateInvitations",
"CreateMember",
"CreateSampleFindings",
"DeclineInvitations",
"DeleteCustomDataIdentifier",
"DeleteFindingsFilter",
"DeleteInvitations",
"DeleteMember",
"DisableMacie",
"DisableOrganizationAdminAccount",
"DisassociateFromAdministratorAccount",
"DisassociateFromMasterAccount",
"DisassociateMember",
"EnableMacie",
"EnableOrganizationAdminAccount",
"PutClassificationExportConfiguration",
"PutFindingsPublicationConfiguration",
"TestCustomDataIdentifier",
"UpdateClassificationJob",
"UpdateFindingsFilter",
"UpdateMacieSession",
"UpdateMemberSession",
"UpdateOrganizationConfiguration"
],
"Read": [
"BatchGetCustomDataIdentifiers",
"DescribeBuckets",
"DescribeClassificationJob",
"DescribeOrganizationConfiguration",
"GetAdministratorAccount",
"GetBucketStatistics",
"GetClassificationExportConfiguration",
"GetCustomDataIdentifier",
"GetFindingStatistics",
"GetFindings",
"GetFindingsFilter",
"GetFindingsPublicationConfiguration",
"GetInvitationsCount",
"GetMacieSession",
"GetMasterAccount",
"GetMember",
"GetUsageStatistics",
"GetUsageTotals",
"ListTagsForResource",
"SearchResources"
],
"List": [
"ListClassificationJobs",
"ListCustomDataIdentifiers",
"ListFindings",
"ListFindingsFilters",
"ListInvitations",
"ListManagedDataIdentifiers",
"ListMembers",
"ListOrganizationAdminAccounts"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type ClassificationJob to the statement
*
* https://docs.aws.amazon.com/macie/latest/user/what-is-macie.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onClassificationJob(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:macie2:${Region}:${Account}:classification-job/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type CustomDataIdentifier to the statement
*
* https://docs.aws.amazon.com/macie/latest/user/what-is-macie.html.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onCustomDataIdentifier(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:macie2:${Region}:${Account}:custom-data-identifier/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type FindingsFilter to the statement
*
* https://docs.aws.amazon.com/macie/latest/user/what-is-macie.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onFindingsFilter(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:macie2:${Region}:${Account}:findings-filter/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Member to the statement
*
* https://docs.aws.amazon.com/macie/latest/user/what-is-macie.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onMember(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:macie2:${Region}:${Account}:member/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
import { createElement } from '@syncfusion/ej2-base';
import { Diagram } from '../../../src/diagram/diagram';
import { DiagramElement } from '../../../src/diagram/core/elements/diagram-element';
import { Canvas } from '../../../src/diagram/core/containers/canvas';
import { HorizontalAlignment, VerticalAlignment, RelativeMode, UnitMode } from '../../../src/diagram/enum/enum';
import { Thickness } from '../../../src/diagram/core/appearance';
import {profile , inMB, getMemoryProfile} from '../../../spec/common.spec';
describe('Diagram Control', () => {
describe('Simple canvas panel without children', () => {
let diagram: Diagram;
let ele: HTMLElement;
let canvas: Canvas;
let canvasWithMinMaxSize: Canvas;
let canvasWithoutSize: Canvas;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagram4' });
document.body.appendChild(ele);
canvas = new Canvas();
canvas.pivot = { x: 0, y: 0 };
canvas.offsetX = 200;
canvas.offsetY = 100;
canvas.width = 200;
canvas.height = 200;
canvas.minWidth = canvas.minHeight = 125;
canvas.maxWidth = canvas.maxHeight = 150;
canvasWithMinMaxSize = new Canvas();
canvasWithMinMaxSize.pivot = { x: 0, y: 0 };
canvasWithMinMaxSize.offsetX = 400;
canvasWithMinMaxSize.offsetY = 100;
canvasWithMinMaxSize.minWidth = canvasWithMinMaxSize.minHeight = 125;
canvasWithMinMaxSize.maxWidth = canvasWithMinMaxSize.maxHeight = 150;
canvasWithoutSize = new Canvas();
canvasWithoutSize.pivot = { x: 0, y: 0 };
canvasWithoutSize.offsetX = 600;
canvasWithoutSize.offsetY = 100;
diagram = new Diagram({ mode: 'Canvas', width: '1000px', height: '600px', basicElements: [canvas, canvasWithMinMaxSize, canvasWithoutSize] });
diagram.appendTo('#diagram4');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking canvas panel and with size in SVG rendering Mode', (done: Function) => {
expect(canvas.actualSize.width === 150 && canvas.actualSize.height === 150).toBe(true);
done();
});
it('Checking canvas panel without size and with min max size in SVG rendering Mode', (done: Function) => {
expect(canvasWithMinMaxSize.actualSize.width === 125 && canvasWithMinMaxSize.actualSize.height === 125).toBe(true);
done();
});
it('Checking canvas panel without size and without min max size in SVG rendering Mode', (done: Function) => {
expect(canvasWithoutSize.actualSize.width === 0 && canvasWithoutSize.actualSize.height === 0).toBe(true);
done();
});
});
describe('Simple canvas panel with empty children collection', () => {
let diagram: Diagram;
let ele: HTMLElement;
let canvas: Canvas = new Canvas();
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagram5' });
document.body.appendChild(ele);
canvas.pivot = { x: 0, y: 0 };
canvas.offsetX = 200;
canvas.offsetY = 100;
canvas.width = 100;
canvas.height = 100;
canvas.children = [];
diagram = new Diagram({ mode: 'Canvas', width: '1000px', height: '600px', basicElements: [canvas], });
diagram.appendTo('#diagram5');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking Simple canvas panel with empty children collection in SVG rendering Mode', (done: Function) => {
expect(canvas.actualSize.width === 100 && canvas.actualSize.height === 100).toBe(true);
done();
});
});
describe('Simple canvas panel with one child', () => {
let diagram: Diagram;
let ele: HTMLElement;
let child: DiagramElement;
let canvasWithoutSize: Canvas;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagram6' });
document.body.appendChild(ele);
let canvas: Canvas = new Canvas();
canvas.pivot = { x: 0, y: 0 };
canvas.offsetX = 200;
canvas.offsetY = 100;
canvas.width = 100;
canvas.height = 100;
child = new DiagramElement();
child.margin = { left: 10, right: 10, top: 10, bottom: 10 };
canvas.children = [child];
canvasWithoutSize = new Canvas();
canvasWithoutSize.offsetX = 400;
canvasWithoutSize.offsetY = 100;
let child2: DiagramElement = new DiagramElement();
child2.width = 100;
child2.height = 100;
canvasWithoutSize.children = [child2];
diagram = new Diagram({ mode: 'Canvas', width: '1000px', height: '600px', basicElements: [canvas, canvasWithoutSize] });
diagram.appendTo('#diagram6');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking canvas panel with a child - inherits size from canvas in SVG rendering Mode', (done: Function) => {
expect(child.actualSize.width === 80 && child.actualSize.height === 80).toBe(true);
done();
});
it('Checking canvas panel with a child - canvas wraps the child in SVG rendering Mode', (done: Function) => {
expect(canvasWithoutSize.actualSize.width === 100 && canvasWithoutSize.actualSize.height === 100).toBe(true);
done();
});
});
describe('Canvas Panel with one child with absolute position', () => {
let diagram: Diagram;
let ele: HTMLElement;
let child: DiagramElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagram7' });
document.body.appendChild(ele);
let canvas: Canvas = new Canvas();
canvas.pivot = { x: 0, y: 0 };
canvas.offsetX = 200;
canvas.offsetY = 100;
canvas.width = 200;
canvas.height = 200;
child = new DiagramElement();
child.setOffsetWithRespectToBounds(95, 95, 'Absolute');
child.width = 10;
child.height = 10;
canvas.children = [child];
diagram = new Diagram({ mode: 'Canvas', width: '1000px', height: '600px', basicElements: [canvas] });
diagram.appendTo('#diagram7');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking canvas panel with a child with absolute position in SVG rendering Mode', (done: Function) => {
expect(child.offsetX === 300 && child.offsetY === 200).toBe(true);
done();
});
});
describe('Simple canvas panel without size and two children', () => {
let diagram: Diagram;
let ele: HTMLElement;
let canvas: Canvas;
let child1: DiagramElement;
let child2: DiagramElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagram8' });
document.body.appendChild(ele);
canvas = new Canvas();
canvas.pivot = { x: 0, y: 0 };
canvas.offsetX = 200;
canvas.offsetY = 100;
canvas.style.fill = 'wheat';
child1 = new DiagramElement();
child1.width = 100;
child1.height = 100;
child1.margin.left = child1.margin.top = 10;
child2 = new DiagramElement();
child2.width = 100; child2.height = 100;
child2.margin.left = 190;
child2.margin.top = 190;
canvas.children = [child1, child2];
diagram = new Diagram({ mode: 'Canvas', width: '1000px', height: '600px', basicElements: [canvas] });
diagram.appendTo('#diagram8');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking canvas panel without size with two children(margin) in SVG rendering Mode', (done: Function) => {
expect(canvas.actualSize.width === 290 && canvas.actualSize.height === 290 && child1.offsetX === 260 && child2.offsetX === 440 &&
child1.offsetY === 160 && child2.offsetY === 340).toBe(true);
done();
});
});
describe('Simple canvas panel with padding and two children', () => {
let diagram: Diagram;
let ele: HTMLElement;
let canvas: Canvas;
let child1: DiagramElement;
let child2: DiagramElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagram9' });
document.body.appendChild(ele);
canvas = new Canvas();
canvas.padding = new Thickness(10, 10, 10, 10);
canvas.pivot = { x: 0, y: 0 };
canvas.offsetX = 200;
canvas.offsetY = 100;
canvas.style.fill = 'wheat';
child1 = new DiagramElement();
child1.width = 100;
child1.height = 100;
child1.margin.left = child1.margin.top = 10;
child2 = new DiagramElement();
child2.width = 100; child2.height = 100;
child2.margin.left = 190;
child2.margin.top = 190;
canvas.children = [child1, child2];
diagram = new Diagram({ mode: 'Canvas', width: '1000px', height: '600px', basicElements: [canvas] });
diagram.appendTo('#diagram9');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking canvas panel with padding and with two children in SVG rendering Mode', (done: Function) => {
expect(canvas.actualSize.width === 310 && canvas.actualSize.height === 310 && child1.offsetX === 270 && child2.offsetX === 450 &&
child1.offsetY === 170 && child2.offsetY === 350).toBe(true);
done();
});
});
describe('Simple canvas panel with size and two children', () => {
let diagram: Diagram;
let ele: HTMLElement;
let canvas: Canvas;
let child1: DiagramElement;
let child2: DiagramElement;
let child3: DiagramElement;
let child4: DiagramElement;
let child5: DiagramElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagram11' });
document.body.appendChild(ele);
canvas = new Canvas();
canvas.pivot = { x: 0, y: 0 };
canvas.offsetX = 200;
canvas.offsetY = 100;
canvas.width = 400;
canvas.height = 400;
child1 = new DiagramElement();
child1.width = 100;
child1.height = 100;
child1.horizontalAlignment = 'Center';
child1.verticalAlignment = 'Stretch';
child1.relativeMode = 'Object';
child2 = new DiagramElement();
child2.width = 100; child2.height = 100;
child2.horizontalAlignment = 'Stretch';
child2.verticalAlignment = 'Center';
child2.relativeMode = 'Object';
child3 = new DiagramElement();
child3.width = 100; child3.height = 100;
child3.horizontalAlignment = 'Left';
child3.verticalAlignment = 'Top';
child3.relativeMode = 'Object';
child3.margin.left = child3.margin.top = 10;
child4 = new DiagramElement();
child4.width = 100; child4.height = 100;
child4.horizontalAlignment = 'Right';
child4.verticalAlignment = 'Bottom';
child4.relativeMode = 'Object';
child4.margin.right = 10;
child4.margin.bottom = 10;
child5 = new DiagramElement();
child5.width = 100;
child5.height = 100;
child5.relativeMode = 'Object';
canvas.children = [child1, child2, child3, child4, child5];
diagram = new Diagram({ mode: 'Canvas', width: '1000px', height: '600px', basicElements: [canvas] });
diagram.appendTo('#diagram11');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking canvas panel with size and with two children(relative position) in SVG rendering Mode', (done: Function) => {
expect(canvas.actualSize.width === 400 && canvas.actualSize.height === 400 &&
child1.offsetX === 400 && child1.offsetY === 300 &&
child2.offsetX === 400 && child2.offsetY === 300 &&
child3.offsetX === 260 && child3.offsetY === 160 &&
child4.offsetX === 540 && child4.offsetY === 440 &&
child5.offsetX === 250 && child5.offsetY === 150).toBe(true);
done();
});
});
describe('Simple canvas panel with two rotated children', () => {
let diagram: Diagram;
let ele: HTMLElement;
let canvas: Canvas;
let child1: DiagramElement;
let child2: DiagramElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagram12' });
document.body.appendChild(ele);
canvas = new Canvas();
canvas.pivot = { x: 0, y: 0 };
canvas.offsetX = 200;
canvas.offsetY = 100;
canvas.style.fill = 'wheat';
canvas.padding = new Thickness(10, 10, 10, 10);
child1 = new DiagramElement();
child1.width = 200;
child1.height = 100;
child1.rotateAngle = 45;
child2 = new DiagramElement();
child2.width = 100; child2.height = 100;
child2.margin.left = 190;
child2.margin.top = 190;
child2.rotateAngle = 45;
canvas.children = [child1, child2];
diagram = new Diagram({ mode: 'Canvas', width: 1000, height: 1000, basicElements: [canvas] });
diagram.appendTo('#diagram12');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking canvas panel with two rotated children in SVG rendering Mode', (done: Function) => {
expect(canvas.actualSize.width === 351.41999999999996 && canvas.actualSize.height === 351.41999999999996 && child1.offsetX === 310 && child2.offsetX === 450 &&
child1.offsetY === 160 && child2.offsetY === 350).toBe(true);
done();
});
});
describe('Rotated canvas panel without size and two rotated children', () => {
let diagram: Diagram;
let ele: HTMLElement;
let canvas: Canvas;
let child1: DiagramElement;
let child2: DiagramElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagram13' });
document.body.appendChild(ele);
canvas = new Canvas();
canvas.pivot = { x: 0, y: 0 };
canvas.offsetX = 200;
canvas.offsetY = 100;
canvas.style.fill = 'wheat';
canvas.rotateAngle = 45;
child1 = new DiagramElement();
child1.width = 200;
child1.height = 100;
child1.margin.left = child1.margin.top = 10;
child2 = new DiagramElement();
child2.width = 100; child2.height = 100;
child2.margin.left = 190;
child2.margin.top = 190;
canvas.children = [child1, child2];
diagram = new Diagram({ mode: 'Canvas', width: '1000px', height: '600px', basicElements: [canvas] });
diagram.appendTo('#diagram13');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking canvas panel without size and rotated children in SVG rendering Mode', (done: Function) => {
expect(canvas.actualSize.width === 290 && canvas.actualSize.height === 290 && child1.offsetX === 235.36 && child2.offsetX === 200 &&
child1.offsetY === 220.21 && child2.offsetY === 439.41 && child1.parentTransform === canvas.parentTransform + canvas.rotateAngle &&
child2.parentTransform === canvas.parentTransform + canvas.rotateAngle).toBe(true);
done();
});
});
describe('Rotated canvas panel without size and two rotated children', () => {
let diagram: Diagram;
let ele: HTMLElement;
let canvas: Canvas;
let child1: DiagramElement;
let child2: DiagramElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagram14' });
document.body.appendChild(ele);
canvas = new Canvas();
canvas.pivot = { x: 0, y: 0 };
canvas.offsetX = 200;
canvas.offsetY = 100;
canvas.style.fill = 'wheat';
canvas.rotateAngle = 45;
child1 = new DiagramElement();
child1.width = 200;
child1.height = 100;
child1.margin.left = child1.margin.top = 10;
child1.rotateAngle = 45;
child2 = new Canvas();
child2.width = 100; child2.height = 100;
child2.margin.left = 190;
child2.margin.top = 190;
child2.rotateAngle = 45;
canvas.children = [child1, child2];
diagram = new Diagram({ mode: 'Canvas', width: '1000px', height: '600px', basicElements: [canvas] });
diagram.appendTo('#diagram14');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking rotated canvas with rotated children in SVG rendering Mode', (done: Function) => {
expect(canvas.actualSize.width === 331.41999999999996 && canvas.actualSize.height === 331.41999999999996 && child1.offsetX === 235.36 && child2.offsetX === 200 &&
child1.offsetY === 220.21 && child2.offsetY === 439.41 && child1.parentTransform === canvas.parentTransform + canvas.rotateAngle &&
child2.parentTransform === canvas.parentTransform + canvas.rotateAngle).toBe(true);
done();
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
})
});
//write test case for nested canvas
}); | the_stack |
import * as Common from '../../../../core/common/common.js';
import * as i18n from '../../../../core/i18n/i18n.js';
import * as Platform from '../../../../core/platform/platform.js';
import * as UI from '../../legacy.js';
import {MinimalTimeWindowMs} from './FlameChart.js';
export interface ChartViewportDelegate {
windowChanged(startTime: number, endTime: number, animate: boolean): void;
updateRangeSelection(startTime: number, endTime: number): void;
setSize(width: number, height: number): void;
update(): void;
}
export class ChartViewport extends UI.Widget.VBox {
private readonly delegate: ChartViewportDelegate;
viewportElement: HTMLElement;
private alwaysShowVerticalScrollInternal: boolean;
private rangeSelectionEnabled: boolean;
private vScrollElement: HTMLElement;
private vScrollContent: HTMLElement;
private readonly selectionOverlay: HTMLElement;
private selectedTimeSpanLabel: HTMLElement;
private cursorElement: HTMLElement;
private isDraggingInternal!: boolean;
private totalHeight!: number;
private offsetHeight!: number;
private scrollTop!: number;
private rangeSelectionStart: number|null;
private rangeSelectionEnd: number|null;
private dragStartPointX!: number;
private dragStartPointY!: number;
private dragStartScrollTop!: number;
private visibleLeftTime!: number;
private visibleRightTime!: number;
private offsetWidth!: number;
private targetLeftTime!: number;
private targetRightTime!: number;
private selectionOffsetShiftX!: number;
private selectionOffsetShiftY!: number;
private selectionStartX!: number|null;
private lastMouseOffsetX!: number;
private minimumBoundary!: number;
private totalTime!: number;
private updateTimerId?: number;
private cancelWindowTimesAnimation?: (() => void)|null;
constructor(delegate: ChartViewportDelegate) {
super();
this.registerRequiredCSS('ui/legacy/components/perf_ui/chartViewport.css');
this.delegate = delegate;
this.viewportElement = this.contentElement.createChild('div', 'fill');
this.viewportElement.addEventListener('mousemove', this.updateCursorPosition.bind(this), false);
this.viewportElement.addEventListener('mouseout', this.onMouseOut.bind(this), false);
this.viewportElement.addEventListener('wheel', this.onMouseWheel.bind(this), false);
this.viewportElement.addEventListener('keydown', this.onChartKeyDown.bind(this), false);
this.viewportElement.addEventListener('keyup', this.onChartKeyUp.bind(this), false);
UI.UIUtils.installDragHandle(
this.viewportElement, this.startDragging.bind(this), this.dragging.bind(this), this.endDragging.bind(this),
'-webkit-grabbing', null);
UI.UIUtils.installDragHandle(
this.viewportElement, this.startRangeSelection.bind(this), this.rangeSelectionDragging.bind(this),
this.endRangeSelection.bind(this), 'text', null);
this.alwaysShowVerticalScrollInternal = false;
this.rangeSelectionEnabled = true;
this.vScrollElement = this.contentElement.createChild('div', 'chart-viewport-v-scroll');
this.vScrollContent = this.vScrollElement.createChild('div');
this.vScrollElement.addEventListener('scroll', this.onScroll.bind(this), false);
this.selectionOverlay = this.contentElement.createChild('div', 'chart-viewport-selection-overlay hidden');
this.selectedTimeSpanLabel = this.selectionOverlay.createChild('div', 'time-span');
this.cursorElement = this.contentElement.createChild('div', 'chart-cursor-element hidden');
this.reset();
this.rangeSelectionStart = null;
this.rangeSelectionEnd = null;
}
alwaysShowVerticalScroll(): void {
this.alwaysShowVerticalScrollInternal = true;
this.vScrollElement.classList.add('always-show-scrollbar');
}
disableRangeSelection(): void {
this.rangeSelectionEnabled = false;
this.rangeSelectionStart = null;
this.rangeSelectionEnd = null;
this.updateRangeSelectionOverlay();
}
isDragging(): boolean {
return this.isDraggingInternal;
}
elementsToRestoreScrollPositionsFor(): Element[] {
return [this.vScrollElement];
}
private updateScrollBar(): void {
const showScroll = this.alwaysShowVerticalScrollInternal || this.totalHeight > this.offsetHeight;
if (this.vScrollElement.classList.contains('hidden') !== showScroll) {
return;
}
this.vScrollElement.classList.toggle('hidden', !showScroll);
this.updateContentElementSize();
}
onResize(): void {
this.updateScrollBar();
this.updateContentElementSize();
this.scheduleUpdate();
}
reset(): void {
this.vScrollElement.scrollTop = 0;
this.scrollTop = 0;
this.rangeSelectionStart = null;
this.rangeSelectionEnd = null;
this.isDraggingInternal = false;
this.dragStartPointX = 0;
this.dragStartPointY = 0;
this.dragStartScrollTop = 0;
this.visibleLeftTime = 0;
this.visibleRightTime = 0;
this.offsetWidth = 0;
this.offsetHeight = 0;
this.totalHeight = 0;
this.targetLeftTime = 0;
this.targetRightTime = 0;
this.updateContentElementSize();
}
private updateContentElementSize(): void {
let offsetWidth: number = this.vScrollElement.offsetLeft;
if (!offsetWidth) {
offsetWidth = this.contentElement.offsetWidth;
}
this.offsetWidth = offsetWidth;
this.offsetHeight = this.contentElement.offsetHeight;
this.delegate.setSize(this.offsetWidth, this.offsetHeight);
}
setContentHeight(totalHeight: number): void {
this.totalHeight = totalHeight;
this.vScrollContent.style.height = totalHeight + 'px';
this.updateScrollBar();
this.updateContentElementSize();
if (this.scrollTop + this.offsetHeight <= totalHeight) {
return;
}
this.scrollTop = Math.max(0, totalHeight - this.offsetHeight);
this.vScrollElement.scrollTop = this.scrollTop;
}
setScrollOffset(offset: number, height?: number): void {
height = height || 0;
if (this.vScrollElement.scrollTop > offset) {
this.vScrollElement.scrollTop = offset;
} else if (this.vScrollElement.scrollTop < offset - this.offsetHeight + height) {
this.vScrollElement.scrollTop = offset - this.offsetHeight + height;
}
}
scrollOffset(): number {
return this.vScrollElement.scrollTop;
}
chartHeight(): number {
return this.offsetHeight;
}
setBoundaries(zeroTime: number, totalTime: number): void {
this.minimumBoundary = zeroTime;
this.totalTime = totalTime;
}
private onMouseWheel(e: Event): void {
const wheelEvent = (e as WheelEvent);
const doZoomInstead = wheelEvent.shiftKey !==
(Common.Settings.Settings.instance().moduleSetting('flamechartMouseWheelAction').get() === 'zoom');
const panVertically = !doZoomInstead && (wheelEvent.deltaY || Math.abs(wheelEvent.deltaX) === 53);
const panHorizontally = doZoomInstead && Math.abs(wheelEvent.deltaX) > Math.abs(wheelEvent.deltaY);
if (panVertically) {
this.vScrollElement.scrollTop += (wheelEvent.deltaY || wheelEvent.deltaX) / 53 * this.offsetHeight / 8;
} else if (panHorizontally) {
this.handlePanGesture(wheelEvent.deltaX, /* animate */ true);
} else { // Zoom.
const wheelZoomSpeed = 1 / 53;
this.handleZoomGesture(Math.pow(1.2, (wheelEvent.deltaY || wheelEvent.deltaX) * wheelZoomSpeed) - 1);
}
// Block swipe gesture.
e.consume(true);
}
private startDragging(event: MouseEvent): boolean {
if (event.shiftKey) {
return false;
}
this.isDraggingInternal = true;
this.dragStartPointX = event.pageX;
this.dragStartPointY = event.pageY;
this.dragStartScrollTop = this.vScrollElement.scrollTop;
this.viewportElement.style.cursor = '';
return true;
}
private dragging(event: MouseEvent): void {
const pixelShift = this.dragStartPointX - event.pageX;
this.dragStartPointX = event.pageX;
this.handlePanGesture(pixelShift);
const pixelScroll = this.dragStartPointY - event.pageY;
this.vScrollElement.scrollTop = this.dragStartScrollTop + pixelScroll;
}
private endDragging(): void {
this.isDraggingInternal = false;
}
private startRangeSelection(event: MouseEvent): boolean {
if (!event.shiftKey || !this.rangeSelectionEnabled) {
return false;
}
this.isDraggingInternal = true;
this.selectionOffsetShiftX = event.offsetX - event.pageX;
this.selectionOffsetShiftY = event.offsetY - event.pageY;
this.selectionStartX = event.offsetX;
const style = this.selectionOverlay.style;
style.left = this.selectionStartX + 'px';
style.width = '1px';
this.selectedTimeSpanLabel.textContent = '';
this.selectionOverlay.classList.remove('hidden');
return true;
}
private endRangeSelection(): void {
this.isDraggingInternal = false;
this.selectionStartX = null;
}
hideRangeSelection(): void {
this.selectionOverlay.classList.add('hidden');
this.rangeSelectionStart = null;
this.rangeSelectionEnd = null;
}
setRangeSelection(startTime: number, endTime: number): void {
if (!this.rangeSelectionEnabled) {
return;
}
this.rangeSelectionStart = Math.min(startTime, endTime);
this.rangeSelectionEnd = Math.max(startTime, endTime);
this.updateRangeSelectionOverlay();
this.delegate.updateRangeSelection(this.rangeSelectionStart, this.rangeSelectionEnd);
}
onClick(event: Event): void {
const mouseEvent = (event as MouseEvent);
const time = this.pixelToTime(mouseEvent.offsetX);
if (this.rangeSelectionStart !== null && this.rangeSelectionEnd !== null && time >= this.rangeSelectionStart &&
time <= this.rangeSelectionEnd) {
return;
}
this.hideRangeSelection();
}
private rangeSelectionDragging(event: MouseEvent): void {
const x = Platform.NumberUtilities.clamp(event.pageX + this.selectionOffsetShiftX, 0, this.offsetWidth);
const start = this.pixelToTime(this.selectionStartX || 0);
const end = this.pixelToTime(x);
this.setRangeSelection(start, end);
}
private updateRangeSelectionOverlay(): void {
const rangeSelectionStart = this.rangeSelectionStart || 0;
const rangeSelectionEnd = this.rangeSelectionEnd || 0;
const margin = 100;
const left =
Platform.NumberUtilities.clamp(this.timeToPosition(rangeSelectionStart), -margin, this.offsetWidth + margin);
const right =
Platform.NumberUtilities.clamp(this.timeToPosition(rangeSelectionEnd), -margin, this.offsetWidth + margin);
const style = this.selectionOverlay.style;
style.left = left + 'px';
style.width = (right - left) + 'px';
const timeSpan = rangeSelectionEnd - rangeSelectionStart;
this.selectedTimeSpanLabel.textContent = i18n.TimeUtilities.preciseMillisToString(timeSpan, 2);
}
private onScroll(): void {
this.scrollTop = this.vScrollElement.scrollTop;
this.scheduleUpdate();
}
private onMouseOut(): void {
this.lastMouseOffsetX = -1;
this.showCursor(false);
}
private updateCursorPosition(e: Event): void {
const mouseEvent = (e as MouseEvent);
this.showCursor(mouseEvent.shiftKey);
this.cursorElement.style.left = mouseEvent.offsetX + 'px';
this.lastMouseOffsetX = mouseEvent.offsetX;
}
pixelToTime(x: number): number {
return this.pixelToTimeOffset(x) + this.visibleLeftTime;
}
pixelToTimeOffset(x: number): number {
return x * (this.visibleRightTime - this.visibleLeftTime) / this.offsetWidth;
}
timeToPosition(time: number): number {
return Math.floor(
(time - this.visibleLeftTime) / (this.visibleRightTime - this.visibleLeftTime) * this.offsetWidth);
}
timeToPixel(): number {
return this.offsetWidth / (this.visibleRightTime - this.visibleLeftTime);
}
private showCursor(visible: boolean): void {
this.cursorElement.classList.toggle('hidden', !visible || this.isDraggingInternal);
}
private onChartKeyDown(e: Event): void {
const mouseEvent = (e as MouseEvent);
this.showCursor(mouseEvent.shiftKey);
this.handleZoomPanKeys(e);
}
private onChartKeyUp(e: Event): void {
const mouseEvent = (e as MouseEvent);
this.showCursor(mouseEvent.shiftKey);
}
private handleZoomPanKeys(e: Event): void {
if (!UI.KeyboardShortcut.KeyboardShortcut.hasNoModifiers(e)) {
return;
}
const keyboardEvent = (e as KeyboardEvent);
const zoomFactor = keyboardEvent.shiftKey ? 0.8 : 0.3;
const panOffset = keyboardEvent.shiftKey ? 320 : 160;
switch (keyboardEvent.code) {
case 'KeyA':
this.handlePanGesture(-panOffset, /* animate */ true);
break;
case 'KeyD':
this.handlePanGesture(panOffset, /* animate */ true);
break;
case 'KeyW':
this.handleZoomGesture(-zoomFactor);
break;
case 'KeyS':
this.handleZoomGesture(zoomFactor);
break;
default:
return;
}
e.consume(true);
}
private handleZoomGesture(zoom: number): void {
const bounds = {left: this.targetLeftTime, right: this.targetRightTime};
const cursorTime = this.pixelToTime(this.lastMouseOffsetX);
bounds.left += (bounds.left - cursorTime) * zoom;
bounds.right += (bounds.right - cursorTime) * zoom;
this.requestWindowTimes(bounds, /* animate */ true);
}
private handlePanGesture(offset: number, animate?: boolean): void {
const bounds = {left: this.targetLeftTime, right: this.targetRightTime};
const timeOffset = Platform.NumberUtilities.clamp(
this.pixelToTimeOffset(offset), this.minimumBoundary - bounds.left,
this.totalTime + this.minimumBoundary - bounds.right);
bounds.left += timeOffset;
bounds.right += timeOffset;
this.requestWindowTimes(bounds, Boolean(animate));
}
private requestWindowTimes(
bounds: {
left: number,
right: number,
},
animate: boolean): void {
const maxBound = this.minimumBoundary + this.totalTime;
if (bounds.left < this.minimumBoundary) {
bounds.right = Math.min(bounds.right + this.minimumBoundary - bounds.left, maxBound);
bounds.left = this.minimumBoundary;
} else if (bounds.right > maxBound) {
bounds.left = Math.max(bounds.left - bounds.right + maxBound, this.minimumBoundary);
bounds.right = maxBound;
}
if (bounds.right - bounds.left < MinimalTimeWindowMs) {
return;
}
this.delegate.windowChanged(bounds.left, bounds.right, animate);
}
scheduleUpdate(): void {
if (this.updateTimerId || this.cancelWindowTimesAnimation) {
return;
}
this.updateTimerId = this.element.window().requestAnimationFrame(() => {
this.updateTimerId = 0;
this.update();
});
}
private update(): void {
this.updateRangeSelectionOverlay();
this.delegate.update();
}
setWindowTimes(startTime: number, endTime: number, animate?: boolean): void {
if (startTime === this.targetLeftTime && endTime === this.targetRightTime) {
return;
}
if (!animate || this.visibleLeftTime === 0 || this.visibleRightTime === Infinity ||
(startTime === 0 && endTime === Infinity) || (startTime === Infinity && endTime === Infinity)) {
// Skip animation, move instantly.
this.targetLeftTime = startTime;
this.targetRightTime = endTime;
this.visibleLeftTime = startTime;
this.visibleRightTime = endTime;
this.scheduleUpdate();
return;
}
if (this.cancelWindowTimesAnimation) {
this.cancelWindowTimesAnimation();
this.visibleLeftTime = this.targetLeftTime;
this.visibleRightTime = this.targetRightTime;
}
this.targetLeftTime = startTime;
this.targetRightTime = endTime;
this.cancelWindowTimesAnimation = UI.UIUtils.animateFunction(
this.element.window(), animateWindowTimes.bind(this),
[{from: this.visibleLeftTime, to: startTime}, {from: this.visibleRightTime, to: endTime}], 100, () => {
this.cancelWindowTimesAnimation = null;
});
function animateWindowTimes(this: ChartViewport, startTime: number, endTime: number): void {
this.visibleLeftTime = startTime;
this.visibleRightTime = endTime;
this.update();
}
}
windowLeftTime(): number {
return this.visibleLeftTime;
}
windowRightTime(): number {
return this.visibleRightTime;
}
} | the_stack |
import { TKeyType, IKey, ManagedKeyInfo, MinimalImportableKey, RequireOnly } from '@veramo/core'
import { AbstractKeyManagementSystem, AbstractPrivateKeyStore } from '@veramo/key-manager'
import { ManagedPrivateKey } from '@veramo/key-manager'
import { EdDSASigner, ES256KSigner } from 'did-jwt'
import {
generateKeyPair as generateSigningKeyPair,
convertPublicKeyToX25519,
convertSecretKeyToX25519,
extractPublicKeyFromSecretKey,
} from '@stablelib/ed25519'
import {
generateKeyPair as generateEncryptionKeypair,
generateKeyPairFromSeed as generateEncryptionKeyPairFromSeed,
sharedKey,
} from '@stablelib/x25519'
import { TypedDataDomain, TypedDataField } from '@ethersproject/abstract-signer'
import { TransactionRequest } from '@ethersproject/abstract-provider'
import { toUtf8String } from '@ethersproject/strings'
import { parse } from '@ethersproject/transactions'
import { Wallet } from '@ethersproject/wallet'
import { SigningKey } from '@ethersproject/signing-key'
import { randomBytes } from '@ethersproject/random'
import { arrayify, hexlify } from '@ethersproject/bytes'
import * as u8a from 'uint8arrays'
import Debug from 'debug'
const debug = Debug('veramo:kms:local')
export class KeyManagementSystem extends AbstractKeyManagementSystem {
private readonly keyStore: AbstractPrivateKeyStore
constructor(keyStore: AbstractPrivateKeyStore) {
super()
this.keyStore = keyStore
}
async importKey(args: Omit<MinimalImportableKey, 'kms'>): Promise<ManagedKeyInfo> {
if (!args.type || !args.privateKeyHex) {
throw new Error('invalid_argument: type and privateKeyHex are required to import a key')
}
const managedKey = this.asManagedKeyInfo({ alias: args.kid, ...args })
await this.keyStore.import({ alias: managedKey.kid, ...args })
debug('imported key', managedKey.type, managedKey.publicKeyHex)
return managedKey
}
async listKeys(): Promise<ManagedKeyInfo[]> {
const privateKeys = await this.keyStore.list({})
const managedKeys = privateKeys.map((key) => this.asManagedKeyInfo(key))
return managedKeys
}
async createKey({ type }: { type: TKeyType }): Promise<ManagedKeyInfo> {
let key: ManagedKeyInfo
switch (type) {
case 'Ed25519': {
const keyPairEd25519 = generateSigningKeyPair()
key = await this.importKey({
type,
privateKeyHex: u8a.toString(keyPairEd25519.secretKey, 'base16'),
})
break
}
case 'Secp256k1': {
const privateBytes = randomBytes(32)
key = await this.importKey({
type,
privateKeyHex: u8a.toString(privateBytes, 'base16'),
})
break
}
case 'X25519': {
const keyPairX25519 = generateEncryptionKeypair()
key = await this.importKey({
type,
privateKeyHex: u8a.toString(keyPairX25519.secretKey, 'base16'),
})
break
}
default:
throw Error('not_supported: Key type not supported: ' + type)
}
debug('Created key', type, key.publicKeyHex)
return key
}
async deleteKey(args: { kid: string }) {
return await this.keyStore.delete({ alias: args.kid })
}
async sign({
keyRef,
algorithm,
data,
}: {
keyRef: Pick<IKey, 'kid'>
algorithm?: string
data: Uint8Array
}): Promise<string> {
let managedKey: ManagedPrivateKey
try {
managedKey = await this.keyStore.get({ alias: keyRef.kid })
} catch (e) {
throw new Error(`key_not_found: No key entry found for kid=${keyRef.kid}`)
}
if (
managedKey.type === 'Ed25519' &&
(typeof algorithm === 'undefined' || ['Ed25519', 'EdDSA'].includes(algorithm))
) {
return await this.signEdDSA(managedKey.privateKeyHex, data)
} else if (managedKey.type === 'Secp256k1') {
if (typeof algorithm === 'undefined' || ['ES256K', 'ES256K-R'].includes(algorithm)) {
return await this.signES256K(managedKey.privateKeyHex, algorithm, data)
} else if (['eth_signTransaction', 'signTransaction', 'signTx'].includes(algorithm)) {
return await this.eth_signTransaction(managedKey.privateKeyHex, data)
} else if (algorithm === 'eth_signMessage') {
return await this.eth_signMessage(managedKey.privateKeyHex, data)
} else if (['eth_signTypedData', 'EthereumEip712Signature2021'].includes(algorithm)) {
return await this.eth_signTypedData(managedKey.privateKeyHex, data)
}
}
throw Error(`not_supported: Cannot sign ${algorithm} using key of type ${managedKey.type}`)
}
async sharedSecret(args: {
myKeyRef: Pick<IKey, 'kid'>
theirKey: Pick<IKey, 'type' | 'publicKeyHex'>
}): Promise<string> {
let myKey: ManagedPrivateKey
try {
myKey = await this.keyStore.get({ alias: args.myKeyRef.kid })
} catch (e) {
throw new Error(`key_not_found: No key entry found for kid=${args.myKeyRef.kid}`)
}
if (!myKey.privateKeyHex) {
throw Error('key_not_managed: No private key is available for kid: ' + myKey.alias)
}
let theirKey: Pick<IKey, 'type' | 'publicKeyHex'> = args.theirKey
if (
!theirKey.type ||
typeof theirKey.type !== 'string' ||
!theirKey.publicKeyHex ||
typeof theirKey.publicKeyHex !== 'string'
) {
throw new Error(`invalid_argument: args.theirKey must contain 'type' and 'publicKeyHex'`)
}
let myKeyBytes = arrayify('0x' + myKey.privateKeyHex)
if (myKey.type === 'Ed25519') {
myKeyBytes = convertSecretKeyToX25519(myKeyBytes)
} else if (myKey.type !== 'X25519') {
throw new Error(`not_supported: can't compute shared secret for type=${myKey.type}`)
}
let theirKeyBytes = arrayify('0x' + theirKey.publicKeyHex)
if (theirKey.type === 'Ed25519') {
theirKeyBytes = convertPublicKeyToX25519(theirKeyBytes)
} else if (theirKey.type !== 'X25519') {
throw new Error(`not_supported: can't compute shared secret for type=${theirKey.type}`)
}
const shared = sharedKey(myKeyBytes, theirKeyBytes)
return hexlify(shared).substring(2)
}
/**
* @returns a `0x` prefixed hex string representing the signed EIP712 data
*/
private async eth_signTypedData(privateKeyHex: string, data: Uint8Array) {
let msg, msgDomain, msgTypes
const serializedData = toUtf8String(data)
try {
let jsonData = <Eip712Payload>JSON.parse(serializedData)
if (typeof jsonData.domain === 'object' && typeof jsonData.types === 'object') {
const { domain, types, message } = jsonData
msg = message
msgDomain = domain
msgTypes = types
} else {
// next check will throw since the data couldn't be parsed
}
} catch (e) {
// next check will throw since the data couldn't be parsed
}
if (typeof msgDomain !== 'object' || typeof msgTypes !== 'object' || typeof msg !== 'object') {
throw Error(
`invalid_arguments: Cannot sign typed data. 'domain', 'types', and 'message' must be provided`,
)
}
const wallet = new Wallet(privateKeyHex)
const signature = await wallet._signTypedData(msgDomain, msgTypes, msg)
// HEX encoded string
return signature
}
/**
* @returns a `0x` prefixed hex string representing the signed message
*/
private async eth_signMessage(privateKeyHex: string, rawMessageBytes: Uint8Array) {
const wallet = new Wallet(privateKeyHex)
const signature = await wallet.signMessage(rawMessageBytes)
// HEX encoded string, 0x prefixed
return signature
}
/**
* @returns a `0x` prefixed hex string representing the signed raw transaction
*/
private async eth_signTransaction(privateKeyHex: string, rlpTransaction: Uint8Array) {
const { v, r, s, from, ...tx } = parse(rlpTransaction)
const wallet = new Wallet(privateKeyHex)
if (from) {
debug('WARNING: executing a transaction signing request with a `from` field.')
if (wallet.address.toLowerCase() !== from.toLowerCase()) {
const msg = "invalid_arguments: eth_signTransaction `from` field does not match the chosen key. `from` field should be omitted."
debug(msg)
throw new Error(msg)
}
}
const signedRawTransaction = await wallet.signTransaction(<TransactionRequest>tx)
// HEX encoded string, 0x prefixed
return signedRawTransaction
}
/**
* @returns a base64url encoded signature for the `EdDSA` alg
*/
private async signEdDSA(key: string, data: Uint8Array): Promise<string> {
const signer = EdDSASigner(key)
const signature = await signer(data)
// base64url encoded string
return signature as string
}
/**
* @returns a base64url encoded signature for the `ES256K` or `ES256K-R` alg
*/
private async signES256K(
privateKeyHex: string,
alg: string | undefined,
data: Uint8Array,
): Promise<string> {
const signer = ES256KSigner(privateKeyHex, alg === 'ES256K-R')
const signature = await signer(data)
// base64url encoded string
return signature as string
}
/**
* Converts a {@link ManagedPrivateKey} to {@link ManagedKeyInfo}
*/
private asManagedKeyInfo(args: RequireOnly<ManagedPrivateKey, 'privateKeyHex' | 'type'>): ManagedKeyInfo {
let key: Partial<ManagedKeyInfo>
switch (args.type) {
case 'Ed25519': {
const secretKey = u8a.fromString(args.privateKeyHex.toLowerCase(), 'base16')
const publicKeyHex = u8a.toString(extractPublicKeyFromSecretKey(secretKey), 'base16')
key = {
type: args.type,
kid: args.alias || publicKeyHex,
publicKeyHex,
meta: {
algorithms: ['Ed25519', 'EdDSA'],
},
}
break
}
case 'Secp256k1': {
const privateBytes = u8a.fromString(args.privateKeyHex.toLowerCase(), 'base16')
const keyPair = new SigningKey(privateBytes)
const publicKeyHex = keyPair.publicKey.substring(2)
key = {
type: args.type,
kid: args.alias || publicKeyHex,
publicKeyHex,
meta: {
algorithms: ['ES256K', 'ES256K-R', 'eth_signTransaction', 'eth_signTypedData', 'eth_signMessage'],
},
}
break
}
case 'X25519': {
const secretKeyBytes = u8a.fromString(args.privateKeyHex.toLowerCase(), 'base16')
const keyPairX25519 = generateEncryptionKeyPairFromSeed(secretKeyBytes)
const publicKeyHex = u8a.toString(keyPairX25519.publicKey, 'base16')
key = {
type: args.type,
kid: args.alias || publicKeyHex,
publicKeyHex: publicKeyHex,
meta: {
algorithms: ['ECDH', 'ECDH-ES', 'ECDH-1PU'],
},
}
break
}
default:
throw Error('not_supported: Key type not supported: ' + args.type)
}
return key as ManagedKeyInfo
}
}
type Eip712Payload = {
domain: TypedDataDomain
types: Record<string, TypedDataField[]>
primaryType: string
message: Record<string, any>
} | the_stack |
import { isDeno } from '../util'
import { CANCEL_BUBBLE_IMMEDIATELY } from './Event'
// note that we are using provided EventTarget if possible (deno)
class EventTarget implements globalThis.EventTarget {
// beware collisions, preact is using node._listeners
#listeners = {}
addEventListener(type: string, listener) {
this.#listeners[type] = [...this.#listeners[type] ?? [], listener]
}
removeEventListener(type: string, listener) {
this.#listeners[type] = (this.#listeners[type] ?? []).filter(l => l !== listener)
}
dispatchEvent(event: Event) {
;(event as any).target = this
this._dispatch(event)
return !event.defaultPrevented
}
// TODO: inline in dispatchEvent but it MUST NOT set event.target during bubbling
_dispatch(event: Event) {
;(event as any).currentTarget = this
for (const l of this.#listeners[event.type] ?? []) {
if ('handleEvent' in l) {
l.handleEvent(event)
} else {
l.call(this, event)
}
if (event[CANCEL_BUBBLE_IMMEDIATELY]) {
break
}
}
if (!event.cancelBubble) {
// bubble
this['parentNode']?._dispatch(event)
}
}
}
// prefer deno EventTarget
const BaseEventTarget: typeof EventTarget = isDeno ? (globalThis.EventTarget as any) : EventTarget
const INLINE_HANDLERS = Symbol()
// define new class for our purposes
class EventTargetWithHandlerProps extends BaseEventTarget {
[INLINE_HANDLERS] = {}
// on* event handler props
// - makes TS happy
// - everything is here so we don't need to repeat it again in all possible ev targets
// - preact needs this for some golfing: name = (nameLower in dom ? nameLower : name).slice(2);
// https://github.com/preactjs/preact/blob/013dc382cf7239422e834e74a6ab0b592c5a9c43/src/diff/props.js#L80
get onabort() {
return getHandler(this, 'abort')
}
set onabort(listener) {
setHandler(this, 'abort', listener)
}
get onafterprint() {
return getHandler(this, 'afterprint')
}
set onafterprint(listener) {
setHandler(this, 'afterprint', listener)
}
get onanimationcancel() {
return getHandler(this, 'animationcancel')
}
set onanimationcancel(listener) {
setHandler(this, 'animationcancel', listener)
}
get onanimationend() {
return getHandler(this, 'animationend')
}
set onanimationend(listener) {
setHandler(this, 'animationend', listener)
}
get onanimationiteration() {
return getHandler(this, 'animationiteration')
}
set onanimationiteration(listener) {
setHandler(this, 'animationiteration', listener)
}
get onanimationstart() {
return getHandler(this, 'animationstart')
}
set onanimationstart(listener) {
setHandler(this, 'animationstart', listener)
}
get onauxclick() {
return getHandler(this, 'auxclick')
}
set onauxclick(listener) {
setHandler(this, 'auxclick', listener)
}
get onbeforeprint() {
return getHandler(this, 'beforeprint')
}
set onbeforeprint(listener) {
setHandler(this, 'beforeprint', listener)
}
get onbeforeunload() {
return getHandler(this, 'beforeunload')
}
set onbeforeunload(listener) {
setHandler(this, 'beforeunload', listener)
}
get onblur() {
return getHandler(this, 'blur')
}
set onblur(listener) {
setHandler(this, 'blur', listener)
}
get oncancel() {
return getHandler(this, 'cancel')
}
set oncancel(listener) {
setHandler(this, 'cancel', listener)
}
get oncanplay() {
return getHandler(this, 'canplay')
}
set oncanplay(listener) {
setHandler(this, 'canplay', listener)
}
get oncanplaythrough() {
return getHandler(this, 'canplaythrough')
}
set oncanplaythrough(listener) {
setHandler(this, 'canplaythrough', listener)
}
get onchange() {
return getHandler(this, 'change')
}
set onchange(listener) {
setHandler(this, 'change', listener)
}
get onclick() {
return getHandler(this, 'click')
}
set onclick(listener) {
setHandler(this, 'click', listener)
}
get onclose() {
return getHandler(this, 'close')
}
set onclose(listener) {
setHandler(this, 'close', listener)
}
get oncompassneedscalibration() {
return getHandler(this, 'compassneedscalibration')
}
set oncompassneedscalibration(listener) {
setHandler(this, 'compassneedscalibration', listener)
}
get oncontextmenu() {
return getHandler(this, 'contextmenu')
}
set oncontextmenu(listener) {
setHandler(this, 'contextmenu', listener)
}
get oncopy() {
return getHandler(this, 'copy')
}
set oncopy(listener) {
setHandler(this, 'copy', listener)
}
get oncuechange() {
return getHandler(this, 'cuechange')
}
set oncuechange(listener) {
setHandler(this, 'cuechange', listener)
}
get oncut() {
return getHandler(this, 'cut')
}
set oncut(listener) {
setHandler(this, 'cut', listener)
}
get ondblclick() {
return getHandler(this, 'dblclick')
}
set ondblclick(listener) {
setHandler(this, 'dblclick', listener)
}
get ondevicelight() {
return getHandler(this, 'devicelight')
}
set ondevicelight(listener) {
setHandler(this, 'devicelight', listener)
}
get ondevicemotion() {
return getHandler(this, 'devicemotion')
}
set ondevicemotion(listener) {
setHandler(this, 'devicemotion', listener)
}
get ondeviceorientation() {
return getHandler(this, 'deviceorientation')
}
set ondeviceorientation(listener) {
setHandler(this, 'deviceorientation', listener)
}
get ondeviceorientationabsolute() {
return getHandler(this, 'deviceorientationabsolute')
}
set ondeviceorientationabsolute(listener) {
setHandler(this, 'deviceorientationabsolute', listener)
}
get ondrag() {
return getHandler(this, 'drag')
}
set ondrag(listener) {
setHandler(this, 'drag', listener)
}
get ondragend() {
return getHandler(this, 'dragend')
}
set ondragend(listener) {
setHandler(this, 'dragend', listener)
}
get ondragenter() {
return getHandler(this, 'dragenter')
}
set ondragenter(listener) {
setHandler(this, 'dragenter', listener)
}
get ondragexit() {
return getHandler(this, 'dragexit')
}
set ondragexit(listener) {
setHandler(this, 'dragexit', listener)
}
get ondragleave() {
return getHandler(this, 'dragleave')
}
set ondragleave(listener) {
setHandler(this, 'dragleave', listener)
}
get ondragover() {
return getHandler(this, 'dragover')
}
set ondragover(listener) {
setHandler(this, 'dragover', listener)
}
get ondragstart() {
return getHandler(this, 'dragstart')
}
set ondragstart(listener) {
setHandler(this, 'dragstart', listener)
}
get ondrop() {
return getHandler(this, 'drop')
}
set ondrop(listener) {
setHandler(this, 'drop', listener)
}
get ondurationchange() {
return getHandler(this, 'durationchange')
}
set ondurationchange(listener) {
setHandler(this, 'durationchange', listener)
}
get onemptied() {
return getHandler(this, 'emptied')
}
set onemptied(listener) {
setHandler(this, 'emptied', listener)
}
get onended() {
return getHandler(this, 'ended')
}
set onended(listener) {
setHandler(this, 'ended', listener)
}
get onerror() {
return getHandler(this, 'error')
}
set onerror(listener) {
setHandler(this, 'error', listener)
}
get onfocus() {
return getHandler(this, 'focus')
}
set onfocus(listener) {
setHandler(this, 'focus', listener)
}
get onformdata() {
return getHandler(this, 'formdata')
}
set onformdata(listener) {
setHandler(this, 'formdata', listener)
}
get onfullscreenchange() {
return getHandler(this, 'fullscreenchange')
}
set onfullscreenchange(listener) {
setHandler(this, 'fullscreenchange', listener)
}
get onfullscreenerror() {
return getHandler(this, 'fullscreenerror')
}
set onfullscreenerror(listener) {
setHandler(this, 'fullscreenerror', listener)
}
get ongamepadconnected() {
return getHandler(this, 'gamepadconnected')
}
set ongamepadconnected(listener) {
setHandler(this, 'gamepadconnected', listener)
}
get ongamepaddisconnected() {
return getHandler(this, 'gamepaddisconnected')
}
set ongamepaddisconnected(listener) {
setHandler(this, 'gamepaddisconnected', listener)
}
get ongotpointercapture() {
return getHandler(this, 'gotpointercapture')
}
set ongotpointercapture(listener) {
setHandler(this, 'gotpointercapture', listener)
}
get onhashchange() {
return getHandler(this, 'hashchange')
}
set onhashchange(listener) {
setHandler(this, 'hashchange', listener)
}
get oninput() {
return getHandler(this, 'input')
}
set oninput(listener) {
setHandler(this, 'input', listener)
}
get oninvalid() {
return getHandler(this, 'invalid')
}
set oninvalid(listener) {
setHandler(this, 'invalid', listener)
}
get onkeydown() {
return getHandler(this, 'keydown')
}
set onkeydown(listener) {
setHandler(this, 'keydown', listener)
}
get onkeypress() {
return getHandler(this, 'keypress')
}
set onkeypress(listener) {
setHandler(this, 'keypress', listener)
}
get onkeyup() {
return getHandler(this, 'keyup')
}
set onkeyup(listener) {
setHandler(this, 'keyup', listener)
}
get onlanguagechange() {
return getHandler(this, 'languagechange')
}
set onlanguagechange(listener) {
setHandler(this, 'languagechange', listener)
}
get onload() {
return getHandler(this, 'load')
}
set onload(listener) {
setHandler(this, 'load', listener)
}
get onloadeddata() {
return getHandler(this, 'loadeddata')
}
set onloadeddata(listener) {
setHandler(this, 'loadeddata', listener)
}
get onloadedmetadata() {
return getHandler(this, 'loadedmetadata')
}
set onloadedmetadata(listener) {
setHandler(this, 'loadedmetadata', listener)
}
get onloadstart() {
return getHandler(this, 'loadstart')
}
set onloadstart(listener) {
setHandler(this, 'loadstart', listener)
}
get onlostpointercapture() {
return getHandler(this, 'lostpointercapture')
}
set onlostpointercapture(listener) {
setHandler(this, 'lostpointercapture', listener)
}
get onmessage() {
return getHandler(this, 'message')
}
set onmessage(listener) {
setHandler(this, 'message', listener)
}
get onmessageerror() {
return getHandler(this, 'messageerror')
}
set onmessageerror(listener) {
setHandler(this, 'messageerror', listener)
}
get onmousedown() {
return getHandler(this, 'mousedown')
}
set onmousedown(listener) {
setHandler(this, 'mousedown', listener)
}
get onmouseenter() {
return getHandler(this, 'mouseenter')
}
set onmouseenter(listener) {
setHandler(this, 'mouseenter', listener)
}
get onmouseleave() {
return getHandler(this, 'mouseleave')
}
set onmouseleave(listener) {
setHandler(this, 'mouseleave', listener)
}
get onmousemove() {
return getHandler(this, 'mousemove')
}
set onmousemove(listener) {
setHandler(this, 'mousemove', listener)
}
get onmouseout() {
return getHandler(this, 'mouseout')
}
set onmouseout(listener) {
setHandler(this, 'mouseout', listener)
}
get onmouseover() {
return getHandler(this, 'mouseover')
}
set onmouseover(listener) {
setHandler(this, 'mouseover', listener)
}
get onmouseup() {
return getHandler(this, 'mouseup')
}
set onmouseup(listener) {
setHandler(this, 'mouseup', listener)
}
get onmousewheel() {
return getHandler(this, 'mousewheel')
}
set onmousewheel(listener) {
setHandler(this, 'mousewheel', listener)
}
get onoffline() {
return getHandler(this, 'offline')
}
set onoffline(listener) {
setHandler(this, 'offline', listener)
}
get ononline() {
return getHandler(this, 'online')
}
set ononline(listener) {
setHandler(this, 'online', listener)
}
get onorientationchange() {
return getHandler(this, 'orientationchange')
}
set onorientationchange(listener) {
setHandler(this, 'orientationchange', listener)
}
get onpagehide() {
return getHandler(this, 'pagehide')
}
set onpagehide(listener) {
setHandler(this, 'pagehide', listener)
}
get onpageshow() {
return getHandler(this, 'pageshow')
}
set onpageshow(listener) {
setHandler(this, 'pageshow', listener)
}
get onpaste() {
return getHandler(this, 'paste')
}
set onpaste(listener) {
setHandler(this, 'paste', listener)
}
get onpause() {
return getHandler(this, 'pause')
}
set onpause(listener) {
setHandler(this, 'pause', listener)
}
get onplay() {
return getHandler(this, 'play')
}
set onplay(listener) {
setHandler(this, 'play', listener)
}
get onplaying() {
return getHandler(this, 'playing')
}
set onplaying(listener) {
setHandler(this, 'playing', listener)
}
get onpointercancel() {
return getHandler(this, 'pointercancel')
}
set onpointercancel(listener) {
setHandler(this, 'pointercancel', listener)
}
get onpointerdown() {
return getHandler(this, 'pointerdown')
}
set onpointerdown(listener) {
setHandler(this, 'pointerdown', listener)
}
get onpointerenter() {
return getHandler(this, 'pointerenter')
}
set onpointerenter(listener) {
setHandler(this, 'pointerenter', listener)
}
get onpointerleave() {
return getHandler(this, 'pointerleave')
}
set onpointerleave(listener) {
setHandler(this, 'pointerleave', listener)
}
get onpointerlockchange() {
return getHandler(this, 'pointerlockchange')
}
set onpointerlockchange(listener) {
setHandler(this, 'pointerlockchange', listener)
}
get onpointerlockerror() {
return getHandler(this, 'pointerlockerror')
}
set onpointerlockerror(listener) {
setHandler(this, 'pointerlockerror', listener)
}
get onpointermove() {
return getHandler(this, 'pointermove')
}
set onpointermove(listener) {
setHandler(this, 'pointermove', listener)
}
get onpointerout() {
return getHandler(this, 'pointerout')
}
set onpointerout(listener) {
setHandler(this, 'pointerout', listener)
}
get onpointerover() {
return getHandler(this, 'pointerover')
}
set onpointerover(listener) {
setHandler(this, 'pointerover', listener)
}
get onpointerup() {
return getHandler(this, 'pointerup')
}
set onpointerup(listener) {
setHandler(this, 'pointerup', listener)
}
get onpopstate() {
return getHandler(this, 'popstate')
}
set onpopstate(listener) {
setHandler(this, 'popstate', listener)
}
get onprogress() {
return getHandler(this, 'progress')
}
set onprogress(listener) {
setHandler(this, 'progress', listener)
}
get onratechange() {
return getHandler(this, 'ratechange')
}
set onratechange(listener) {
setHandler(this, 'ratechange', listener)
}
get onreadystatechange() {
return getHandler(this, 'readystatechange')
}
set onreadystatechange(listener) {
setHandler(this, 'readystatechange', listener)
}
get onrejectionhandled() {
return getHandler(this, 'rejectionhandled')
}
set onrejectionhandled(listener) {
setHandler(this, 'rejectionhandled', listener)
}
get onreset() {
return getHandler(this, 'reset')
}
set onreset(listener) {
setHandler(this, 'reset', listener)
}
get onresize() {
return getHandler(this, 'resize')
}
set onresize(listener) {
setHandler(this, 'resize', listener)
}
get onscroll() {
return getHandler(this, 'scroll')
}
set onscroll(listener) {
setHandler(this, 'scroll', listener)
}
get onsecuritypolicyviolation() {
return getHandler(this, 'securitypolicyviolation')
}
set onsecuritypolicyviolation(listener) {
setHandler(this, 'securitypolicyviolation', listener)
}
get onseeked() {
return getHandler(this, 'seeked')
}
set onseeked(listener) {
setHandler(this, 'seeked', listener)
}
get onseeking() {
return getHandler(this, 'seeking')
}
set onseeking(listener) {
setHandler(this, 'seeking', listener)
}
get onselect() {
return getHandler(this, 'select')
}
set onselect(listener) {
setHandler(this, 'select', listener)
}
get onselectionchange() {
return getHandler(this, 'selectionchange')
}
set onselectionchange(listener) {
setHandler(this, 'selectionchange', listener)
}
get onselectstart() {
return getHandler(this, 'selectstart')
}
set onselectstart(listener) {
setHandler(this, 'selectstart', listener)
}
get onstalled() {
return getHandler(this, 'stalled')
}
set onstalled(listener) {
setHandler(this, 'stalled', listener)
}
get onstorage() {
return getHandler(this, 'storage')
}
set onstorage(listener) {
setHandler(this, 'storage', listener)
}
get onsubmit() {
return getHandler(this, 'submit')
}
set onsubmit(listener) {
setHandler(this, 'submit', listener)
}
get onsuspend() {
return getHandler(this, 'suspend')
}
set onsuspend(listener) {
setHandler(this, 'suspend', listener)
}
get ontimeupdate() {
return getHandler(this, 'timeupdate')
}
set ontimeupdate(listener) {
setHandler(this, 'timeupdate', listener)
}
get ontoggle() {
return getHandler(this, 'toggle')
}
set ontoggle(listener) {
setHandler(this, 'toggle', listener)
}
get ontouchcancel() {
return getHandler(this, 'touchcancel')
}
set ontouchcancel(listener) {
setHandler(this, 'touchcancel', listener)
}
get ontouchend() {
return getHandler(this, 'touchend')
}
set ontouchend(listener) {
setHandler(this, 'touchend', listener)
}
get ontouchmove() {
return getHandler(this, 'touchmove')
}
set ontouchmove(listener) {
setHandler(this, 'touchmove', listener)
}
get ontouchstart() {
return getHandler(this, 'touchstart')
}
set ontouchstart(listener) {
setHandler(this, 'touchstart', listener)
}
get ontransitioncancel() {
return getHandler(this, 'transitioncancel')
}
set ontransitioncancel(listener) {
setHandler(this, 'transitioncancel', listener)
}
get ontransitionend() {
return getHandler(this, 'transitionend')
}
set ontransitionend(listener) {
setHandler(this, 'transitionend', listener)
}
get ontransitionrun() {
return getHandler(this, 'transitionrun')
}
set ontransitionrun(listener) {
setHandler(this, 'transitionrun', listener)
}
get ontransitionstart() {
return getHandler(this, 'transitionstart')
}
set ontransitionstart(listener) {
setHandler(this, 'transitionstart', listener)
}
get onunhandledrejection() {
return getHandler(this, 'unhandledrejection')
}
set onunhandledrejection(listener) {
setHandler(this, 'unhandledrejection', listener)
}
get onunload() {
return getHandler(this, 'unload')
}
set onunload(listener) {
setHandler(this, 'unload', listener)
}
get onvisibilitychange() {
return getHandler(this, 'visibilitychange')
}
set onvisibilitychange(listener) {
setHandler(this, 'visibilitychange', listener)
}
get onvolumechange() {
return getHandler(this, 'volumechange')
}
set onvolumechange(listener) {
setHandler(this, 'volumechange', listener)
}
get onvrdisplayactivate() {
return getHandler(this, 'vrdisplayactivate')
}
set onvrdisplayactivate(listener) {
setHandler(this, 'vrdisplayactivate', listener)
}
get onvrdisplayblur() {
return getHandler(this, 'vrdisplayblur')
}
set onvrdisplayblur(listener) {
setHandler(this, 'vrdisplayblur', listener)
}
get onvrdisplayconnect() {
return getHandler(this, 'vrdisplayconnect')
}
set onvrdisplayconnect(listener) {
setHandler(this, 'vrdisplayconnect', listener)
}
get onvrdisplaydeactivate() {
return getHandler(this, 'vrdisplaydeactivate')
}
set onvrdisplaydeactivate(listener) {
setHandler(this, 'vrdisplaydeactivate', listener)
}
get onvrdisplaydisconnect() {
return getHandler(this, 'vrdisplaydisconnect')
}
set onvrdisplaydisconnect(listener) {
setHandler(this, 'vrdisplaydisconnect', listener)
}
get onvrdisplayfocus() {
return getHandler(this, 'vrdisplayfocus')
}
set onvrdisplayfocus(listener) {
setHandler(this, 'vrdisplayfocus', listener)
}
get onvrdisplaypointerrestricted() {
return getHandler(this, 'vrdisplaypointerrestricted')
}
set onvrdisplaypointerrestricted(listener) {
setHandler(this, 'vrdisplaypointerrestricted', listener)
}
get onvrdisplaypointerunrestricted() {
return getHandler(this, 'vrdisplaypointerunrestricted')
}
set onvrdisplaypointerunrestricted(listener) {
setHandler(this, 'vrdisplaypointerunrestricted', listener)
}
get onvrdisplaypresentchange() {
return getHandler(this, 'vrdisplaypresentchange')
}
set onvrdisplaypresentchange(listener) {
setHandler(this, 'vrdisplaypresentchange', listener)
}
get onwaiting() {
return getHandler(this, 'waiting')
}
set onwaiting(listener) {
setHandler(this, 'waiting', listener)
}
get onwheel() {
return getHandler(this, 'wheel')
}
set onwheel(listener) {
setHandler(this, 'wheel', listener)
}
get onzoom() {
return getHandler(this, 'zoom')
}
set onzoom(listener) {
setHandler(this, 'zoom', listener)
}
// ignore vendor
onmsgesturechange
onmsgesturedoubletap
onmsgestureend
onmsgesturehold
onmsgesturestart
onmsgesturetap
onmsinertiastart
onmspointercancel
onmspointerdown
onmspointerenter
onmspointerleave
onmspointermove
onmspointerout
onmspointerover
onmspointerup
onwebkitanimationend
onwebkitanimationiteration
onwebkitanimationstart
onwebkittransitionend
}
const getHandler = (et, kind) => et[INLINE_HANDLERS][kind] ?? null
const setHandler = (et, kind, handler) => {
if (!handler) {
return et.removeEventListener(kind, handlerProxy)
}
if (!et[INLINE_HANDLERS][kind]) {
et.addEventListener(kind, handlerProxy)
}
et[INLINE_HANDLERS][kind] = handler
}
function handlerProxy(e) {
// @ts-expect-error
(this[INLINE_HANDLERS] ?? {})[e.type].call(this, e)
}
export { EventTargetWithHandlerProps as EventTarget } | the_stack |
import * as _ from 'lodash';
import { Component, ElementRef, EventEmitter, Injector, Input, OnDestroy, OnInit, Output } from '@angular/core';
import { PopupService } from '@common/service/popup.service';
import { AbstractPopupComponent } from '@common/component/abstract-popup.component';
import { PrDataset } from '@domain/data-preparation/pr-dataset';
import { DataflowService } from '../../../../../service/dataflow.service';
import { PreparationAlert } from '../../../../../../util/preparation-alert.util';
@Component({
selector: 'app-union-add-datasets',
templateUrl: './union-add-datasets.component.html',
})
export class UnionAddDatasetsComponent extends AbstractPopupComponent implements OnInit, OnDestroy {
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
private readonly DS_TYPE: string = 'WRANGLED';
private readonly IMPORT_TYPE: string = '';
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public - Input Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
@Input()
public masterDsId: string;
@Input()
public dfId: string;
@Input()
public existingDatasets: PrDataset[];
@Input()
public editInfo: PrDataset[];
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public - Output Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
@Output()
public complete = new EventEmitter();
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
public searchText: string = '';
public selectedContentSort: Order = new Order();
public datasets: PrDataset[] = []; // 화면에 보여지는 데이터셋 리스트
public selectedItems: PrDataset[] = [];
public isUpdate: boolean = false; // 수정 모드 여부
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
constructor(protected popupService: PopupService,
protected dataflowService: DataflowService,
protected elementRef: ElementRef,
protected injector: Injector) {
super(elementRef, injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
public ngOnInit() {
super.ngOnInit();
this.initialisePaging();
// Update if editInfo has value
this.isUpdate = this.editInfo.length > 0;
this._getDatasets(true);
}
public ngOnDestroy() {
super.ngOnDestroy();
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* Initialise paging information
*/
public initialisePaging() {
// TODO: no paging ?
this.page.size = 10000;
this.page.sort = 'modifiedTime,desc';
}
/**
* 수정 정보 세팅
*/
public checkEditInfo(list) {
list.forEach((item) => {
if (item.dsId !== this.masterDsId) {
const idx = _.findIndex(this.datasets, {dsId: item.dsId});
if (-1 !== idx) {
this.datasets[idx].selected= true;
this.datasets[idx].origin = false;
this.selectedItems.push(this.datasets[idx]);
}
}
})
}
/**
* Close popup
*/
public close() {
this.complete.emit(null);
}
/**
* When add button is pressed
*/
public addDatasets() {
if (this.selectedItems.length === 0) {
return;
}
this.complete.emit(this.selectedItems);
}
/**
* Add selected item
* @param ds
* @private
*/
private _addSelectedItem(ds: PrDataset) {
this.selectedItems.push(ds);
}
/**
* Delete selected item
* @param ds
* @private
*/
private _deleteSelectedItem(ds: PrDataset) {
const index = _.findIndex(this.selectedItems, {dsId: ds.dsId});
if (-1 !== index) {
this.selectedItems.splice(index,1);
}
}
/**
* 모든 아이템 선택 해제
* @private
*/
private _deleteAllItems(){
this.datasets.forEach((item) => {
if (!item.origin && item.selected) {
item.selected = false;
this._deleteSelectedItem(item);
}
})
}
/**
* 모든 아이템 선택
* @private
*/
private _addAllItems() {
this.datasets.forEach((item) => {
if (!item.origin) {
item.selected = true;
if (-1 === _.findIndex(this.selectedItems, {dsId: item.dsId})) {
this._addSelectedItem(item);
}
}
})
}
/**
* 체크박스 전체 선택
*/
public checkAll() {
this.isAllChecked() ? this._deleteAllItems() : this._addAllItems();
}
/**
* 체크박스 선택
*/
public check(ds: PrDataset) {
// 중복 체크 방지
event.stopImmediatePropagation();
// Original dataset cannot be checked
if (ds.origin) {
return;
}
ds.selected = !ds.selected;
-1 === _.findIndex(this.selectedItems, {dsId: ds.dsId}) ?
this._addSelectedItem(ds) : this._deleteSelectedItem(ds);
} // function - check
/**
* 전체 체크 박스가 비활성화 인지 확인
*/
public isCheckAllDisabled(): boolean {
return this.datasets.filter((item) => {
return !item.origin
}).length === 0;
}
/**
* 전체 체크 인지 확인
*/
public isAllChecked(): boolean {
if (this.isCheckAllDisabled()) {
return;
}
const listWithNoOrigin = this.datasets.filter((item) => {
return !item.origin
});
if (listWithNoOrigin.length !== 0) {
for (let index = 0, nMax = listWithNoOrigin.length; index < nMax; index++) {
if (_.findIndex(this.selectedItems, {dsId: listWithNoOrigin[index].dsId}) === -1) {
return false;
}
}
return true;
} else {
// 조회된 멤버 목록이 없다면 false
return false;
}
}
/**
* Check if add selections btn should be disabled or not
* @returns {boolean}
*/
public isAddEnabled() {
return ( 0 === this.datasets.filter(item => item.origin === false && item.selected).length );
}
/**
* Sort list
*/
public sortList(column: string) {
this.page.page = 0;
// 초기화
this.selectedContentSort.sort = this.selectedContentSort.key !== column ? 'default' : this.selectedContentSort.sort;
// asc, desc, default
switch (this.selectedContentSort.sort) {
case 'asc':
this.selectedContentSort.sort = 'desc';
break;
case 'desc':
this.selectedContentSort.sort = 'asc';
break;
case 'default':
this.selectedContentSort.sort = 'desc';
break;
}
this.page.sort = column + ',' + this.selectedContentSort.sort;
// 데이터소스 리스트 조회
this._getDatasets();
}
/**
* On key press event
* @param event
*/
public onKeyPress(event: any) {
// Enter key
if (13 === event.keyCode) {
this._getDatasets();
// ESC
} else if (27 === event.keyCode) {
// Refresh search text
this.searchText = '';
}
}
/**
* Refresh search text
*/
public refreshSearch() {
this.searchText = '';
this._getDatasets();
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* Fetch dataset list
*/
private _getDatasets(isInitial: boolean = false) {
this.datasets = [];
this.loadingShow();
// Fetch dataset list
this.dataflowService.getDatasets(this.searchText, this.page, 'listing', this.DS_TYPE, this.IMPORT_TYPE).then((data) => {
// sorting
const sorting = this.page.sort.split(',');
this.selectedContentSort.key = sorting[0];
this.selectedContentSort.sort = sorting[1];
// if result exists
if (data['_embedded'] && data['_embedded'].preparationdatasets) {
// Show only datasets from same dataflow as master dataset
this.datasets = data['_embedded'].preparationdatasets.filter((item) => {
return item.creatorDfId === this.dfId;
});
// get upstreams
this._getUpstreams(isInitial);
} else {
this.loadingHide();
}
}).catch((error) => {
this.loadingHide();
const prepError = this.dataprepExceptionHandler(error);
PreparationAlert.output(prepError, this.translateService.instant(prepError.message));
});
}
/**
* Fetch upstreams
* @param isInitial 처음 실행인지 ?
* @private
*/
private _getUpstreams(isInitial?: boolean) {
// Fetch upstreams
this.dataflowService.getUpstreams(this.dfId, this.isUpdate).then((upstreams) => {
this.loadingHide();
const upstreamIds = [];
// it upstream exists
if (upstreams.length > 0) {
// returns upstreamDsIds that has same dsId as masterDsId
upstreams.forEach((item) => {
if (item.dsId === this.masterDsId) {
upstreamIds.push(item.upstreamDsId);
}
});
}
/*
How upstream works ?
masterDsId : 444
list = [
{dsId: 111, upstreamDsId: aaa},
{dsId: 222, upstreamDsId: bbb},
{dsId: 333, upstreamDsId: ccc},
{dsId: 444, upstreamDsId: ddd},
{dsId: ddd, upstreamDsId: fff}
]
list[3]is origin = true (dsId is same as masterDsId)
list[4]os origin = true (dsId is same as ↑ upstreamDsId)
*/
this.datasets.forEach((item) => {
item.origin = (-1 < upstreamIds.indexOf(item.dsId)) || item.dsId === this.masterDsId;
// set already selected items
const idx = _.findIndex(this.selectedItems, {dsId: item.dsId});
item.selected = (-1 < upstreamIds.indexOf(item.dsId)) || item.dsId === this.masterDsId || idx > -1;
});
// if initial loading, set existingDatasets
if (isInitial && this.existingDatasets.length > 0) {
this.checkEditInfo(this.existingDatasets);
}
// If editInfo exists, it's update
if (isInitial && this.editInfo.length > 0) {
// 편집일떄 해야하는일
this.checkEditInfo(this.editInfo);
}
}).catch((error) => {
this.loadingHide();
const prepError = this.dataprepExceptionHandler(error);
PreparationAlert.output(prepError, this.translateService.instant(prepError.message));
});
}
}
class Order {
key: string = 'createdTime';
sort: string = 'default';
} | the_stack |
import React, { Component } from 'react'
import {
StyleSheet,
Text,
View,
Image,
Dimensions,
TouchableNativeFeedback,
TextInput,
Linking,
Animated,
Platform,
Keyboard
} from 'react-native'
declare var global
import Ionicons from 'react-native-vector-icons/Ionicons'
import { standardColor, accentColor } from '../../constant/colorConfig'
import { registURL } from '../../dao/login'
import { postPass } from '../../dao/post'
class Login extends Component<any, any> {
constructor(props) {
super(props)
this.state = {
oldpass: '',
newpass: '',
newpass2: '',
oldpassMarginTop: new Animated.Value(0),
passwordMarginTop: new Animated.Value(0),
password2MarginTop: new Animated.Value(0),
avoidKeyboardMarginTop: new Animated.Value(0),
addIcon: false
}
}
_pressButton = () => {
this.props.navigation.goBack()
}
regist = () => {
Linking.canOpenURL(registURL).then(supported => {
if (supported)
Linking.openURL(registURL)
else
global.toast && global.toast(`未找到浏览器, 如果您使用了冰箱, 请先解冻浏览器`, 2000)
}).catch(() => {})
}
keyboardDidShowListener: any = false
keyboardDidHideListener: any = false
accountTextInput: any = false
passwordTextInput: any = false
password2TextInput: any = false
async componentWillMount() {
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', () => {
Animated.spring(this.state.avoidKeyboardMarginTop, {
toValue: 1,
friction: 10,
useNativeDriver: true
}).start()
})
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => {
Animated.spring(this.state.avoidKeyboardMarginTop, {
toValue: 0,
friction: 10,
useNativeDriver: true
}).start()
})
const source = await Ionicons.getImageSource('ios-add', 24, '#fff')
this.setState({
addIcon: source
})
}
componentWillUnmount() {
this.keyboardDidHideListener.remove()
this.keyboardDidShowListener.remove()
}
onAccountTextFocus = () => {
let text = this.accountTextInput._lastNativeText
if (typeof text !== 'undefined' && text !== '')
return
Animated.spring(this.state.oldpassMarginTop, {
toValue: 1,
friction: 10
// useNativeDriver: true
}).start()
}
onAccountTextBlur = () => {
let text = this.accountTextInput._lastNativeText
if (typeof text !== 'undefined' && text !== '')
return
Animated.spring(this.state.oldpassMarginTop, {
toValue: 0,
friction: 10
// useNativeDriver: true
}).start()
}
onPasswordTextFocus = () => {
let text = this.passwordTextInput._lastNativeText
if (typeof text !== 'undefined' && text !== '')
return
Animated.spring(this.state.passwordMarginTop, {
toValue: 1,
friction: 10
// useNativeDriver: true
}).start()
}
onPasswordTextBlur = () => {
let text = this.passwordTextInput._lastNativeText
if (typeof text !== 'undefined' && text !== '')
return
Animated.spring(this.state.passwordMarginTop, {
toValue: 0,
friction: 10
// useNativeDriver: true
}).start()
}
onPassword2TextFocus = () => {
let text = this.password2TextInput._lastNativeText
if (typeof text !== 'undefined' && text !== '')
return
Animated.spring(this.state.password2MarginTop, {
toValue: 1,
friction: 10
// useNativeDriver: true
}).start()
}
onPassword2TextBlur = () => {
let text = this.password2TextInput._lastNativeText
if (typeof text !== 'undefined' && text !== '')
return
Animated.spring(this.state.password2MarginTop, {
toValue: 0,
friction: 10
// useNativeDriver: true
}).start()
}
onSubmit = () => {
postPass({
oldpass: this.state.oldpass,
newpass: this.state.newpass,
newpass2: this.state.newpass2,
changepass: ''
}).then(res => res.text()).then((html) => {
// console.log(res.clone().text())
const matched = html.match(/<div class=\"alert-error pd10\"\>(.*?)<\/div>/)
if (matched && matched[1]) {
global.toast(matched[1])
return
}
global.toast('修改密码成功,请重新登录')
}).catch((err) => {
global.toast(err.toString())
})
}
focusNextField = (nextField) => {
this[nextField].focus()
}
render() {
// console.log('Loggin.js rendered');
let marginLeft = 40
const { modeInfo } = this.props.screenProps
const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get('window')
let avoidKeyboardStyle = {
bottom: marginLeft * 1.5,
top: SCREEN_HEIGHT / 10 * 4 - marginLeft * 1.5,
transform: [{
translateY: this.state.avoidKeyboardMarginTop.interpolate({
inputRange: [0, 1],
outputRange: [0, marginLeft - (SCREEN_HEIGHT / 10 * 4 - marginLeft * 1.5)]
})
}]
}
let accountTextStyle = {
transform: [{
translateY: this.state.oldpassMarginTop.interpolate({
inputRange: [0, 1],
outputRange: [40, 10]
})
}],
// top: this.state.accountMarginTop.interpolate({
// inputRange: [0, 1],
// outputRange: [40, 15]
// }),
color: this.state.oldpassMarginTop.interpolate({
inputRange: [0, 1],
outputRange: [modeInfo.standardTextColor, modeInfo.standardColor]
}),
fontSize: this.state.oldpassMarginTop.interpolate({
inputRange: [0, 1],
outputRange: [15, 12]
})
}
let passwordTextStyle = {
transform: [{
translateY: this.state.passwordMarginTop.interpolate({
inputRange: [0, 1],
outputRange: [40, 10]
})
}],
// top: this.state.passwordMarginTop.interpolate({
// inputRange: [0, 1],
// outputRange: [40, 15]
// }),
color: this.state.passwordMarginTop.interpolate({
inputRange: [0, 1],
outputRange: [modeInfo.standardTextColor, modeInfo.standardColor]
}),
fontSize: this.state.passwordMarginTop.interpolate({
inputRange: [0, 1],
outputRange: [15, 12]
})
}
let password2TextStyle = {
transform: [{
translateY: this.state.password2MarginTop.interpolate({
inputRange: [0, 1],
outputRange: [40, 10]
})
}],
// top: this.state.passwordMarginTop.interpolate({
// inputRange: [0, 1],
// outputRange: [40, 15]
// }),
color: this.state.password2MarginTop.interpolate({
inputRange: [0, 1],
outputRange: [modeInfo.standardTextColor, modeInfo.standardColor]
}),
fontSize: this.state.password2MarginTop.interpolate({
inputRange: [0, 1],
outputRange: [15, 12]
})
}
return (
<View style={{ flex: 1, backgroundColor: modeInfo.standardColor }}>
<Animated.View
collapsable={true}
style={{
width: 56,
height: 56,
borderRadius: 30,
backgroundColor: modeInfo.accentColor,
position: 'absolute',
/*top: this.state.avoidKeyboardMarginTop.interpolate({
inputRange: [0, 1],
outputRange: [SCREEN_HEIGHT / 10 * 4 - marginLeft + 28, marginLeft + 28]
}),*/
transform: [{
translateY: this.state.avoidKeyboardMarginTop.interpolate({
inputRange: [0, 1],
outputRange: [(SCREEN_HEIGHT / 10 * 4 - marginLeft + 28), 28 + marginLeft * 1.5]
})
}],
right: 12,
elevation: 6,
zIndex: 1
}}>
<TouchableNativeFeedback
onPress={this.regist}
background={TouchableNativeFeedback.SelectableBackgroundBorderless()}
style={{
width: 56,
height: 56,
borderRadius: 30,
flex: 1,
zIndex: 1,
backgroundColor: modeInfo.accentColor
}}>
<View style={{ borderRadius: 30 }}>
{this.state.addIcon && (<Image source={this.state.addIcon}
style={{
marginLeft: 16,
marginTop: 16,
width: 24,
height: 24
}}
/>)}
</View>
</TouchableNativeFeedback>
</Animated.View>
<Animated.View style={[{
backgroundColor: modeInfo.backgroundColor,
position: 'absolute',
width: SCREEN_WIDTH - marginLeft * 2,
height: 384,
marginLeft: marginLeft,
bottom: marginLeft,
borderRadius: 5,
elevation: 6
}, avoidKeyboardStyle]}>
<View style={[styles.loginTextView, { marginLeft: marginLeft / 2 * 1.5, marginTop: 27 }]}>
<Text style={[styles.mainFont, { fontSize: 30, marginLeft: 0, marginBottom: 0, color: modeInfo.accentColor }]}>修改密码</Text>
</View>
<View style={[styles.KeyboardAvoidingView, {
width: SCREEN_WIDTH - marginLeft * 3
}]} >
<View style={[styles.accountView, { marginTop: 0 }]}>
<Animated.Text
style={[{ color: modeInfo.standardTextColor, marginLeft: 5 },
accountTextStyle
]}>
{'旧密码'}
</Animated.Text>
<TextInput underlineColorAndroid={modeInfo.accentColor}
onChange={({ nativeEvent }) => { this.setState({ oldpass: nativeEvent.text }) }}
ref={ref => this.accountTextInput = ref}
onFocus={this.onAccountTextFocus}
onBlur={this.onAccountTextBlur}
blurOnSubmit={false}
returnKeyType='next'
onSubmitEditing={() => this.focusNextField('passwordTextInput')}
style={[styles.textInput, { color: modeInfo.standardTextColor }]}
placeholderTextColor={modeInfo.standardTextColor}
/>
</View>
<View style={[styles.passwordView, { marginTop: 0, marginBottom: 0 }]}>
<Animated.Text
style={[{ color: modeInfo.standardTextColor, marginLeft: 5 },
passwordTextStyle
]}>
{'新密码'}
</Animated.Text>
<TextInput underlineColorAndroid={modeInfo.accentColor} secureTextEntry={true}
onChange={({ nativeEvent }) => { this.setState({ newpass: nativeEvent.text }) }}
ref={ref => this.passwordTextInput = ref}
onFocus={this.onPasswordTextFocus}
onBlur={this.onPasswordTextBlur}
blurOnSubmit={false}
returnKeyType='next'
onSubmitEditing={() => this.focusNextField('password2TextInput')}
style={[styles.textInput, { color: modeInfo.standardTextColor }]}
placeholderTextColor={modeInfo.standardTextColor}
/>
</View>
<View style={[styles.passwordView, { marginTop: 0 }]}>
<Animated.Text
style={[{ color: modeInfo.standardTextColor, marginLeft: 5 },
password2TextStyle
]}>
{'新密码第二次'}
</Animated.Text>
<TextInput underlineColorAndroid={modeInfo.accentColor} secureTextEntry={true}
onChange={({ nativeEvent }) => { this.setState({ newpass2: nativeEvent.text }) }}
ref={ref => this.password2TextInput = ref}
onFocus={this.onPassword2TextFocus}
onBlur={this.onPassword2TextBlur}
onSubmitEditing={this.onSubmit}
style={[styles.textInput, { color: modeInfo.standardTextColor }]}
placeholderTextColor={modeInfo.standardTextColor}
/>
</View>
</View>
<View style={[styles.customView, {
width: SCREEN_WIDTH - marginLeft * 3
}]}>
<View style={styles.submit}>
<TouchableNativeFeedback
onPress={this.onSubmit}
>
<View style={[styles.submitButton, {backgroundColor: modeInfo.accentColor}]}>
<Text style={[styles.textInput, { color: modeInfo.backgroundColor }]}>提交</Text>
</View>
</TouchableNativeFeedback>
</View>
</View>
</Animated.View>
</View>
)
}
}
const width = Dimensions.get('window').width
const styles = StyleSheet.create({
toolbar: {
backgroundColor: standardColor,
height: 56,
elevation: 4
},
mainFont: {
fontSize: 15,
color: accentColor
},
textInput: {
fontSize: 15,
minHeight: 40,
padding: Platform.OS === 'ios' ? 12 : 0
},
customView: {
flex: -1,
marginTop: -20,
width: width - 40,
alignSelf: 'center',
justifyContent: 'center',
flexDirection: 'column'
},
KeyboardAvoidingView: {
flex: -1,
marginTop: 0,
width: width - 40,
alignSelf: 'center',
justifyContent: 'space-between',
flexDirection: 'column'
},
loginTextView: {
flexDirection: 'column',
justifyContent: 'space-between',
margin: 10,
marginTop: 20,
marginBottom: 0
},
accountView: {
flexDirection: 'column',
justifyContent: 'space-between',
marginLeft: 10,
marginRight: 10,
marginTop: 20
},
passwordView: {
flexDirection: 'column',
marginLeft: 10,
marginRight: 10,
marginTop: 20,
marginBottom: 20
},
submit: {
flex: -1,
height: 30,
margin: 10,
marginTop: 40,
marginBottom: 20
},
submitButton: {
backgroundColor: accentColor,
height: 40,
alignItems: 'center',
justifyContent: 'center'
},
regist: {
flex: 1,
flexDirection: 'row',
marginTop: 20,
margin: 10
},
openURL: {
color: accentColor,
textDecorationLine: 'underline'
}
})
export default Login | the_stack |
import { UxPositioningOptions, UxPlacement, UxMissingSpaceStrategy, UxPositioningConfiguration } from './interfaces';
import { inject, TaskQueue } from 'aurelia-framework';
// import this CSS for the default hidden class `.ux-positioning--hidden`
import './ux-positioning.css';
type MainPlacement = 'left' | 'right' | 'bottom' | 'top';
type SecondaryPlacement = 'vstart' | 'vcenter' | 'vend' | 'hstart' | 'hcenter' | 'hend';
const flip: {[key: string]: MainPlacement} = {
left: 'right',
right: 'left',
bottom: 'top',
top: 'bottom'
};
// tslint:disable-next-line: max-line-length
export type UxPositioningFactory = (anchor: HTMLElement, element: HTMLElement, options?: UxPositioningOptions) => UxPositioning;
@inject(UxPositioningConfiguration, TaskQueue)
export class UxPositioning {
public anchor: HTMLElement;
public element: HTMLElement;
public constraintElement: HTMLElement | Window;
public preferedPlacement: UxPlacement = 'auto';
public missingSpaceStrategy: UxMissingSpaceStrategy = 'flip';
public offsetX: number = 5;
public offsetY: number = 5;
public constraintMarginX: number = 5;
public constraintMarginY: number = 5;
public hiddenClass = 'ux-positioning--hidden';
// will be used for each positioning calculation
private anchorRect: DOMRect | ClientRect;
private elementRect: DOMRect | ClientRect;
private hostOffsetX: number = 0;
private hostOffsetY: number = 0;
private constraintX: number = 0;
private constraintY: number = 0;
private constraintHeight: number = 0;
private constraintWidth: number = window.innerWidth;
private spaceTop?: number = void 0;
private spaceRight?: number = void 0;
private spaceBottom?: number = void 0;
private spaceLeft?: number = void 0;
constructor(
configuration: UxPositioningConfiguration,
public taskQueue: TaskQueue,
anchor: HTMLElement,
element: HTMLElement,
options?: UxPositioningOptions
) {
const settings: UxPositioningOptions = {...configuration, ...options};
this.anchor = anchor;
this.element = element;
if (settings && settings.placement) {
this.preferedPlacement = settings.placement;
}
if (settings && settings.missingSpaceStrategy) {
this.missingSpaceStrategy = settings.missingSpaceStrategy;
}
if (settings && settings.hiddenClass) {
this.hiddenClass = settings.hiddenClass;
}
if (settings && settings.offsetX !== undefined) {
this.offsetX = settings.offsetX;
}
if (settings && settings.offsetY !== undefined) {
this.offsetY = settings.offsetY;
}
if (settings && settings.constraintMarginX !== undefined) {
this.constraintMarginX = settings.constraintMarginX;
}
if (settings && settings.constraintMarginY !== undefined) {
this.constraintMarginY = settings.constraintMarginY;
}
this.constraintElement = settings && settings.constraintElement
? this.constraintElement = settings.constraintElement
: this.constraintElement = element.parentElement || window;
this.init();
return this;
}
private init() {
// When we init the positioning, it might happen that it occurs
// a little too early and the element that we must positionned
// is not quite ready. We check this with a DOMRect() and if
// the width or height are not set we assume we should wait
// a little before positioning
this.update();
const rect = this.element.getBoundingClientRect();
if (rect.width && rect.height) {
this.update();
} else {
// We use queueTask here because queueMicroTask
// resolves too early in several occasions
// this.taskQueue.queueTask(() => {
// this.update();
// });
setTimeout(() => {
this.update();
}, 0);
}
}
public async update() {
this.resetElement();
this.prepare();
// try the prefered placement
const mainPlacement = this.getMainPlacement();
let hide = false;
if (!this.placeMain(mainPlacement, this.missingSpaceStrategy)) {
// placeMain returns false if the placement could not be ideally done
// with the requested strategy
if (this.missingSpaceStrategy === 'flip') {
const alternativePlacement = flip[mainPlacement];
if (!this.placeMain(alternativePlacement)) {
// if flip doesn't work either, then we force the main placement
this.placeMain(mainPlacement, 'ignore');
}
} else if (this.missingSpaceStrategy === 'hide') {
hide = true;
}
}
this.element.classList.toggle(this.hiddenClass, hide);
if (hide) {
return;
}
const secondaryPlacement = this.getSecondaryPlacement(mainPlacement);
this.placeSecondary(secondaryPlacement);
}
private resetElement() {
const style = this.element.style;
style.position = 'absolute';
style.top = '0';
style.left = '0';
style.right = 'auto';
style.bottom = 'auto';
style.width = 'unset';
style.height = 'unset';
}
private getMainPlacement(): MainPlacement {
if (this.preferedPlacement === 'auto' || this.preferedPlacement === 'auto-end' || this.preferedPlacement === 'auto-start') {
return this.getAutoPlacement();
}
return this.preferedPlacement.split('-')[0] as 'left' | 'right' | 'top' | 'bottom';
}
private prepare() {
// set first variables that are needed in all scenarios
this.anchorRect = this.anchor.getBoundingClientRect();
this.elementRect = this.element.getBoundingClientRect();
this.hostOffsetX = 0;
this.hostOffsetY = 0;
if (this.element.parentElement) {
// set the host to relative if static
const style = window.getComputedStyle(this.element.parentElement);
if (style.position === 'static') {
this.element.parentElement.style.position = 'relative';
}
const rect = this.element.parentElement.getBoundingClientRect();
this.hostOffsetX = rect.left * -1;
this.hostOffsetY = rect.top * -1;
// If the host container has borders, they need to be offseted
// Important: this suppose a border-box box-sizing
// The reason is because the border is included in the sizing of the
// host (width and height) but not included when it comes to positioning
// the child element (top:0, left:0 start inside the element)
if (style.borderLeftWidth) {
this.hostOffsetX = this.hostOffsetX - parseFloat(style.borderLeftWidth);
}
if (style.borderTopWidth) {
this.hostOffsetY = this.hostOffsetY - parseFloat(style.borderTopWidth);
}
}
this.constraintX = 0;
this.constraintY = 0;
this.constraintHeight = 0;
this.constraintWidth = window.innerWidth;
if (this.constraintElement instanceof HTMLElement) {
const rect = this.constraintElement.getBoundingClientRect();
this.constraintX = rect.left;
this.constraintY = rect.top;
this.constraintHeight = rect.height;
this.constraintWidth = rect.width;
}
this.spaceTop = undefined;
this.spaceRight = undefined;
this.spaceBottom = undefined;
this.spaceLeft = undefined;
}
private getSpaceTop() {
if (this.spaceTop !== undefined) {
return this.spaceTop;
}
this.spaceTop = this.anchorRect.top - this.constraintY - this.constraintMarginY;
return this.spaceTop;
}
private getSpaceRight() {
if (this.spaceRight !== undefined) {
return this.spaceRight;
}
this.spaceRight = this.constraintElement === window
// tslint:disable-next-line: max-line-length
? window.innerWidth - window.scrollX - this.anchorRect.width - this.anchorRect.left - this.constraintX - this.constraintMarginX
: this.constraintX + this.constraintWidth - this.anchorRect.width - this.anchorRect.left - this.constraintMarginX;
return this.spaceRight;
}
private getSpaceBottom() {
if (this.spaceBottom !== undefined) {
return this.spaceBottom;
}
this.spaceBottom = this.constraintElement === window
? window.innerHeight - window.scrollY - this.anchorRect.height - this.anchorRect.top - this.constraintY
// tslint:disable-next-line: max-line-length
: this.constraintY + this.constraintHeight - this.anchorRect.height - this.anchorRect.top - this.constraintMarginY;
return this.spaceBottom;
}
private getSpaceLeft() {
if (this.spaceLeft !== undefined) {
return this.spaceLeft;
}
this.spaceLeft = this.anchorRect.left - this.constraintX - this.constraintMarginX;
return this.spaceLeft;
}
private getAutoPlacement(): 'left' | 'right' | 'top' | 'bottom' {
// if the constraints is an HTMLElement, we include it here in the space check
const left = this.getSpaceLeft();
const right = this.getSpaceRight();
const top = this.getSpaceTop();
const bottom = this.getSpaceBottom();
if (left > right && left > top && left > bottom) {
return 'left';
} else if (right > top && right > bottom) {
return 'right';
} else if (top > bottom) {
return 'top';
}
return 'bottom';
}
private getSecondaryPlacement(mainPlacement: MainPlacement): SecondaryPlacement {
const prefix = mainPlacement === 'left' || mainPlacement === 'right' ? 'v' : 'h';
const instruction = this.preferedPlacement.split('-');
const suffix = instruction.length === 2 ? instruction[1] : 'center';
return `${prefix}${suffix}` as SecondaryPlacement;
}
private placeMain(placement: 'left' | 'right' | 'top' | 'bottom', missingSpaceStrategy: UxMissingSpaceStrategy = 'flip'): boolean {
const style = this.element.style;
const requiredWidth = this.elementRect.width + this.offsetX + this.constraintMarginX;
const requiredHeight = this.elementRect.height + this.offsetY + this.constraintMarginY;
if (missingSpaceStrategy !== 'ignore') {
const flipOrHide = missingSpaceStrategy === 'flip' || missingSpaceStrategy === 'hide';
// if !force => we check if there is enough space for placing the element
if (placement === 'left' && this.getSpaceLeft() < requiredWidth) {
if (flipOrHide) {
return false;
} else {
style.left = `${this.constraintX + this.hostOffsetX + this.constraintMarginX}px`;
style.top = `${this.anchorRect.top + this.hostOffsetY}px`;
return true;
}
}
if (placement === 'right' && this.getSpaceRight() < requiredWidth) {
if (flipOrHide) {
return false;
} else {
style.left = this.constraintElement === window
? `${window.innerWidth - this.elementRect.width - this.constraintMarginX + this.hostOffsetX}px`
: `${this.constraintX + this.constraintWidth - this.elementRect.width - this.constraintMarginX + this.hostOffsetX}px`;
style.top = `${this.anchorRect.top + this.hostOffsetY}px`;
return true;
}
}
if (placement === 'top' && this.getSpaceTop() < requiredHeight) {
if (flipOrHide) {
return false;
} else {
style.left = `${this.anchorRect.left + this.hostOffsetX}px`;
style.top = `${this.constraintY + this.hostOffsetY + this.constraintMarginY}px`;
return true;
}
}
if (placement === 'bottom' && this.getSpaceBottom() < requiredHeight) {
if (flipOrHide) {
return false;
} else {
style.left = `${this.anchorRect.left + this.hostOffsetX}px`;
style.top = this.constraintElement === window
? `${window.innerHeight - this.elementRect.height - this.constraintMarginY + this.hostOffsetY}px`
: `${this.constraintY + this.constraintHeight - this.elementRect.height - this.constraintMarginY + this.hostOffsetY}px`;
return true;
}
}
}
if (placement === 'left') {
style.left = `${this.anchorRect.left - this.elementRect.width - this.offsetX + this.hostOffsetX}px`;
style.top = `${this.anchorRect.top + this.hostOffsetY}px`;
}
if (placement === 'right') {
style.left = `${this.anchorRect.left + this.anchorRect.width + this.offsetX + this.hostOffsetX}px`;
style.top = `${this.anchorRect.top + this.hostOffsetY}px`;
}
if (placement === 'top') {
style.top = `${this.anchorRect.top - this.elementRect.height - this.offsetY + this.hostOffsetY}px`;
style.left = `${this.anchorRect.left + this.hostOffsetX}px`;
}
if (placement === 'bottom') {
style.top = `${this.anchorRect.top + this.anchorRect.height + this.offsetY + this.hostOffsetY}px`;
style.left = `${this.anchorRect.left + this.hostOffsetX}px`;
}
return true;
}
private placeSecondary(placement: SecondaryPlacement) {
const style = this.element.style;
if (placement === 'hstart' || placement === 'hcenter' || placement === 'hend') {
let left: number = 0;
if (placement === 'hstart') {
left = this.anchorRect.left + this.hostOffsetX;
} else if (placement === 'hcenter') {
left = this.anchorRect.left + this.hostOffsetX + (this.anchorRect.width / 2) - (this.elementRect.width / 2);
} else if (placement === 'hend') {
left = this.anchorRect.left + this.hostOffsetX + this.anchorRect.width - this.elementRect.width;
}
// First we check if the element overflow on the right of the screen
// and if it does, we bring it back inside the requested margin
// Second we check if the element overflow on the left of the screen
// We do this check in second as then it takes priority and if the element
// must overflow, then it will be on the right
if (this.missingSpaceStrategy === 'ignore') {
// do nothing
} else if (this.constraintElement === window) {
// tslint:disable-next-line: max-line-length
const xExtraRight = left + this.elementRect.width - window.innerWidth - window.scrollX + this.constraintMarginX - this.hostOffsetX;
if (xExtraRight > 0) {
left -= xExtraRight;
}
if (left < this.constraintMarginX + this.hostOffsetX) {
left = this.constraintMarginX + this.hostOffsetX;
}
} else if (this.constraintElement instanceof HTMLElement) {
const constraintMaxX = this.constraintX + this.constraintWidth;
const elementMaxX = left + this.elementRect.width - this.hostOffsetX + this.constraintMarginX;
const xExtraRight = elementMaxX - constraintMaxX;
if (xExtraRight > 0) {
left -= xExtraRight;
}
if (left < this.constraintX + this.hostOffsetX + this.constraintMarginX) {
left = this.constraintX + this.hostOffsetX + this.constraintMarginX;
}
}
style.left = `${left}px`;
}
if (placement === 'vstart' || placement === 'vcenter' || placement === 'vend') {
let top: number = 0;
if (placement === 'vstart') {
top = this.anchorRect.top + this.hostOffsetY;
} else if (placement === 'vcenter') {
top = this.anchorRect.top + this.hostOffsetY + (this.anchorRect.height / 2) - (this.elementRect.height / 2);
} else if (placement === 'vend') {
top = this.anchorRect.top + this.hostOffsetY + this.anchorRect.height - this.elementRect.height;
}
// First we check if the element overflow on the right of the screen
// and if it does, we bring it back inside the requested margin
// Second we check if the element overflow on the left of the screen
// We do this check in second as then it takes priority and if the element
// must overflow, then it will be on the right
if (this.missingSpaceStrategy === 'ignore') {
// do nothing
} else if (this.constraintElement === window) {
// tslint:disable-next-line: max-line-length
const yExtraBottom = top + this.elementRect.height - window.innerHeight - window.scrollY + this.constraintMarginY - this.hostOffsetY;
if (yExtraBottom > 0) {
top -= yExtraBottom;
}
if (top < this.constraintMarginY + this.hostOffsetY) {
top = this.constraintMarginY + this.hostOffsetY;
}
} else if (this.constraintElement instanceof HTMLElement) {
const constraintMaxY = this.constraintY + this.constraintHeight;
const elementMaxY = top + this.elementRect.height - this.hostOffsetY + this.constraintMarginY;
const yExtraBottom = elementMaxY - constraintMaxY;
if (yExtraBottom > 0) {
top -= yExtraBottom;
}
if (top < this.constraintY + this.hostOffsetY + this.constraintMarginY) {
top = this.constraintY + this.hostOffsetY + this.constraintMarginY;
}
}
style.top = `${top}px`;
}
}
} | the_stack |
// tslint:disable:no-duplicate-imports
// tslint:disable:trailing-comma
import * as assert from 'assert';
import * as parsec from 'typescript-parsec';
import { buildLexer, Token } from 'typescript-parsec';
import { alt, apply, errd, kleft, kmid, kright, opt, opt_sc, rep, rep_sc, repr, seq, str, tok } from 'typescript-parsec';
function notUndefined<T>(t: T | undefined): T {
assert.notStrictEqual(t, undefined);
return <T>t;
}
function succeeded<TKind, TResult>(r: parsec.ParserOutput<TKind, TResult>): parsec.ParseResult<TKind, TResult>[] {
if (r.successful) {
return r.candidates;
}
throw new Error(`The parsing does not succeed.`);
}
enum TokenKind {
Number,
Identifier,
Comma,
Space,
}
const lexer = buildLexer([
[true, /^\d+/g, TokenKind.Number],
[true, /^[a-zA-Z]\w*/g, TokenKind.Identifier],
[false, /^,/g, TokenKind.Comma],
[false, /^\s+/g, TokenKind.Space]
]);
test(`Parser: str`, () => {
const firstToken = notUndefined(lexer.parse(`123,456`));
{
const result = succeeded(str('123').parse(firstToken));
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].result.text, '123');
assert.strictEqual(result[0].firstToken, firstToken);
assert.strictEqual(result[0].nextToken, firstToken.next);
}
{
const result = str('456').parse(firstToken);
assert.strictEqual(result.successful, false);
}
});
test(`Parser: tok`, () => {
const firstToken = notUndefined(lexer.parse(`123,456`));
{
const result = succeeded(tok(TokenKind.Number).parse(firstToken));
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].result.text, '123');
assert.strictEqual(result[0].firstToken, firstToken);
assert.strictEqual(result[0].nextToken, firstToken.next);
}
{
const result = str('456').parse(firstToken);
assert.strictEqual(result.successful, false);
}
});
test(`Parser: alt`, () => {
const firstToken = notUndefined(lexer.parse(`123,456`));
{
const result = succeeded(alt(tok(TokenKind.Number), tok(TokenKind.Identifier)).parse(firstToken));
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].result.text, '123');
assert.strictEqual(result[0].firstToken, firstToken);
assert.strictEqual(result[0].nextToken, firstToken.next);
}
});
test(`Parser: seq`, () => {
const firstToken = notUndefined(lexer.parse(`123,456`));
{
const result = seq(tok(TokenKind.Number), tok(TokenKind.Identifier)).parse(firstToken);
assert.strictEqual(result.successful, false);
}
{
const result = succeeded(seq(tok(TokenKind.Number), tok(TokenKind.Number)).parse(firstToken));
assert.strictEqual(result.length, 1);
assert.deepStrictEqual(result[0].result.map((value: Token<TokenKind>) => value.text), ['123', '456']);
assert.strictEqual(result[0].firstToken, firstToken);
assert.strictEqual(result[0].nextToken, undefined);
}
});
test(`Parser: kleft, kmid, kright`, () => {
const firstToken = notUndefined(lexer.parse(`123,456,789`));
{
const result = succeeded(kleft(tok(TokenKind.Number), seq(tok(TokenKind.Number), tok(TokenKind.Number))).parse(firstToken));
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].result.text, '123');
assert.strictEqual(result[0].firstToken, firstToken);
assert.strictEqual(result[0].nextToken, undefined);
}
{
const result = succeeded(kmid(tok(TokenKind.Number), tok(TokenKind.Number), tok(TokenKind.Number)).parse(firstToken));
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].result.text, '456');
assert.strictEqual(result[0].firstToken, firstToken);
assert.strictEqual(result[0].nextToken, undefined);
}
{
const result = succeeded(kright(tok(TokenKind.Number), seq(tok(TokenKind.Number), tok(TokenKind.Number))).parse(firstToken));
assert.strictEqual(result.length, 1);
assert.deepStrictEqual(result[0].result.map((value: Token<TokenKind>) => value.text), ['456', '789']);
assert.strictEqual(result[0].firstToken, firstToken);
assert.strictEqual(result[0].nextToken, undefined);
}
});
test(`Parser: opt`, () => {
const firstToken = notUndefined(lexer.parse(`123,456`));
{
const result = succeeded(opt(tok(TokenKind.Number)).parse(firstToken));
assert.strictEqual(result.length, 2);
assert.strictEqual((<Token<TokenKind>>result[0].result).text, '123');
assert.strictEqual(result[0].firstToken, firstToken);
assert.strictEqual(result[0].nextToken, firstToken.next);
assert.strictEqual(result[1].result, undefined);
assert.strictEqual(result[1].firstToken, firstToken);
assert.strictEqual(result[1].nextToken, firstToken);
}
});
test(`Parser: opt_sc`, () => {
const firstToken = notUndefined(lexer.parse(`123,456`));
{
const result = succeeded(opt_sc(tok(TokenKind.Number)).parse(firstToken));
assert.strictEqual(result.length, 1);
assert.strictEqual((<Token<TokenKind>>result[0].result).text, '123');
assert.strictEqual(result[0].firstToken, firstToken);
assert.strictEqual(result[0].nextToken, firstToken.next);
}
{
const result = succeeded(opt_sc(tok(TokenKind.Identifier)).parse(firstToken));
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].result, undefined);
assert.strictEqual(result[0].firstToken, firstToken);
assert.strictEqual(result[0].nextToken, firstToken);
}
});
test(`Parser: rep_sc`, () => {
const firstToken = notUndefined(lexer.parse(`123,456`));
{
const result = succeeded(rep_sc(tok(TokenKind.Number)).parse(firstToken));
assert.strictEqual(result.length, 1);
assert.deepStrictEqual(result[0].result.map((value: Token<TokenKind>) => value.text), ['123', '456']);
assert.strictEqual(result[0].firstToken, firstToken);
assert.strictEqual(result[0].nextToken, undefined);
}
{
const result = succeeded(rep_sc(tok(TokenKind.Identifier)).parse(firstToken));
assert.strictEqual(result.length, 1);
assert.deepStrictEqual(result[0].result.map((value: Token<TokenKind>) => value.text), []);
assert.strictEqual(result[0].firstToken, firstToken);
assert.strictEqual(result[0].nextToken, firstToken);
}
});
test(`Parser: repr`, () => {
const firstToken = notUndefined(lexer.parse(`123,456`));
{
const result = succeeded(repr(tok(TokenKind.Number)).parse(firstToken));
assert.strictEqual(result.length, 3);
assert.deepStrictEqual(result[0].result, []);
assert.strictEqual(result[0].firstToken, firstToken);
assert.strictEqual(result[0].nextToken, firstToken);
assert.deepStrictEqual(result[1].result.map((value: Token<TokenKind>) => value.text), ['123']);
assert.strictEqual(result[1].firstToken, firstToken);
assert.strictEqual(result[1].nextToken, firstToken.next);
assert.deepStrictEqual(result[2].result.map((value: Token<TokenKind>) => value.text), ['123', '456']);
assert.strictEqual(result[2].firstToken, firstToken);
assert.strictEqual(result[2].nextToken, undefined);
}
});
test(`Parser: rep`, () => {
const firstToken = notUndefined(lexer.parse(`123,456`));
{
const result = succeeded(rep(tok(TokenKind.Number)).parse(firstToken));
assert.strictEqual(result.length, 3);
assert.deepStrictEqual(result[0].result.map((value: Token<TokenKind>) => value.text), ['123', '456']);
assert.strictEqual(result[0].firstToken, firstToken);
assert.strictEqual(result[0].nextToken, undefined);
assert.deepStrictEqual(result[1].result.map((value: Token<TokenKind>) => value.text), ['123']);
assert.strictEqual(result[1].firstToken, firstToken);
assert.strictEqual(result[1].nextToken, firstToken.next);
assert.deepStrictEqual(result[2].result, []);
assert.strictEqual(result[2].firstToken, firstToken);
assert.strictEqual(result[2].nextToken, firstToken);
}
});
test(`Parser: apply`, () => {
const firstToken = notUndefined(lexer.parse(`123,456`));
{
const result = succeeded(
apply(
repr(tok(TokenKind.Number)),
(values: Token<TokenKind>[]) => {
return values.map((value: Token<TokenKind>) => {
return value.text;
}).join(';');
}
).parse(firstToken)
);
assert.strictEqual(result.length, 3);
assert.strictEqual(result[0].result, '');
assert.strictEqual(result[0].firstToken, firstToken);
assert.strictEqual(result[0].nextToken, firstToken);
assert.strictEqual(result[1].result, '123');
assert.strictEqual(result[1].firstToken, firstToken);
assert.strictEqual(result[1].nextToken, firstToken.next);
assert.strictEqual(result[2].result, '123;456');
assert.strictEqual(result[2].firstToken, firstToken);
assert.strictEqual(result[2].nextToken, undefined);
}
});
test(`Parser: errd`, () => {
const firstToken = notUndefined(lexer.parse(`a`));
{
const result =
errd(
apply(
tok(TokenKind.Number),
(value: Token<TokenKind>) => +value.text
),
'This is not a number!',
1024
).parse(firstToken);
assert.strictEqual(result.successful, true);
if (result.successful) {
assert.strictEqual(result.candidates.length, 1);
assert.strictEqual(result.candidates[0].result, 1024);
assert.strictEqual(result.candidates[0].firstToken, firstToken);
assert.strictEqual(result.candidates[0].nextToken, firstToken);
assert.deepStrictEqual(result.error, {
kind: 'Error',
pos: firstToken.pos,
message: 'This is not a number!'
});
}
}
}); | the_stack |
import { RequestParameters } from "@azure-rest/core-client";
import {
BasicDef,
IntWrapper,
LongWrapper,
FloatWrapper,
DoubleWrapper,
BooleanWrapper,
StringWrapper,
DateWrapper,
DatetimeWrapper,
Datetimerfc1123Wrapper,
DurationWrapper,
ByteWrapper,
ArrayWrapper,
DictionaryWrapper,
Siamese,
Fish,
Salmon,
ReadonlyObj
} from "./models";
export type BasicGetValidParameters = RequestParameters;
export interface BasicPutValidBodyParam {
/** Please put {id: 2, name: 'abc', color: 'Magenta'} */
body: BasicDef;
}
export interface BasicPutValidMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type BasicPutValidParameters = BasicPutValidMediaTypesParam &
BasicPutValidBodyParam &
RequestParameters;
export type BasicGetInvalidParameters = RequestParameters;
export type BasicGetEmptyParameters = RequestParameters;
export type BasicGetNullParameters = RequestParameters;
export type BasicGetNotProvidedParameters = RequestParameters;
export type PrimitiveGetIntParameters = RequestParameters;
export interface PrimitivePutIntBodyParam {
/** Please put -1 and 2 */
body: IntWrapper;
}
export interface PrimitivePutIntMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type PrimitivePutIntParameters = PrimitivePutIntMediaTypesParam &
PrimitivePutIntBodyParam &
RequestParameters;
export type PrimitiveGetLongParameters = RequestParameters;
export interface PrimitivePutLongBodyParam {
/** Please put 1099511627775 and -999511627788 */
body: LongWrapper;
}
export interface PrimitivePutLongMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type PrimitivePutLongParameters = PrimitivePutLongMediaTypesParam &
PrimitivePutLongBodyParam &
RequestParameters;
export type PrimitiveGetFloatParameters = RequestParameters;
export interface PrimitivePutFloatBodyParam {
/** Please put 1.05 and -0.003 */
body: FloatWrapper;
}
export interface PrimitivePutFloatMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type PrimitivePutFloatParameters = PrimitivePutFloatMediaTypesParam &
PrimitivePutFloatBodyParam &
RequestParameters;
export type PrimitiveGetDoubleParameters = RequestParameters;
export interface PrimitivePutDoubleBodyParam {
/** Please put 3e-100 and -0.000000000000000000000000000000000000000000000000000000005 */
body: DoubleWrapper;
}
export interface PrimitivePutDoubleMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type PrimitivePutDoubleParameters = PrimitivePutDoubleMediaTypesParam &
PrimitivePutDoubleBodyParam &
RequestParameters;
export type PrimitiveGetBoolParameters = RequestParameters;
export interface PrimitivePutBoolBodyParam {
/** Please put true and false */
body: BooleanWrapper;
}
export interface PrimitivePutBoolMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type PrimitivePutBoolParameters = PrimitivePutBoolMediaTypesParam &
PrimitivePutBoolBodyParam &
RequestParameters;
export type PrimitiveGetStringParameters = RequestParameters;
export interface PrimitivePutStringBodyParam {
/** Please put 'goodrequest', '', and null */
body: StringWrapper;
}
export interface PrimitivePutStringMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type PrimitivePutStringParameters = PrimitivePutStringMediaTypesParam &
PrimitivePutStringBodyParam &
RequestParameters;
export type PrimitiveGetDateParameters = RequestParameters;
export interface PrimitivePutDateBodyParam {
/** Please put '0001-01-01' and '2016-02-29' */
body: DateWrapper;
}
export interface PrimitivePutDateMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type PrimitivePutDateParameters = PrimitivePutDateMediaTypesParam &
PrimitivePutDateBodyParam &
RequestParameters;
export type PrimitiveGetDateTimeParameters = RequestParameters;
export interface PrimitivePutDateTimeBodyParam {
/** Please put '0001-01-01T12:00:00-04:00' and '2015-05-18T11:38:00-08:00' */
body: DatetimeWrapper;
}
export interface PrimitivePutDateTimeMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type PrimitivePutDateTimeParameters = PrimitivePutDateTimeMediaTypesParam &
PrimitivePutDateTimeBodyParam &
RequestParameters;
export type PrimitiveGetDateTimeRfc1123Parameters = RequestParameters;
export interface PrimitivePutDateTimeRfc1123BodyParam {
/** Please put 'Mon, 01 Jan 0001 12:00:00 GMT' and 'Mon, 18 May 2015 11:38:00 GMT' */
body: Datetimerfc1123Wrapper;
}
export interface PrimitivePutDateTimeRfc1123MediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type PrimitivePutDateTimeRfc1123Parameters = PrimitivePutDateTimeRfc1123MediaTypesParam &
PrimitivePutDateTimeRfc1123BodyParam &
RequestParameters;
export type PrimitiveGetDurationParameters = RequestParameters;
export interface PrimitivePutDurationBodyParam {
/** Please put 'P123DT22H14M12.011S' */
body: DurationWrapper;
}
export interface PrimitivePutDurationMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type PrimitivePutDurationParameters = PrimitivePutDurationMediaTypesParam &
PrimitivePutDurationBodyParam &
RequestParameters;
export type PrimitiveGetByteParameters = RequestParameters;
export interface PrimitivePutByteBodyParam {
/** Please put non-ascii byte string hex(FF FE FD FC 00 FA F9 F8 F7 F6) */
body: ByteWrapper;
}
export interface PrimitivePutByteMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type PrimitivePutByteParameters = PrimitivePutByteMediaTypesParam &
PrimitivePutByteBodyParam &
RequestParameters;
export type ArrayGetValidParameters = RequestParameters;
export interface ArrayPutValidBodyParam {
/** Please put an array with 4 items: "1, 2, 3, 4", "", null, "&S#$(*Y", "The quick brown fox jumps over the lazy dog" */
body: ArrayWrapper;
}
export interface ArrayPutValidMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type ArrayPutValidParameters = ArrayPutValidMediaTypesParam &
ArrayPutValidBodyParam &
RequestParameters;
export type ArrayGetEmptyParameters = RequestParameters;
export interface ArrayPutEmptyBodyParam {
/** Please put an empty array */
body: ArrayWrapper;
}
export interface ArrayPutEmptyMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type ArrayPutEmptyParameters = ArrayPutEmptyMediaTypesParam &
ArrayPutEmptyBodyParam &
RequestParameters;
export type ArrayGetNotProvidedParameters = RequestParameters;
export type DictionaryGetValidParameters = RequestParameters;
export interface DictionaryPutValidBodyParam {
/** Please put a dictionary with 5 key-value pairs: "txt":"notepad", "bmp":"mspaint", "xls":"excel", "exe":"", "":null */
body: DictionaryWrapper;
}
export interface DictionaryPutValidMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type DictionaryPutValidParameters = DictionaryPutValidMediaTypesParam &
DictionaryPutValidBodyParam &
RequestParameters;
export type DictionaryGetEmptyParameters = RequestParameters;
export interface DictionaryPutEmptyBodyParam {
/** Please put an empty dictionary */
body: DictionaryWrapper;
}
export interface DictionaryPutEmptyMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type DictionaryPutEmptyParameters = DictionaryPutEmptyMediaTypesParam &
DictionaryPutEmptyBodyParam &
RequestParameters;
export type DictionaryGetNullParameters = RequestParameters;
export type DictionaryGetNotProvidedParameters = RequestParameters;
export type InheritanceGetValidParameters = RequestParameters;
export interface InheritancePutValidBodyParam {
/** Please put a siamese with id=2, name="Siameee", color=green, breed=persion, which hates 2 dogs, the 1st one named "Potato" with id=1 and food="tomato", and the 2nd one named "Tomato" with id=-1 and food="french fries". */
body: Siamese;
}
export interface InheritancePutValidMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type InheritancePutValidParameters = InheritancePutValidMediaTypesParam &
InheritancePutValidBodyParam &
RequestParameters;
export type PolymorphismGetValidParameters = RequestParameters;
export interface PolymorphismPutValidBodyParam {
/**
* Please put a salmon that looks like this:
* {
* 'fishtype':'Salmon',
* 'location':'alaska',
* 'iswild':true,
* 'species':'king',
* 'length':1.0,
* 'siblings':[
* {
* 'fishtype':'Shark',
* 'age':6,
* 'birthday': '2012-01-05T01:00:00Z',
* 'length':20.0,
* 'species':'predator',
* },
* {
* 'fishtype':'Sawshark',
* 'age':105,
* 'birthday': '1900-01-05T01:00:00Z',
* 'length':10.0,
* 'picture': new Buffer([255, 255, 255, 255, 254]).toString('base64'),
* 'species':'dangerous',
* },
* {
* 'fishtype': 'goblin',
* 'age': 1,
* 'birthday': '2015-08-08T00:00:00Z',
* 'length': 30.0,
* 'species': 'scary',
* 'jawsize': 5
* }
* ]
* };
*/
body: Fish;
}
export interface PolymorphismPutValidMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type PolymorphismPutValidParameters = PolymorphismPutValidMediaTypesParam &
PolymorphismPutValidBodyParam &
RequestParameters;
export type PolymorphismGetDotSyntaxParameters = RequestParameters;
export type PolymorphismGetComposedWithDiscriminatorParameters = RequestParameters;
export type PolymorphismGetComposedWithoutDiscriminatorParameters = RequestParameters;
export type PolymorphismGetComplicatedParameters = RequestParameters;
export interface PolymorphismPutComplicatedBodyParam {
body: Salmon;
}
export interface PolymorphismPutComplicatedMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type PolymorphismPutComplicatedParameters = PolymorphismPutComplicatedMediaTypesParam &
PolymorphismPutComplicatedBodyParam &
RequestParameters;
export interface PolymorphismPutMissingDiscriminatorBodyParam {
body: Salmon;
}
export interface PolymorphismPutMissingDiscriminatorMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type PolymorphismPutMissingDiscriminatorParameters = PolymorphismPutMissingDiscriminatorMediaTypesParam &
PolymorphismPutMissingDiscriminatorBodyParam &
RequestParameters;
export interface PolymorphismPutValidMissingRequiredBodyParam {
/**
* Please attempt put a sawshark that looks like this, the client should not allow this data to be sent:
* {
* "fishtype": "sawshark",
* "species": "snaggle toothed",
* "length": 18.5,
* "age": 2,
* "birthday": "2013-06-01T01:00:00Z",
* "location": "alaska",
* "picture": base64(FF FF FF FF FE),
* "siblings": [
* {
* "fishtype": "shark",
* "species": "predator",
* "birthday": "2012-01-05T01:00:00Z",
* "length": 20,
* "age": 6
* },
* {
* "fishtype": "sawshark",
* "species": "dangerous",
* "picture": base64(FF FF FF FF FE),
* "length": 10,
* "age": 105
* }
* ]
* }
*/
body: Fish;
}
export interface PolymorphismPutValidMissingRequiredMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type PolymorphismPutValidMissingRequiredParameters = PolymorphismPutValidMissingRequiredMediaTypesParam &
PolymorphismPutValidMissingRequiredBodyParam &
RequestParameters;
export type PolymorphicrecursiveGetValidParameters = RequestParameters;
export interface PolymorphicrecursivePutValidBodyParam {
/**
* Please put a salmon that looks like this:
* {
* "fishtype": "salmon",
* "species": "king",
* "length": 1,
* "age": 1,
* "location": "alaska",
* "iswild": true,
* "siblings": [
* {
* "fishtype": "shark",
* "species": "predator",
* "length": 20,
* "age": 6,
* "siblings": [
* {
* "fishtype": "salmon",
* "species": "coho",
* "length": 2,
* "age": 2,
* "location": "atlantic",
* "iswild": true,
* "siblings": [
* {
* "fishtype": "shark",
* "species": "predator",
* "length": 20,
* "age": 6
* },
* {
* "fishtype": "sawshark",
* "species": "dangerous",
* "length": 10,
* "age": 105
* }
* ]
* },
* {
* "fishtype": "sawshark",
* "species": "dangerous",
* "length": 10,
* "age": 105
* }
* ]
* },
* {
* "fishtype": "sawshark",
* "species": "dangerous",
* "length": 10,
* "age": 105
* }
* ]
* }
*/
body: Fish;
}
export interface PolymorphicrecursivePutValidMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type PolymorphicrecursivePutValidParameters = PolymorphicrecursivePutValidMediaTypesParam &
PolymorphicrecursivePutValidBodyParam &
RequestParameters;
export type ReadonlypropertyGetValidParameters = RequestParameters;
export interface ReadonlypropertyPutValidBodyParam {
body: ReadonlyObj;
}
export interface ReadonlypropertyPutValidMediaTypesParam {
/** Request content type */
contentType?: "application/json";
}
export type ReadonlypropertyPutValidParameters = ReadonlypropertyPutValidMediaTypesParam &
ReadonlypropertyPutValidBodyParam &
RequestParameters;
export type FlattencomplexGetValidParameters = RequestParameters; | the_stack |
import { SourceLocation, SourceRange } from '../utils/source_locations';
import { ThingTalkSyntaxError } from '../utils/errors';
import { CONTEXTUAL_KEYWORDS, DOLLAR_KEYWORDS, FORBIDDEN_KEYWORDS, KEYWORDS } from './keywords';
import { Token } from './token';
function unescape(string : string, sourceloc : SourceRange) {
return string.replace(/(?:\\x([0-9a-fA-F]{2})|\\u([0-9a-fA-F]{2})|\\u\{([0-9a-fA-F]+)\}|\\(.))/g, (full, hex, unicode, codepoint, char) => {
if (hex || unicode || codepoint) {
return String.fromCharCode(parseInt(hex || unicode || codepoint, 16));
} else {
if (/[ux]|[1-9]/.test(char))
throw new ThingTalkSyntaxError(`Invalid escape \\${char}`, sourceloc);
switch (char) {
case 'n':
return '\n';
case 't':
return '\t';
case 'b':
return '\b';
case 'f':
return '\b';
case 'r':
return '\r';
case 'v':
return '\v';
case '0':
return '\0';
default:
return char;
}
}
});
}
export function* surfaceLexer(input : string) : IterableIterator<Token> {
let lineno = 0;
let offset = 0;
let column = 0;
function makeLocation() : SourceLocation {
// note: line and column numbers are 1-based (because that's what editors do)
return {
line: lineno + 1,
column: column + 1,
offset: offset + 1,
token: 0,
};
}
function done() {
return offset >= input.length;
}
// This lexical grammar tries to follow ECMA 262 6.0, aka JavaScript
// Link: https://www.ecma-international.org/ecma-262/6.0/#sec-ecmascript-language-lexical-grammar
//
// Intentional differences:
// - Line continuations are not supported
// - There is no automatic semicolon insertion
// - $ is not a valid character in identifiers (but identifiers starting with $ are recognized as keywords)
//
// Differences with JavaScript as commonly implemented by browsers (incl. Appendix B Web Compat.)
// - Old-school octal literals and octal escape sequences are not recognized (new style octals are ok)
//
// Thingtalk additions:
// - =~ and ~= are valid operators (a single token)
// - contains~, in_array~, ~contains and ~in_array are valid operators
// - := is a valid operator (legacy assignment for dataset)
// - $? is a valid operator
// - @ introduces class names
// - ^^ introduces entity names
// - #[ introduces annotations
// - #_[ introduces metadata (NL annotations)
// - a numeric literal can be followed immediately by an identifier to form a measure token (and that identifier
// is treated as unit even if it would be otherwise a keyword, e.g. "in")
// - a numeric literal can be followed immediately by a $ and an identifier to form a currency token
//
// Differences that could change in the future:
// - Unicode white space (characters in Zs class) is not recognized as such
// - Unicode in identifiers is not allowed
// - Unicode escape sequences in identifiers are not allowed
// - U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are not recognized as line terminators (but they can
// be used inside string literals)
// NOTE: do not move this to block scope!
// test() modifies the regexp object to set lastIndex and would be very confused if concurrent usage also
// modified the regexps
const SINGLE_LINE_BLOCK_COMMENT = /\/\*(?:[^\r\n*]|\*[^\r\n/])*\*\//y;
const WHITESPACE = /[ \t\v\f\u00a0\ufeff]+/y;
const MULTILINE_BLOCK_COMMENT_BEGIN = /\/\*(?:[^\r\n*]|\*[^\r\n/])*(?:\r\n|[\n\r])/y;
const MULTILINE_BLOCK_COMMENT_END = /(?:[^\r\n*]|\*[^\r\n/])*\*\//y;
const LINE_COMMENT = /\/\/[^\r\n]*(?:\r\n|[\n\r]|$)/y;
const NEWLINE = /(?:\r\n|[\n\r])/y;
const NEXT_LINE = /[^\r\n]*(?:\r\n|[\n\r])/y;
const DOLLAR_IDENT = /\$(?:[A-Za-z0-9_]+|\?)/y;
const IDENTIFIER = /[A-Za-z_][A-Za-z0-9_]*/y;
const CLASSNAME = /@[A-Za-z_][A-Za-z0-9_-]*(?:\.[A-Za-z_][A-Za-z0-9_-]*)*/y;
const ENTITYNAME = /\^\^[A-Za-z_][A-Za-z0-9_-]*(?:\.[A-Za-z_][A-Za-z0-9_-]*)*:[A-Za-z_][A-Za-z0-9_]*/y;
const TILDE_OPERATOR = /~[A-Za-z_][A-Za-z0-9_]*|[A-Za-z_][A-Za-z0-9_]*~/y;
// HACK: for compatibility with Thingpedia, we need to recognize Entity(...) type references without
// the ^^ marker
const OLD_ENTITY_REFERENCE = /Entity\([A-Za-z_][A-Za-z0-9_-]*(?:\.[A-Za-z_][A-Za-z0-9_-]*)*:[A-Za-z_][A-Za-z0-9_]*\)/y;
// note that line continuations are not handled, unlike in JS, because they are not very useful
// and make the grammar very messy
// also note that this regexp is loose wrt escape sequences, the actual escape handling is in unescape()
const STRING_LITERAL = /(?:"(?:[^\\\n\r"]|\\.)*"|'(?:[^\\\n\r']|\\.)*')/y;
const UNTERMINATED_STRING_LITERAL = /(?:"(?:[^\\\n\r"]|\\.)*(?:[\n\r]|$)|'(?:[^\\\n\r']|\\.)*(?:[\n\r]|$))/y;
// NOTE: ALL operators from JavaScript are recognized, plus the ThingTalk specific ones
// Of course, most operators will be rejected by the parser, but that's a different problem
// NOTE 2: this regexp needs to be sorted so that greedy left-first matches are longer
const PUNCTUATOR = /(?:>>>=|\.\.\.|===|!==|>>>|\*\*=|>>=|<<=|#_\[|#\[|[><+*/%~!&|^:-]=|=[~>]|==|\*\*|\+\+|--|<<|>>|&&|\|\||::|[{}()[\].;><*/+&|^!~?:=-])/y;
const DECIMAL_LITERAL = /-?(?:(?:0|[1-9][0-9]*)\.[0-9]*(?:[eE][+-]?[0-9]+)?|\.[0-9]+(?:[eE][+-]?[0-9]+)?|(?:0|[1-9][0-9]*)(?:[eE][+-]?[0-9]+)?)/y;
const BASE_INT_LITERAL = /-?(?:0[bB][01]+|0[xX][0-9A-Fa-f]+|0[oO][0-7]+)/y;
function test(regexp : RegExp) : number {
regexp.lastIndex = offset;
const match = regexp.exec(input);
if (match === null)
return 0;
else
return match[0].length;
}
function skip(regexp : RegExp) : boolean {
const eaten = test(regexp);
if (eaten > 0) {
offset += eaten;
column += eaten;
return true;
} else {
return false;
}
}
function consume(regexp : RegExp) : string|null {
const eaten = test(regexp);
if (eaten > 0) {
const v = input.substring(offset, offset + eaten);
offset += eaten;
column += eaten;
return v;
} else {
return null;
}
}
while (!done()) {
if (skip(NEWLINE)) {
lineno ++;
column = 0;
continue;
}
if (skip(MULTILINE_BLOCK_COMMENT_BEGIN)) {
lineno ++;
column = 0;
let ended = test(MULTILINE_BLOCK_COMMENT_END);
while (ended === 0) {
skip(NEXT_LINE);
lineno ++;
column = 0;
ended = test(MULTILINE_BLOCK_COMMENT_END);
}
offset += ended;
column = ended;
continue;
}
if (skip(LINE_COMMENT)) {
lineno ++;
column = 0;
continue;
}
if (skip(WHITESPACE))
continue;
if (skip(SINGLE_LINE_BLOCK_COMMENT))
continue;
const start = makeLocation();
if (skip(UNTERMINATED_STRING_LITERAL)) {
column = 0;
lineno += 1;
const end = makeLocation();
throw new ThingTalkSyntaxError(`Unterminated string literal`, { start, end });
}
const oldEntityName = consume(OLD_ENTITY_REFERENCE);
if (oldEntityName) {
const end = makeLocation();
yield Token.make('Entity', { start, end }, null);
yield Token.make( '(', { start, end }, null);
yield Token.make('ENTITY_NAME', { start, end },
oldEntityName.substring('Entity('.length, oldEntityName.length-1));
yield Token.make(')', { start, end }, null);
continue;
}
const tildeOp = consume(TILDE_OPERATOR);
if (tildeOp) {
const end = makeLocation();
yield Token.make(tildeOp, { start, end }, null);
continue;
}
const identifier = consume(IDENTIFIER);
if (identifier) {
const end = makeLocation();
if (FORBIDDEN_KEYWORDS.has(identifier))
throw new ThingTalkSyntaxError(`Forbidden token ${identifier}`, { start, end });
if (KEYWORDS.has(identifier) || CONTEXTUAL_KEYWORDS.has(identifier))
yield Token.make(identifier, { start, end }, null);
else
yield Token.make('IDENTIFIER', { start, end }, identifier);
continue;
}
const dollarident = consume(DOLLAR_IDENT);
if (dollarident) {
const end = makeLocation();
if (DOLLAR_KEYWORDS.has(dollarident))
yield Token.make(dollarident, { start, end }, null);
else
yield Token.make('DOLLARIDENTIFIER', { start, end }, dollarident.substring(1));
continue;
}
const className = consume(CLASSNAME);
if (className) {
const end = makeLocation();
// eat the @ at the beginning
yield Token.make('CLASS_OR_FUNCTION_REF', { start, end }, className.substring(1));
continue;
}
const entityName = consume(ENTITYNAME);
if (entityName) {
const end = makeLocation();
// eat the ^^ at the beginning
yield Token.make('ENTITY_NAME', { start, end }, entityName.substring(2));
continue;
}
const stringLiteral = consume(STRING_LITERAL);
if (stringLiteral) {
const end = makeLocation();
const range = { start, end };
// eat the opening/closing quote
const string = unescape(stringLiteral.substring(1, stringLiteral.length-1), range);
yield Token.make('QUOTED_STRING', range, string);
continue;
}
const intWithBase = consume(BASE_INT_LITERAL);
if (intWithBase) {
const negative = intWithBase[0] === '-';
const baseChar = negative ? intWithBase[2] : intWithBase[1];
let base : number;
switch (baseChar) {
case 'x':
case 'X':
base = 16;
break;
case 'b':
case 'B':
base = 2;
break;
case 'o':
case 'O':
base = 8;
break;
default:
throw new Error('unexpected');
}
const value = parseInt(intWithBase.substring(negative ? 3 : 2), base)
* (negative ? -1 : 1);
const end = makeLocation();
yield Token.make('NUMBER', { start, end }, value);
continue;
} else {
const decimal = consume(DECIMAL_LITERAL);
if (decimal) {
const end = makeLocation();
yield Token.make('NUMBER', { start, end }, parseFloat(decimal));
continue;
}
}
const punct = consume(PUNCTUATOR);
if (punct) {
const end = makeLocation();
yield Token.make(punct, { start, end }, null);
continue;
}
// we have exhausted all possibilities: it is not an identifier, not a keyword, not a numeric or string literal,
// hence it is an invalid token
// we just take the next character, generate a token for it, and let the parser deal with it
const char = input[offset];
offset += 1;
column += 1;
const end = makeLocation();
yield Token.make(char, { start, end }, null);
}
} | the_stack |
import { JsonConvert } from "../src/json2typescript/json-convert";
import { JsonObject, JsonProperty } from "../src/json2typescript/json-convert-decorators";
import { PropertyConvertingMode, ValueCheckingMode } from "../src/json2typescript/json-convert-enums";
describe("JsonConvert primitive type tests", () => {
// <editor-fold desc="JSON CONVERT INSTANCES">
const jsonConvertIgnorePrimitives = new JsonConvert();
jsonConvertIgnorePrimitives.ignorePrimitiveChecks = true;
const jsonConvertCheckPrimitives = new JsonConvert();
jsonConvertCheckPrimitives.ignorePrimitiveChecks = false;
// </editor-fold>
// <editor-fold desc="CLASSES">
@JsonObject("PrimitivePropertyTest")
class PrimitivePropertyTest {
@JsonProperty("n", Number)
n: number = 0;
@JsonProperty("s", String)
s: string = "";
@JsonProperty("b", Boolean)
b: boolean = false;
}
// </editor-fold>
// <editor-fold desc="TESTS">
describe("primitive property checks", () => {
describe("serialize", () => {
it("ignore primitives", () => {
const tests: { data: any, expected?: any, mapUndefinedToNull?: boolean, throws?: boolean }[] = [
// Good data
{
data: {n: 0, s: "A", b: true},
expected: {n: 0, s: "A", b: true},
},
{
data: {n: "0", s: 1, b: "true"},
expected: {n: "0", s: 1, b: "true"},
},
// Bad data (wrong dimension)
{
data: {n: {value: 0}, s: "A", b: true},
throws: true,
},
{
data: {n: [0], s: "A", b: true},
throws: true,
},
{
data: {n: 0, s: {value: "A"}, b: true},
throws: true,
},
{
data: {n: 0, s: ["A"], b: true},
throws: true,
},
{
data: {n: 0, s: "A", b: {value: true}},
throws: true,
},
{
data: {n: 0, s: "A", b: [true]},
throws: true,
},
];
for (const test of tests) {
serializeData(
jsonConvertIgnorePrimitives,
test.data,
PrimitivePropertyTest,
test.expected,
test.throws,
);
}
});
it("check primitives", () => {
const tests: { data: any, expected?: any, mapUndefinedToNull?: boolean, throws?: boolean }[] = [
// Good data
{
data: {n: 0, s: "A", b: true},
expected: {n: 0, s: "A", b: true},
},
// Bad data (wrong primitive type)
{
data: {n: "0", s: "A", b: true},
throws: true,
},
{
data: {n: 0, s: 0, b: true},
throws: true,
},
{
data: {n: 0, s: "A", b: "true"},
throws: true,
},
// Bad data (wrong dimension)
{
data: {n: {value: 0}, s: "A", b: true},
throws: true,
},
{
data: {n: [0], s: "A", b: true},
throws: true,
},
{
data: {n: 0, s: {value: "A"}, b: true},
throws: true,
},
{
data: {n: 0, s: ["A"], b: true},
throws: true,
},
{
data: {n: 0, s: "A", b: {value: true}},
throws: true,
},
{
data: {n: 0, s: "A", b: [true]},
throws: true,
},
];
for (const test of tests) {
serializeData(
jsonConvertCheckPrimitives,
test.data,
PrimitivePropertyTest,
test.expected,
test.throws,
);
}
});
});
describe("deserialize", () => {
it("ignore primitives", () => {
const tests: { data: any, expected?: any, mapUndefinedToNull?: boolean, throws?: boolean }[] = [
// Good data
{
data: {n: 0, s: "A", b: true},
expected: {n: 0, s: "A", b: true},
},
{
data: {n: "0", s: 1, b: "true"},
expected: {n: "0", s: 1, b: "true"},
},
// Bad data (wrong dimension)
{
data: {n: {value: 0}, s: "A", b: true},
throws: true,
},
{
data: {n: [0], s: "A", b: true},
throws: true,
},
{
data: {n: 0, s: {value: "A"}, b: true},
throws: true,
},
{
data: {n: 0, s: ["A"], b: true},
throws: true,
},
{
data: {n: 0, s: "A", b: {value: true}},
throws: true,
},
{
data: {n: 0, s: "A", b: [true]},
throws: true,
},
];
for (const test of tests) {
deserializeData(
jsonConvertIgnorePrimitives,
test.data,
PrimitivePropertyTest,
test.expected,
test.throws,
);
}
});
it("check primitives", () => {
const tests: { data: any, expected?: any, mapUndefinedToNull?: boolean, throws?: boolean }[] = [
// Good data
{
data: {n: 0, s: "A", b: true},
expected: {n: 0, s: "A", b: true},
},
// Bad data (wrong primitive type)
{
data: {n: "0", s: "A", b: true},
throws: true,
},
{
data: {n: 0, s: 0, b: true},
throws: true,
},
{
data: {n: 0, s: "A", b: "true"},
throws: true,
},
// Bad data (wrong dimension)
{
data: {n: {value: 0}, s: "A", b: true},
throws: true,
},
{
data: {n: [0], s: "A", b: true},
throws: true,
},
{
data: {n: 0, s: {value: "A"}, b: true},
throws: true,
},
{
data: {n: 0, s: ["A"], b: true},
throws: true,
},
{
data: {n: 0, s: "A", b: {value: true}},
throws: true,
},
{
data: {n: 0, s: "A", b: [true]},
throws: true,
},
];
for (const test of tests) {
deserializeData(
jsonConvertCheckPrimitives,
test.data,
PrimitivePropertyTest,
test.expected,
test.throws,
);
}
});
});
});
// </editor-fold>
// <editor-fold desc="TEST METHODS">
/**
* Generic method for serializing data.
*/
function serializeData(jsonConvert: JsonConvert,
data: any,
classReference: any,
expectedResult: any,
throws: boolean = false): void {
if (throws) {
expect(() => jsonConvert.serialize(data, classReference)).toThrowError();
} else {
const result: any = jsonConvert.serialize(data, classReference);
if (result === undefined || result === null) {
expect(result).toEqual(expectedResult);
return;
}
Object.keys(result).forEach((key: string) => {
const value = result[key];
expect(value).toEqual(expectedResult[key]);
});
}
jsonConvert.mapUndefinedToNull = false;
}
/**
* Generic method for deserializing data.
*/
function deserializeData(jsonConvert: JsonConvert,
data: any,
classReference: any,
expectedResult: any,
throws: boolean = false): void {
if (throws) {
expect(() => jsonConvert.deserialize(data, classReference)).toThrowError();
} else {
const result: any = jsonConvert.deserialize(data, classReference);
if (result === undefined || result === null) {
expect(result).toEqual(expectedResult);
return;
}
Object.keys(result).forEach((key: string) => {
const value = result[key];
expect(value).toEqual(expectedResult[key]);
});
}
jsonConvert.mapUndefinedToNull = false;
}
// </editor-fold>
}); | the_stack |
import {
includes,
map,
reduce,
indexOf,
constant,
escapeRegExp,
get,
} from 'lodash';
import React, { useState } from 'react';
import { Meta } from '@storybook/react';
import { SearchableSingleSelect, Underline } from '../../index';
//👇 Provide Storybook with the component name, 'section', any subcomponents and a description
export default {
title: 'Controls/SearchableSingleSelect',
component: SearchableSingleSelect,
subcomponents: {
'SearchableSingleSelect.Placeholder': SearchableSingleSelect.SearchField,
'SearchableSingleSelect.Option': SearchableSingleSelect.Option,
'SearchableSingleSelect.Option.Selected':
SearchableSingleSelect.Option.Selected,
'SearchableSingleSelect.OptionGroup': SearchableSingleSelect.OptionGroup,
'SearchableSingleSelect.SearchField': SearchableSingleSelect.SearchField,
},
parameters: {
docs: {
description: {
component: SearchableSingleSelect.peek.description,
},
},
},
} as Meta;
//👇 Destructure any child components that we will need
const { Option, OptionGroup } = SearchableSingleSelect;
//👇 Add a key prop to each child element of the array
function addKeys(children: any) {
return map(children, (child, index) => ({ ...child, key: index }));
}
//👇 Create a “template” of how args map to rendering
const Template: any = (args) => {
return (
<section>
<SearchableSingleSelect {...args} style={{ maxWidth: '200px' }} />
</section>
);
};
//👇 Each story then reuses that template
/** Default */
export const Default = Template.bind({});
Default.args = {
SearchField: { placeholder: 'Search State' },
children: addKeys([
<Option>Alabama</Option>,
<Option>Alaska</Option>,
<Option>Arizona</Option>,
<Option>Arkansas</Option>,
<Option>California</Option>,
<Option>Colorado</Option>,
<Option>Connecticut</Option>,
<Option>Delaware</Option>,
<Option>Florida</Option>,
<Option>Georgia</Option>,
<Option>Hawaii</Option>,
<Option>Idaho</Option>,
<Option>Illinois</Option>,
<Option>Indiana</Option>,
<Option>Iowa</Option>,
<Option>Kansas</Option>,
<Option>Kentucky</Option>,
<Option>Louisiana</Option>,
<Option>Maine</Option>,
<Option>Maryland</Option>,
<Option>Massachusetts</Option>,
<Option>Michigan</Option>,
<Option>Minnesota</Option>,
<Option>Mississippi</Option>,
<Option>Missouri</Option>,
<Option>Montana Nebraska</Option>,
<Option>Nevada</Option>,
<Option>New Hampshire</Option>,
<Option>New Jersey</Option>,
<Option>New Mexico</Option>,
<Option>New York</Option>,
<Option>North Carolina</Option>,
<Option>North Dakota</Option>,
<Option>Ohio</Option>,
<Option>Oklahoma</Option>,
<Option>Oregon</Option>,
<Option>Pennsylvania Rhode Island</Option>,
<Option>South Carolina</Option>,
<Option>South Dakota</Option>,
<Option>Tennessee</Option>,
<Option>Texas</Option>,
<Option>Utah</Option>,
<Option>Vermont</Option>,
<Option>Virginia</Option>,
<Option>Washington</Option>,
<Option>West Virginia</Option>,
<Option>Wisconsin</Option>,
<Option>Wyoming</Option>,
]),
};
/** Props */
export const Props = (args) => {
return (
<section>
<h5>Loading</h5>
<SearchableSingleSelect {...args} isLoading={true}>
<Option>Alabama</Option>
</SearchableSingleSelect>
<h5>Disabled</h5>
<SearchableSingleSelect {...args} isDisabled={true}>
<Option>Alabama</Option>
</SearchableSingleSelect>
</section>
);
};
Props.args = {
...Default.args,
SearchField: { placeholder: '' },
};
Props.parameters = {
docs: {
description: {
story: `Apply \`isLoading\` to the dropdown when it is loading, and apply \`isDisabled\` to the dropdown if none of the options are currently available.
`,
},
},
};
/** Asynchronous */
const allData: any = {
100: { name: 'Rita Daniel' },
101: { name: 'Meghan Mcgowan' },
102: { name: 'Latisha Kent' },
103: { name: 'Jeannine Horton' },
104: { name: 'Noreen Joyner' },
105: { name: 'Angelique Head' },
106: { name: 'Kim Salinas' },
107: { name: 'Alexis Small' },
108: { name: 'Fernandez Singleton' },
109: { name: 'Jacqueline Alvarado' },
110: { name: 'Cornelia Roman' },
111: { name: 'John Gonzales' },
112: { name: 'Mcleod Hodge' },
113: { name: 'Fry Barrera' },
114: { name: 'Jannie Compton' },
115: { name: 'June Odom' },
116: { name: 'Rose Foster' },
117: { name: 'Kathryn Prince' },
118: { name: 'Hebert Bowman' },
119: { name: 'Shawn Burgess' },
};
export const Asynchronous = (args) => {
const [selectedId, setSelectedId] = useState<number | null>(null); // current selection
const [visibleIds, setVisibleIds] = useState<any[]>([]); // aka current search results
const [isLoading, setIsLoading] = useState<boolean>(false);
const handleSearch = (searchText) => {
setIsLoading(true);
// Fake an API call
setTimeout(() => {
const searchResults = reduce(
allData,
(acc: any[], { name }: { name: string }, id: string) => {
return includes(name.toLowerCase(), searchText.toLowerCase())
? acc.concat(id)
: acc;
},
[]
);
setIsLoading(false);
setVisibleIds(searchResults);
});
};
const handleSelect = (index: string, event: any) => {
const optionsId = get(event, 'props.callbackId', null);
setSelectedId(optionsId);
};
const selectedIndex =
indexOf(visibleIds, selectedId) === -1
? null
: indexOf(visibleIds, selectedId);
return (
<section>
<SearchableSingleSelect
{...args}
isLoading={isLoading}
onSelect={handleSelect}
onSearch={handleSearch}
selectedIndex={selectedIndex}
optionFilter={constant(true)}
SearchField={{
placeholder: 'Type here to simulate an API backed search',
}}
>
{map(visibleIds, (id) => (
<Option key={id} callbackId={id}>
{allData[id].name}
</Option>
))}
</SearchableSingleSelect>
</section>
);
};
/** Grouped Options */
export const GroupedOptions = Template.bind({});
GroupedOptions.args = {
children: addKeys([
<OptionGroup>
Northeast
<Option>Connecticut</Option>
<Option>Delaware</Option>
<Option>Maine</Option>
<Option>Maryland</Option>
<Option>Massachusetts</Option>
<Option>New Hampshire</Option>
<Option>New Jersey</Option>
<Option>New York</Option>
<Option>Pennsylvania</Option>
<Option>Rhode Island</Option>
<Option>Vermont</Option>
</OptionGroup>,
<OptionGroup>
Southeast
<Option>Alabama</Option>
<Option>Arkansas</Option>
<Option>Florida</Option>
<Option>Georgia</Option>
<Option>Kentucky</Option>
<Option>Louisiana</Option>
<Option>Mississippi</Option>
<Option>North Carolina</Option>
<Option>South Carolina</Option>
<Option>Tennessee</Option>
<Option>Virginia</Option>
<Option>West Virginia</Option>
</OptionGroup>,
<OptionGroup>
Midwest
<Option>Illinois</Option>
<Option>Indiana</Option>
<Option>Iowa</Option>
<Option>Kansas</Option>
<Option>Michigan</Option>
<Option>Minnesota</Option>
<Option>Missouri</Option>
<Option>Nebraska</Option>
<Option>North Dakota</Option>
<Option>Ohio</Option>
<Option>South Dakota</Option>
<Option>Wisconsin</Option>
</OptionGroup>,
<OptionGroup>
Southwest
<Option>Arizona</Option>
<Option>New Mexico</Option>
<Option>Oklahoma</Option>
<Option>Texas</Option>
</OptionGroup>,
<OptionGroup>
West
<Option>California</Option>
<Option>Colorado</Option>
<Option>Idaho</Option>
<Option>Montana</Option>
<Option>Nevada</Option>
<Option>Oregon</Option>
<Option>Utah</Option>
<Option>Washington</Option>
<Option>Wyoming</Option>
</OptionGroup>,
<Option>Alaska</Option>,
<Option>Hawaii</Option>,
]),
};
GroupedOptions.parameters = {
docs: {
description: {
story: `Grouped options allows you to have sections within your dropdown. Use this to help frame users' understanding of the options.
`,
},
},
};
/** Selected Option */
export const SelectedOption = Template.bind({});
SelectedOption.args = {
...Default.args,
SearchField: {
placeholder: 'Search Color',
},
children: addKeys([
<Option Selected={<div style={{ color: 'red' }}>RED</div>}>Red</Option>,
<Option Selected={<div style={{ color: 'blue' }}>BLUE</div>}>Blue</Option>,
<Option Selected={<div style={{ color: 'green' }}>GREEN</div>}>
Green
</Option>,
]),
};
/** Invalid Option */
export const InvalidOption = () => {
const [selectedIndex, setSelectedIndex] = useState<number | null>(null);
const handleSelect = (optionIndex: number | null) => {
setSelectedIndex(optionIndex);
};
return (
<SearchableSingleSelect
onSelect={handleSelect}
Error={selectedIndex === 2 ? null : 'Please Choose Green'}
>
<Option Selected={<div style={{ color: 'red' }}>RED</div>}>Red</Option>
<Option Selected={<div style={{ color: 'blue' }}>BLUE</div>}>Blue</Option>
<Option Selected={<div style={{ color: 'green' }}>GREEN</div>}>
Green
</Option>
</SearchableSingleSelect>
);
};
/** Formatted Options */
const OptionCols = ({
col1,
col2,
col3,
textMatch,
}: {
col1: string;
col2: string;
col3: string;
textMatch?: string | undefined;
}) => (
<div style={{ display: 'flex' }}>
<div style={{ width: 100 }}>
<Underline match={textMatch}>{col1}</Underline>
</div>
<div style={{ width: 100 }}>
<Underline match={textMatch}>{col2}</Underline>
</div>
<div style={{ width: 200 }}>
<Underline match={textMatch}>{col3}</Underline>
</div>
</div>
);
const optionFilter = (
searchText: string,
{ filterText }: { filterText: string }
) => {
if (filterText) {
return new RegExp(escapeRegExp(searchText), 'i').test(filterText);
}
return true;
};
export const FormattedOptions = Template.bind({});
FormattedOptions.args = {
...Default.args,
SearchField: {
placeholder: 'Search Options',
},
optionFilter,
children: addKeys([
<OptionGroup>
<OptionCols col1='ID' col2='NAME' col3='DESCRIPTION' />
<Option filterText='13 Drone lorem ipsum dolor sit' Selected='Drone (13)'>
{({ searchText }: { searchText: string }) => (
<OptionCols
col1='13'
col2='Drone'
col3='lorem ipsum dolor sit'
textMatch={searchText}
/>
)}
</Option>
<Option
filterText='14 Appa dolor sit amet consectetur'
Selected='Appa (14)'
>
{({ searchText }: { searchText: string }) => (
<OptionCols
col1='14'
col2='Appa'
col3='dolor sit amet consectetur'
textMatch={searchText}
/>
)}
</Option>
<Option
filterText='15 Breakfast amet consectetur adipiscing elit'
Selected='Breakfast (14)'
>
{({ searchText }: { searchText: string }) => (
<OptionCols
col1='14'
col2='Breakfast'
col3='amet consectetur adipiscing elit'
textMatch={searchText}
/>
)}
</Option>
<Option
filterText='16 Scout adipiscing elit sed do'
Selected='Scout (15)'
>
{({ searchText }: { searchText: string }) => (
<OptionCols
col1='15'
col2='Scout'
col3='adipiscing elit sed do'
textMatch={searchText}
/>
)}
</Option>
</OptionGroup>,
]),
};
FormattedOptions.parameters = {
docs: {
description: {
story: `Use multiple columns of data in your dropdown when additional information is needed to make a selection.
`,
},
},
}; | the_stack |
import { Aurelia, TaskQueue, useShadowDOM } from 'aurelia-framework';
import { inlineView, Controller, bindable, ShadowDOM, ViewSlot, ShadowSlot } from './aurelia-templating';
import 'aurelia-loader-webpack';
import { child, children } from '../src/child-observation';
interface IChildObserver {}
interface IBindableMutationObserver extends MutationObserver {
binders: IChildObserver[];
}
interface IMutationObserverHost extends Element {
__childObserver__: IBindableMutationObserver;
}
describe('child-observation.integration.spec.ts', () => {
beforeAll(() => waitForTicks(10));
for (const shouldUseShadowDom of [true, false]) {
describe(`[useShadowDOM(): ${shouldUseShadowDom}]`, () => {
it('gets the child correctly in basic scenario', async () => {
const Template_App =
`<template>
<parent-el view-model.ref=parentVm>
<div class="item"></div>
</parent-el>
</template>`;
const Template_Parent = '<template>This is parent<div><slot></slot></div></template>';
@inlineView(Template_App)
class App {
itemCount = 10;
parentVm: ParentEl;
}
@inlineView(Template_Parent)
class ParentEl {
@child('.item') item: HTMLDivElement;
@children('.item') items: HTMLDivElement[];
item_changed_call_count = 0;
items_changed_call_count = 0;
itemChanged() {
this.item_changed_call_count++;
}
itemsChanged() {
this.items_changed_call_count++;
}
}
if (shouldUseShadowDom) {
useShadowDOM({ mode: 'open' })(ParentEl);
}
const {
aurelia,
host,
root,
rootVm,
dispose,
} = await createFixture(App, [ParentEl]);
// right after app has started successfully,
// it is guaranteed that all child observation is setup & done
// so there's no difference between native shadowDOM & emulation
const parentVm = rootVm.parentVm;
expect(parentVm.item instanceof HTMLDivElement).toBe(true);
expect(parentVm.items.length).toBe(1, '1 .item');
expect(parentVm.items[0]).toBe(rootVm.parentVm.item);
expect(parentVm.item_changed_call_count).toBe(1);
expect(parentVm.items_changed_call_count).toBe(1);
const parentEl = host.querySelector('parent-el') as IMutationObserverHost;
assertIsMutationObserverHost(parentEl);
const observer = parentEl.__childObserver__;
expect(observer.binders.length).toBe(/* 1 for @child + 1 for @children */2);
dispose();
expect(observer.binders.length).toBe(0);
expect(parentVm.item_changed_call_count).toBe(1);
expect(parentVm.items_changed_call_count).toBe(1);
if (shouldUseShadowDom) {
// when using shadow DOM, the binder will clear the value on unbind
expect(parentVm.item).toBe(null);
expect(parentVm.items).toBe(null);
} else {
// when not using shadow DOM, the binder won't clear the value on unbind
expect(parentVm.item).not.toBe(null);
expect(parentVm.items).not.toBe(null);
}
});
describe('With [if]', () => {
// In this test, the assertions are:
// 1. initially render without any content element
// 2. showChild = true
// 3. showChild = false
// 4. showChild = true
// 5. dispose
it('works with [if] on content CHILD elements', async () => {
const Template_App =
`<template>
<parent-el view-model.ref=parentVm>
<div class="item" if.bind="showChild"></div>
</parent-el>
</template>`;
const Template_Parent = '<template>This is parent<p><slot></slot></p></template>';
@inlineView(Template_App)
class App {
showChild = false;
parentVm: ParentEl;
}
@inlineView(Template_Parent)
class ParentEl {
@child('.item') item: HTMLDivElement;
@children('.item') items: HTMLDivElement[];
item_changed_call_count = 0;
items_changed_call_count = 0;
itemChanged() {
this.item_changed_call_count++;
}
itemsChanged() {
this.items_changed_call_count++;
}
}
if (shouldUseShadowDom) {
useShadowDOM({ mode: 'open' })(ParentEl);
}
const {
aurelia,
host,
root,
rootVm,
taskQueue,
dispose,
} = await createFixture(App, [ParentEl]);
// Assertion 1 ===========================
const parentVm = rootVm.parentVm;
expect(parentVm.item).toBe(undefined);
if (shouldUseShadowDom) {
// when using shadowDOM, it's safe to initialize immediately
// so if theres no items, initialize it to an empty array
expect(parentVm.items).toEqual([], '0 .item');
} else {
expect(parentVm.items).toEqual(undefined, '0 .item');
}
const parentEl = host.querySelector('parent-el') as IMutationObserverHost;
const observer = parentEl.__childObserver__;
assertIsMutationObserverHost(parentEl);
expect(observer.binders.length).toBe(/* 1 for @child + 1 for @children */2);
// IMPORTANT: ==========
// In native shadow DOM + there's no children
// items Changed call count is always 1 count ahead of itemChanged call count
// as it is always call at the start, with empty values
expect(parentVm.item_changed_call_count).toBe(0, 'item changed() -- 1');
expect(parentVm.items_changed_call_count).toBe(shouldUseShadowDom ? 1 : 0, 'items changed() -- 1');
// Assertion 2 ===========================
rootVm.showChild = true;
// for mutation observer to fire
await waitForTicks(2);
expect(parentVm.item).not.toBe(null);
expect(parentVm.items.length).toBe(1, '0 .item');
expect(parentVm.items[0]).toBe(parentVm.item);
expect(parentVm.item_changed_call_count).toBe(1, 'item changed() -- 2');
expect(parentVm.items_changed_call_count).toBe(shouldUseShadowDom ? 2 : 1, 'items changed() -- 2');
// Assertion 3 ===========================
// Turning show child property back to false
// =======================================
rootVm.showChild = false;
// for mutation observer to fire
await waitForTicks(2);
if (shouldUseShadowDom) {
expect(parentVm.item).toBe(null);
expect(parentVm.items).toEqual([], '0 .item');
} else {
expect(parentVm.item).toBe(null, 'should have no .item after showChild = false');
expect(parentVm.items.length).toBe(0, '1 .item < after showChild = false');
}
expect(parentVm.item_changed_call_count).toBe(2, 'item changed() -- 3');
expect(parentVm.items_changed_call_count).toBe(shouldUseShadowDom ? 3 : 2, 'items changed() -- 3');
// Assertion 4 ===========================
// assert disposing logic with value already populated
rootVm.showChild = true;
await waitForTicks(2);
expect(parentVm.item).not.toBe(null);
expect(parentVm.items.length).toBe(1, '0 .item');
expect(parentVm.items[0]).toBe(parentVm.item);
expect(parentVm.item_changed_call_count).toBe(3, 'item changed() -- 4');
expect(parentVm.items_changed_call_count).toBe(shouldUseShadowDom ? 4 : 3, 'items changed() -- 4');
dispose();
// Assertion 5 ===========================
expect(observer.binders.length).toBe(0, 'should have no binders after dispose()');
expect(parentVm.item_changed_call_count).toBe(3, 'item changed() -- 5');
expect(parentVm.items_changed_call_count).toBe(shouldUseShadowDom ? 4 : 3, 'items changed() -- 5');
if (shouldUseShadowDom) {
// when not using shadow DOM, the binder won't clear the value on unbind
expect(parentVm.item).toBe(null);
expect(parentVm.items).toBe(null);
} else {
// when not using shadow DOM, the binder won't clear the value on unbind
expect(parentVm.item).not.toBe(null);
expect(parentVm.items).not.toBe(null);
}
});
// In this test, the assertions are:
// 1. initially render WITH parent element
// 2. assign false to if binding value, and remove parent element
// 3. assign true to if binding value, and show parent element
// 4. dispose the app
it('works with [if] on content PARENT elements', async () => {
const Template_App =
`<template>
<parent-el view-model.ref=parentVm if.bind="showParent">
<div class="item"></div>
</parent-el>
</template>`;
const Template_Parent = '<template>This is parent<p><slot></slot></p></template>';
@inlineView(Template_App)
class App {
showParent = true;
parentVm: ParentEl;
}
@inlineView(Template_Parent)
class ParentEl {
@child('.item') item: HTMLDivElement;
@children('.item') items: HTMLDivElement[];
item_changed_call_count = 0;
items_changed_call_count = 0;
itemChanged() {
this.item_changed_call_count++;
}
itemsChanged() {
this.items_changed_call_count++;
}
}
if (shouldUseShadowDom) {
useShadowDOM({ mode: 'open' })(ParentEl);
}
const {
aurelia,
host,
root,
rootVm,
taskQueue,
dispose,
} = await createFixture(App, [ParentEl]);
// Assertion 1 =========================================
// 1. initially render WITH parent element
const parentVm = rootVm.parentVm;
expect(parentVm.item instanceof HTMLElement).toBe(true);
expect(parentVm.items.length).toBe(1, '1 .item');
const parentEl = host.querySelector('parent-el') as IMutationObserverHost;
let observer = parentEl.__childObserver__;
assertIsMutationObserverHost(parentEl);
expect(observer.binders.length).toBe(/* 1 for @child + 1 for @children */2);
expect(parentVm.item_changed_call_count).toBe(1, 'item changed() -- 1');
expect(parentVm.items_changed_call_count).toBe(1, 'items changed() -- 1');
// Assertion 2 =========================================
// 2. assign false to if binding value, and remove parent element
rootVm.showParent = false;
// flush all aurelia bindings, including repeat/if
await waitForTicks(1);
// mutation observer is cleaned upon cleaning all binders
expect(parentEl.__childObserver__).toBe(null);
expect(observer.binders.length).toBe(0);
if (shouldUseShadowDom) {
expect(parentVm.item).toBe(null);
expect(parentVm.items).toBe(null);
} else {
expect(parentVm.item instanceof HTMLElement).toBe(true);
expect(parentVm.items.length).toBe(1, '1 .item');
expect(parentVm.items[0]).toBe(parentVm.item);
}
// for mutation observer to fire
await waitForTicks(1);
if (shouldUseShadowDom) {
expect(parentVm.item).toBe(null);
expect(parentVm.items).toBe(null);
} else {
expect(parentVm.item).not.toBe(null);
expect(parentVm.items.length).toBe(1, '0 .item');
expect(parentVm.items[0]).toBe(parentVm.item);
}
// nothing changed, DOM mutation wise
expect(parentVm.item_changed_call_count).toBe(1, 'item changed() -- 2');
expect(parentVm.items_changed_call_count).toBe(1, 'items changed() -- 2');
// Assertion 3 =========================================
// 3. assign true to if binding value, and show parent element
rootVm.showParent = true;
await waitForTicks(1);
// observer is clean so need to get a new reference
expect(observer).not.toBe(parentEl.__childObserver__);
observer = parentEl.__childObserver__;
expect(observer.binders.length).toBe(2, 'Should have 2 binders after showing parent');
// when using native shadow DOM
// whenever the mutation observer binder is bound
// it will calls the change handler, so it's 1 count ahead of the emulation
expect(parentVm.item_changed_call_count).toBe(shouldUseShadowDom ? 2 : 1, 'item changed() -- 3');
expect(parentVm.items_changed_call_count).toBe(shouldUseShadowDom ? 2 : 1, 'items changed() -- 3');
// Assertion 4 =========================================
// 4. dispose the app
dispose();
expect(observer.binders.length).toBe(0);
expect(parentEl.__childObserver__).toBe(null);
if (shouldUseShadowDom) {
expect(parentVm.item).toBe(null);
expect(parentVm.items).toBe(null);
} else {
// when not using shadow DOM, the binder won't clear the value on unbind
expect(parentVm.item).not.toBe(null);
expect(parentVm.items.length).toBe(1, '0 .item');
expect(parentVm.items[0]).toBe(parentVm.item);
}
expect(parentVm.item_changed_call_count).toBe(shouldUseShadowDom ? 2 : 1, 'item changed() -- 4');
expect(parentVm.items_changed_call_count).toBe(shouldUseShadowDom ? 2 : 1, 'items changed() -- 4');
});
});
describe('With [repeat]', () => {
// In this test, the assertions are:
// 1. initially render without any content element (itemCount = 0)
// 2. itemCount = 2, and render child content elements
// 3. itemCount = 0, and remove child content elements
// 4. itemCount = 2, and render child content elements
// 5. dispose the app
it('works with [repeat] on content CHILD elements', async () => {
const Template_App =
`<template>
<parent-el view-model.ref=parentVm>
<div id="item-\${i}" class="item" repeat.for="i of itemCount"></div>
</parent-el>
</template>`;
const Template_Parent = '<template>This is parent<p><slot></slot></p></template>';
@inlineView(Template_App)
class App {
itemCount = 0;
parentVm: ParentEl;
}
@inlineView(Template_Parent)
class ParentEl {
@child('.item') item: HTMLDivElement;
@children('.item') items: HTMLDivElement[];
item_changed_call_count = 0;
items_changed_call_count = 0;
itemChanged() {
this.item_changed_call_count++;
}
itemsChanged() {
this.items_changed_call_count++;
}
}
if (shouldUseShadowDom) {
useShadowDOM({ mode: 'open' })(ParentEl);
}
const {
aurelia,
host,
root,
rootVm,
taskQueue,
dispose,
} = await createFixture(App, [ParentEl]);
// Assertion 1 ===========================
// 1. initially render without any content element (itemCount = 0)
const parentVm = rootVm.parentVm;
expect(parentVm.item).toBe(undefined);
if (shouldUseShadowDom) {
// when using shadowDOM, it's safe to initialize immediately
// so if theres no items, initialize it to an empty array
expect(parentVm.items).toEqual([], '0 .item');
} else {
expect(parentVm.items).toEqual(undefined, '0 .item');
}
const parentEl = host.querySelector('parent-el') as IMutationObserverHost;
const observer = parentEl.__childObserver__;
assertIsMutationObserverHost(parentEl);
expect(observer.binders.length).toBe(/* 1 for @child + 1 for @children */2);
expect(parentVm.item_changed_call_count).toBe(0, 'item changed() -- 1');
expect(parentVm.items_changed_call_count).toBe(shouldUseShadowDom ? 1 : 0, 'items changed() -- 1');
// Assertion 2 ===========================
// 2. itemCount = 2, and render child content elements
rootVm.itemCount = 2;
// for mutation observer to fire
await waitForTicks(2);
expect(parentVm.item).not.toBe(null);
expect(parentVm.items.length).toBe(2, '0 .item');
expect(parentVm.items[0]).not.toBe(parentVm.items[1]);
expect(parentVm.items[1]).toBe(parentVm.item);
// note: change handler is call for every item when it's @child
// this could be a surprise, or perf issue
expect(parentVm.item_changed_call_count).toBe(2, 'item changed() -- 2');
expect(parentVm.items_changed_call_count).toBe(shouldUseShadowDom ? 2 : 1, 'items changed() -- 2');
// Assertion 3 ===========================
// 3. itemCount = 0, and remove child content elements
rootVm.itemCount = 0;
// for mutation observer to fire
await waitForTicks(2);
if (shouldUseShadowDom) {
expect(parentVm.item).toBe(null);
expect(parentVm.items).toEqual([], '0 .item');
} else {
expect(parentVm.item).toBe(null, 'should have no .item after showChild = false');
expect(parentVm.items.length).toBe(0, '1 .item < after showChild = false');
}
expect(parentVm.item_changed_call_count).toBe(3, 'item changed() -- 3');
expect(parentVm.items_changed_call_count).toBe(shouldUseShadowDom ? 3 : 2, 'items changed() -- 3');
// Assertion 4 ===========================
// 4. itemCount = 2, and render child content elements
rootVm.itemCount = 2;
await waitForTicks(2);
expect(parentVm.item).not.toBe(null);
expect(parentVm.items.length).toBe(2, '0 .item');
expect(parentVm.items[0]).not.toBe(parentVm.items[1]);
expect(parentVm.items[1]).toBe(parentVm.item);
expect(parentVm.item_changed_call_count).toBe(5, 'item changed() -- 4');
expect(parentVm.items_changed_call_count).toBe(shouldUseShadowDom ? 4 : 3, 'items changed() -- 4');
dispose();
// Assertion 5 ===========================
expect(observer.binders.length).toBe(0, 'should have no binders after dispose()');
expect(parentVm.item_changed_call_count).toBe(5, 'item changed() -- 5');
expect(parentVm.items_changed_call_count).toBe(shouldUseShadowDom ? 4 : 3, 'items changed() -- 5');
if (shouldUseShadowDom) {
// when not using shadow DOM, the binder won't clear the value on unbind
expect(parentVm.item).toBe(null);
expect(parentVm.items).toBe(null);
} else {
// when not using shadow DOM, the binder won't clear the value on unbind
expect(parentVm.item).not.toBe(null);
expect(parentVm.items).not.toBe(null);
expect(parentVm.items[0]).not.toBe(parentVm.items[1]);
expect(parentVm.items[1]).toBe(parentVm.item);
}
});
});
// In this test, the assertions are:
// 1. showParent = true + itemCount = 0
// ---- assert [add] while [attached] mutation ----
// 2. itemCount = 2
// 2.1 itemCount = 0
// 2.2 itemCount = 2
// ---- assert [removal] while [detached] mutation
// 3. showParent = false
// 4. itemCount = 0
// ---- assert [add] while [detached] ----
// 5. itemCount = 2
// ---- assert [removal] while [attached] mutation -----
// 6. showParent = true
// 7. itemCount = 0
// ---- final ----
// 8. dispose
it('\n\tworks with [if] on content PARENT elements\n\tAnd [repeat] on CHILD elements\n', async () => {
const Template_App =
`<template>
<parent-el view-model.ref=parentVm if.bind="showParent">
<div id="item-\${generateId(i)}" class="item" repeat.for="i of itemCount"></div>
</parent-el>
</template>`;
const Template_Parent = '<template>This is parent<p><slot></slot></p></template>';
@inlineView(Template_App)
class App {
showParent = true;
itemCount = 0;
parentVm: ParentEl;
id = 0;
generateId(i: number) {
return `item-${i}-${this.id++}`;
}
}
@inlineView(Template_Parent)
class ParentEl {
@child('.item') item: HTMLDivElement;
@children('.item') items: HTMLDivElement[];
item_changed_call_count = 0;
items_changed_call_count = 0;
itemChanged() {
this.item_changed_call_count++;
}
itemsChanged() {
this.items_changed_call_count++;
}
}
if (shouldUseShadowDom) {
useShadowDOM({ mode: 'open' })(ParentEl);
}
const {
host,
rootVm,
dispose,
} = await createFixture(App, [ParentEl]);
// Assertion 1 =========================================
// 1. initially render WITH parent element
const parentVm = rootVm.parentVm;
expect(parentVm.item).toBe(undefined, '0 .item');
if (shouldUseShadowDom) {
expect(parentVm.items).toEqual([], '[] .item[]');
} else {
expect(parentVm.items).toBe(undefined, '0 .item[]');
}
const parentEl = host.querySelector('parent-el') as IMutationObserverHost;
let observer = parentEl.__childObserver__;
assertIsMutationObserverHost(parentEl);
expect(observer.binders.length).toBe(/* 1 for @child + 1 for @children */2);
expect(parentVm.item_changed_call_count).toBe(0, 'item changed() -- 1');
// during .bind()
// change handler is always called when using native shadowDOM
expect(parentVm.items_changed_call_count).toBe(shouldUseShadowDom ? 1 : 0, 'items changed() -- 1');
// ---- assert [add] while [attached] mutation ----
// Assertion 2 =========================================
// 2. itemCount = 2
rootVm.itemCount = 2;
// for mutation observer to fire
await waitForTicks(2);
expect(parentVm.item).not.toBe(null);
expect(parentVm.items).not.toBe(null);
expect(parentVm.item instanceof HTMLElement).toBe(true);
expect(parentVm.items.length).toBe(2, '2 .item');
expect(parentVm.items[1]).toBe(parentVm.item);
expect(parentVm.item_changed_call_count).toBe(2, 'item changed() -- 2');
expect(parentVm.items_changed_call_count).toBe(shouldUseShadowDom ? 2 : 1, 'items changed() -- 2');
// 2.1 itemCount = 0
rootVm.itemCount = 0;
await waitForTicks(2);
expect(parentVm.item).toBe(null);
expect(parentVm.items).toEqual([]);
expect(parentVm.item_changed_call_count).toBe(3, 'item changed() -- 2.1');
expect(parentVm.items_changed_call_count).toBe(shouldUseShadowDom ? 3 : 2, 'items changed() -- 2.1');
// 2.2 itemCount = 2
rootVm.itemCount = 2;
await waitForTicks(2);
expect(parentVm.item).not.toBe(null);
expect(parentVm.items).not.toEqual([]);
expect(parentVm.item_changed_call_count).toBe(5, 'item changed() -- 2.2');
expect(parentVm.items_changed_call_count).toBe(shouldUseShadowDom ? 4 : 3, 'items changed() -- 2.2');
// ---- assert [removal] while [detached] mutation
// Assertion 3 =========================================
// 3. showParent = false
rootVm.showParent = false;
await waitForTicks(1);
expect(parentVm.item_changed_call_count).toBe(5, 'item changed() -- 3');
expect(parentVm.items_changed_call_count).toBe(shouldUseShadowDom ? 4 : 3, 'items changed() -- 3');
// ensure one mutation observer not affecting another
await waitForTicks(1);
// Assertion 4 =========================================
// 4. itemCount = 0
// This steps corrupts the repeat, and will leave 2 orphaned <div/> inside the
rootVm.itemCount = 0;
await waitForTicks(2);
if (shouldUseShadowDom) {
assertSelectorCount(parentEl, '.item', 0);
expect(parentVm.item).toBe(null, '4. item === null');
expect(parentVm.items).toBe(null, '4. items === null');
} else {
// shadow dom emulation doesn't response to mutation while detached
assertSelectorCount(parentEl, 'p > .item', 0);
expect(parentVm.item).not.toBe(null);
expect(parentVm.items).not.toBe(null);
expect(parentVm.items.length).toBe(/* 2 orphaned */2);
}
expect(parentVm.item_changed_call_count).toBe(5, 'item changed() -- 4');
expect(parentVm.items_changed_call_count).toBe(shouldUseShadowDom ? 4 : 3, 'items changed() -- 4');
// ---- assert [add] while [detached] ----
// Assertion 5 =========================================
// 5. itemCount = 2
const old_item = parentVm.item;
// const old_items_arr = parentVm.items;
// const old_items = old_items_arr?.slice(0) ?? [];
rootVm.itemCount = 2;
await waitForTicks(2);
if (shouldUseShadowDom) {
assertSelectorCount(parentEl, '.item', 0);
expect(parentVm.item).toBe(null, '5. item === null');
expect(parentVm.item).toBe(old_item, '5. item === old_item');
expect(parentVm.items).toBe(null, '5. items === null');
} else {
// "slotted" content wont be removed when the view is detached
assertSelectorCount(parentEl, 'p > .item', 0);
expect(parentVm.item).not.toBe(null);
expect(parentVm.items).not.toBe(null);
expect(parentVm.items.length).toBe(/* 2 orphaned */2);
}
expect(parentVm.item_changed_call_count).toBe(5, 'item changed() -- 5');
expect(parentVm.items_changed_call_count).toBe(shouldUseShadowDom ? 4 : 3, 'items changed() -- 5');
// ---- assert [removal] while [attached] mutation -----
// 6. showParent = true
rootVm.showParent = true;
await waitForTicks(2);
if (shouldUseShadowDom) {
assertSelectorCount(parentEl, '.item', 2);
expect(parentVm.item).not.toBe(null, '6. item !== null');
expect(parentVm.item).not.toBe(old_item, '6. item !== old_item');
expect(parentVm.items).not.toBe(null, '6. items !== old_items');
} else {
assertSelectorCount(parentEl, 'p > .item', 2);
expect(parentVm.item).not.toBe(null);
expect(parentVm.items).not.toBe(null);
expect(parentVm.items.length).toBe(/* 2 orphaned + 2 from repeat */4);
}
expect(parentVm.item_changed_call_count).toBe(7, 'item changed() -- 6');
// when using shadowDOM
// 1 call for bind()
// 1 call for actual mutation change from repeat
// so +2 more calls in total
expect(parentVm.items_changed_call_count).toBe(shouldUseShadowDom ? 6 : 4, 'items changed() -- 6');
// 7. itemCount = 0
rootVm.itemCount = 0;
await waitForTicks(2);
assertSelectorCount(parentEl, '.item', 0);
if (shouldUseShadowDom) {
expect(parentVm.item).toBe(null, '7. item === null');
expect(parentVm.items).toEqual([], '7. items === null');
} else {
// shadow dom emulation doesn't response to mutation while detached
expect(parentVm.item).toBe(null);
expect(parentVm.items).not.toBe(null);
expect(parentVm.items.length).toBe(/* 2 orphaned */2);
}
expect(parentVm.item_changed_call_count).toBe(8, 'item changed() -- 7');
expect(parentVm.items_changed_call_count).toBe(shouldUseShadowDom ? 7 : 5, 'items changed() -- 7');
// ---- final ----
// 9. dispose
dispose();
expect(observer.binders.length).toBe(0);
expect(parentEl.__childObserver__).toBe(null);
if (shouldUseShadowDom) {
expect(parentVm.item).toBe(null);
expect(parentVm.items).toBe(null);
} else {
expect(parentVm.item).toBe(null);
expect(parentVm.items.length).toBe(/* 2 orphaned */2);
}
});
});
}
async function createFixture<T>(root: Constructable<T>, resources: any[] = []) {
const aurelia = new Aurelia();
let $$taskQueue: TaskQueue = createFixture.taskQueue;
if ($$taskQueue) {
aurelia.container.registerInstance(TaskQueue, $$taskQueue);
} else {
$$taskQueue = createFixture.taskQueue = aurelia.container.get(TaskQueue);
}
aurelia
.use
.defaultBindingLanguage()
.defaultResources()
.globalResources(resources)
const host = document.createElement('div');
await aurelia.start();
await aurelia.setRoot(root, host);
const rootController = aurelia['root'] as Controller;
return {
aurelia,
host,
root: rootController,
rootVm: rootController.viewModel as T,
taskQueue: $$taskQueue,
dispose: () => {
$$taskQueue.flushMicroTaskQueue();
$$taskQueue.flushTaskQueue();
rootController.detached();
rootController.unbind();
$$taskQueue.flushMicroTaskQueue();
}
}
}
createFixture.taskQueue = null;
function assertIsMutationObserverHost(element: Element): element is IMutationObserverHost {
const observer = element['__childObserver__'];
expect(observer instanceof MutationObserver).toBe(true, 'there should be mutation observer on element');
return true;
}
function assertSelectorCount(element: Element, selector: string, count: number): void {
let childCount = element.querySelectorAll(selector).length;
expect(childCount).toBe(count, `Expected selecotr: "${selector}" count for <${element.tagName.toLowerCase()}/> to be ${count}, found ${childCount}`);
}
async function waitForTicks(count = 0) {
while (count > 0) {
await Promise.resolve();
count--;
}
}
interface Constructable<T> {
new(...args: any[]): T;
}
}); | the_stack |
import {
ChangeEvent,
DragEvent,
useCallback,
useEffect,
useReducer,
} from "react";
import { nanoid } from "nanoid";
import { omit } from "@react-md/utils";
import {
CompletedFileUploadStats,
getFileParser as defaultGetFileParser,
FileAccessError,
FileReaderResult,
FileUploadHandlers,
FileUploadStats,
FileValidationError,
FilesValidator,
GetFileParser,
ProcessingFileUploadStats,
isValidFileName as defaultIsValidFileName,
validateFiles as defaultValidateFiles,
FileValidationOptions,
} from "./utils";
/**
*
* @typeParam CustomError - An optional error type that gets returned from the
* {@link FilesValidator}.
* @remarks \@since 2.9.0
*/
export interface FileUploadState<CustomError = never> {
/**
* All the files that have been validated and are either:
* - pending upload
* - uploading
* - complete
*
* Each key in this object is the {@link BaseFileUploadStats.key} generated
* once the upload starts pending.
*/
stats: Readonly<Record<string, Readonly<FileUploadStats>>>;
/**
* A list of validation errors that have occurred before starting the upload
* process.
*
* @see {@link FileAccessError}
* @see {@link TooManyFilesError}
* @see {@link FileValidationError}
*/
errors: readonly FileValidationError<CustomError>[];
}
/**
*
* @typeParam CustomError - An optional error type that gets returned from the
* {@link FilesValidator}.
* @remarks \@since 2.9.0
* @internal
*/
export interface FileUploadHookState<CustomError = never>
extends FileUploadState<CustomError> {
/**
* All the current readers used for uploading files to the browser.
*
* Note: Once an upload has completed, the reader will be removed.
*/
readers: Readonly<Record<string, FileReader>>;
}
/**
*
* @typeParam E - An optional HTMLElement type that is used for the
* {@link FileUploadHandlers}.
* @typeParam CustomError - An optional error type that gets returned from the
* {@link FilesValidator}.
* @remarks \@since 2.9.0
*/
export interface FileUploadOptions<E extends HTMLElement, CustomError = never>
extends FileUploadHandlers<E>,
FileValidationOptions {
/**
* Setting this value to a number greater than `0` will update the browser
* upload process to queue the uploads in chunks instead of all at once. This
* can help prevent the browser from freezing if dealing with large files that
* are being converted to data urls.
*
* @defaultValue `-1`
*/
concurrency?: number;
/** {@inheritDoc FilesValidator} */
validateFiles?: FilesValidator<CustomError>;
/** {@inheritDoc GetFileParser} */
getFileParser?: GetFileParser;
}
/** @internal */
type Action<E = never> =
| {
type: "queue";
errors: readonly FileValidationError<E>[];
files: readonly File[];
}
| { type: "reset" }
| { type: "remove"; files: readonly string[] }
| { type: "start"; key: string; reader: FileReader }
| { type: "progress"; key: string; progress: number }
| { type: "complete"; key: string; result: FileReaderResult }
| { type: "clearErrors" };
/** @remarks \@since 2.9.0 */
export interface FileUploadActions {
/**
* Reset everything related to uploads ensuring that all file readers have
* been aborted.
*/
reset(): void;
/**
* Removes all the errors that exist in state without cancelling any of the
* uploads already in progress.
*/
clearErrors(): void;
/**
* This function is used to cancel pending and uploading files or removing
* completed files.
*
* @param keyOrKeys - A single or list of {@link BaseFileUploadStats.key} to
* remove from state.
*/
remove(keyOrKeys: string | readonly string[]): void;
}
/**
*
* @typeParam E - An optional HTMLElement type that is used for the
* {@link FileUploadHandlers}.
* @typeParam CustomError - An optional error type that gets returned from the
* {@link FilesValidator}.
* @remarks \@since 2.9.0
*/
export interface FileUploadHookReturnValue<
E extends HTMLElement = HTMLElement,
CustomError = never
> extends FileUploadActions,
Required<FileUploadHandlers<E>> {
/** {@inheritDoc FileUploadState.errors} */
errors: readonly FileValidationError<CustomError>[];
/**
* A list of all the {@link FileUploadStats}.
*
* @see {@link getSplitFileUploads} for separating by status
*/
stats: readonly Readonly<FileUploadStats>[];
/**
* The total number of bytes for all the files that exist in the
* {@link stats} list.
*/
totalBytes: number;
/**
* The total number of files in the {@link stats} list.
*/
totalFiles: number;
/**
* An `accept` string that can be passed to the {@link FileInput} component
* when the {@link FileValidationOptions.extensions} list has been provided to
* limit which files the OS will _attempt_ to allow access to.
*
* @example
* Simple example
* ```ts
* const extensions = ['pdf', 'docx', 'ppt'];
* const { accept } = useFileUpload({ extensions, ...others });
*
* expect(accept).toBe("*.pdf,*.docx,*.ppt")
* ```
*
* @defaultValue `"*"`
*/
accept: string;
}
/** @internal */
const EMPTY_LIST = [] as const;
/** @internal */
const EMPTY_OBJECT = {} as const;
/**
* This hook is generally used to upload files **to the browser** in different
* formats to be previewed `<img>`, `<video>`, `<embed>`, etc tags. However, it
* can also be used to upload the files as an `ArrayBuffer` and then uploaded to
* a server.
*
* Note: If using the `aws-sdk` to upload files directly to S3, **do not use
* this hook** since it uses its own upload process.
*
* @typeParam E - An optional HTMLElement type that is used for the
* {@link FileUploadHandlers}.
* @typeParam CustomError - An optional error type that gets returned from the
* {@link FilesValidator}.
* @param options - All the {@link FileUploadOptions}
* @returns the {@link FileUploadHookReturnValue}
* @remarks \@since 2.9.0
*/
export function useFileUpload<E extends HTMLElement, CustomError = never>({
maxFiles = -1,
extensions = EMPTY_LIST,
minFileSize = -1,
maxFileSize = -1,
totalFileSize = -1,
concurrency = -1,
onDrop: propOnDrop,
onChange: propOnChange,
validateFiles = defaultValidateFiles,
getFileParser = defaultGetFileParser,
isValidFileName = defaultIsValidFileName,
}: FileUploadOptions<E, CustomError> = {}): Readonly<
FileUploadHookReturnValue<E, CustomError>
> {
const [state, dispatch] = useReducer(
function reducer(
state: FileUploadHookState<CustomError>,
action: Action<CustomError>
) {
switch (action.type) {
case "reset":
// need to reuse constants so that calling reset doesn't cause an
// infinite loop in an effect
return {
stats: EMPTY_OBJECT,
errors: EMPTY_LIST,
readers: EMPTY_OBJECT,
};
case "remove":
return {
...state,
stats: omit(state.stats, action.files),
};
case "queue":
return {
...state,
stats: {
...state.stats,
...action.files.reduce<Record<string, ProcessingFileUploadStats>>(
(files, file) => {
const key = nanoid();
files[key] = {
key,
file,
progress: 0,
status: "pending",
};
return files;
},
{}
),
},
errors: [...state.errors, ...action.errors],
};
case "start": {
const { key, reader } = action;
/* istanbul ignore next */
if (!state.stats[key]) {
throw new Error(`Missing file with key "${key}"`);
}
const fileStats: ProcessingFileUploadStats = {
key,
file: state.stats[key].file,
progress: 0,
status: "uploading",
};
return {
...state,
readers: {
...state.readers,
[key]: reader,
},
stats: {
...state.stats,
[key]: fileStats,
},
};
}
case "progress": {
const { key, progress } = action;
/* istanbul ignore next */
if (!state.stats[key]) {
throw new Error(`Missing file with key "${key}"`);
}
return {
...state,
stats: {
...state.stats,
[key]: {
...state.stats[key],
progress,
},
},
};
}
case "complete": {
const { key, result } = action;
/* istanbul ignore next */
if (!state.stats[key]) {
throw new Error(`Missing file with key "${key}"`);
}
const file: CompletedFileUploadStats = {
key,
file: state.stats[key].file,
status: "complete",
result,
progress: 100,
};
const { [key]: _reader, ...readers } = state.readers;
return {
...state,
readers,
stats: {
...state.stats,
[key]: file,
},
};
}
case "clearErrors":
return { ...state, errors: [] };
default:
/* istanbul ignore next */
return state;
}
},
{
stats: EMPTY_OBJECT,
errors: EMPTY_LIST,
readers: EMPTY_OBJECT,
}
);
const { stats, errors, readers } = state;
const statsList = Object.values(stats);
const totalFiles = statsList.length;
const totalBytes = statsList.reduce(
(result, { file: { size } }) => result + size,
0
);
const queueFiles = useCallback(
(files: readonly File[]) => {
const { pending, errors } = validateFiles(files, {
maxFiles,
extensions,
minFileSize,
maxFileSize,
totalBytes,
totalFiles,
totalFileSize,
isValidFileName,
});
dispatch({ type: "queue", errors, files: pending });
},
[
validateFiles,
maxFiles,
extensions,
minFileSize,
maxFileSize,
totalBytes,
totalFiles,
totalFileSize,
isValidFileName,
]
);
const onDrop = useCallback(
(event: DragEvent<E>) => {
propOnDrop?.(event);
event.preventDefault();
event.stopPropagation();
try {
const files = event.dataTransfer.files;
if (files) {
queueFiles(Array.from(files));
}
} catch (e) {
dispatch({
type: "queue",
files: [],
errors: [
new FileAccessError(e instanceof Error ? e.message : undefined),
],
});
}
},
[queueFiles, propOnDrop]
);
const onChange = useCallback(
(event: ChangeEvent<HTMLInputElement>) => {
propOnChange?.(event);
try {
const files = event.currentTarget.files;
if (files) {
queueFiles(Array.from(files));
} else {
throw new Error();
}
} catch (e) {
dispatch({
type: "queue",
files: [],
errors: [
new FileAccessError(e instanceof Error ? e.message : undefined),
],
});
}
},
[queueFiles, propOnChange]
);
const remove = useCallback(
(keyOrKeys: string | readonly string[]) => {
const files = typeof keyOrKeys === "string" ? [keyOrKeys] : keyOrKeys;
files.forEach((fileKey) => {
readers[fileKey]?.abort();
});
dispatch({ type: "remove", files });
},
[readers]
);
const reset = useCallback(() => {
Object.values(readers).forEach((reader) => {
reader.abort();
});
dispatch({ type: "reset" });
}, [readers]);
const clearErrors = useCallback(() => {
dispatch({ type: "clearErrors" });
}, []);
const start = useCallback((key: string, reader: FileReader) => {
dispatch({ type: "start", key, reader });
}, []);
const complete = useCallback(
(key: string, result: FileReaderResult = null) => {
dispatch({ type: "complete", key, result });
},
[]
);
const createProgressEventHandler = useCallback(
(key: string) => (event: ProgressEvent) => {
if (event.lengthComputable) {
const percentage = Math.round((event.loaded * 100) / event.total);
dispatch({ type: "progress", key, progress: percentage });
}
},
[]
);
useEffect(() => {
const pending: ProcessingFileUploadStats[] = [];
const uploading: ProcessingFileUploadStats[] = [];
Object.values(stats).forEach((file) => {
if (file.status === "pending") {
pending.push(file);
} else if (file.status === "uploading") {
uploading.push(file);
}
});
const lastIndex =
concurrency === -1
? pending.length
: Math.max(0, concurrency - uploading.length);
const queue = pending.slice(0, lastIndex);
if (!queue.length) {
return;
}
queue.forEach((stats) => {
const { key, file } = stats;
const reader = new FileReader();
// using `addEventListener` instead of directly setting to
// `reader.progress`/`reader.load` so it's easier to test
reader.addEventListener("progress", createProgressEventHandler(key));
reader.addEventListener("load", () => {
complete(key, reader.result);
});
start(key, reader);
const parser = getFileParser(file);
/* istanbul ignore next */
if (
process.env.NODE_ENV !== "production" &&
![
"readAsText",
"readAsDataURL",
"readAsArrayBuffer",
"readAsBinaryString",
].includes(parser)
) {
throw new Error("Invalid file reader parser");
}
reader[parser](file);
});
}, [
concurrency,
stats,
getFileParser,
createProgressEventHandler,
start,
complete,
]);
let accept = "";
if (extensions.length) {
accept = extensions.reduce((s, ext) => `${s ? `${s},` : ""}.${ext}`, "");
}
return {
stats: statsList,
errors,
accept,
totalBytes,
totalFiles,
onDrop,
onChange,
reset,
remove,
clearErrors,
};
} | the_stack |
import { Component, ViewEncapsulation, OnInit } from '@angular/core';
import { LogService, Logger } from './service/log/log.service';
import * as MidiConvert from "midiconvert";
import { IHeader, ITrack, INote } from "./service/mtosState/mtosState.module";
import { ContextMenuService } from "./ui/contextMenu/contextMenu.module";
import { DialogService, IDialogSelect } from "./ui/dialog/dialog.module";
import { ISubMenuComponentOptions } from "./ui/subMenu/subMenu.module";
import * as JSZip from "jszip";
export interface IScaleType{
name: string,
start: number,
offsets: number[]
};
@Component({
selector: 'app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
logger: Logger;
//track: ITrack = { notes: [] };
projectName: string;
header: IHeader;
notes: INote[];
ghostNote: INote = null;
removingNote: boolean = false;
/*
C |C# |D |D# |E |F |F# |G |G# |A |A# |B
24 |25 |26 |27 |28 |29 |30 |31 |32 |33 |34 |35
A Minor
33: [2,1,2,2,1,2,2]
*/
scaleTypeOptionsA = ['Custom']; //['Full', 'Minor', 'Custom'];
scaleTypeOptions: IScaleType[] = [{
name: 'C Major',
start: 24,
offsets: [2, 2, 1, 2, 2, 2, 1]
},{
name: 'G Major',
start: 31,
offsets: [2, 2, 1, 2, 2, 2, 1]
},{
name: 'D Major',
start: 26,
offsets: [2, 2, 1, 2, 2, 2, 1]
},{
name: 'A Major',
start: 33,
offsets: [2, 2, 1, 2, 2, 2, 1]
},{
name: 'E Major',
start: 28,
offsets: [2, 2, 1, 2, 2, 2, 1]
},{
name: 'B Major',
start: 35,
offsets: [2, 2, 1, 2, 2, 2, 1]
},{
name: 'A Minor',
start: 33,
offsets: [2, 1, 2, 2, 1, 2, 2]
},{
name: 'E Minor',
start: 28,
offsets: [2, 1, 2, 2, 1, 2, 2]
},{
name: 'B Minor',
start: 35,
offsets: [2, 1, 2, 2, 1, 2, 2]
},{
name: 'F# Minor',
start: 30,
offsets: [2, 1, 2, 2, 1, 2, 2]
},{
name: 'C# Minor',
start: 25,
offsets: [2, 1, 2, 2, 1, 2, 2]
},{
name: 'G# Minor',
start: 32,
offsets: [2, 1, 2, 2, 1, 2, 2]
},{
name: 'Full',
start: 24,
offsets: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
}];
selectedScaleType: IScaleType = this.scaleTypeOptions[0];
noteScale: number[] = [];
octaveOptions: number[] = [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7];
octave: number;
noteTypes = ['Circle', 'Rectangle', 'Long Notes']
selectedNoteType: any = this.noteTypes[0];
numNotes: number = 20;
noteDistance: number = 3;
noteHeight: number = 3;
noteWidth: number = 3;
trackStart: number = 50;
trackShift: number = 50;
trackPadding: number = 6.35;
trackParts: number[];
trackPartLength: number = 200;
trackLength: number = 200;
noteTable = {};
mainMenuOptions: ISubMenuComponentOptions;
constructor(private contextMenuService: ContextMenuService, private dialogService: DialogService) {
window['state'] = this; //Debug only;
this.mainMenuOptions = {
onInit: () => { },
disableBackground: true,
disableText: false,
iconSize: 'big',
buttons: [{
text: 'Help',
iconClass: 'int-icon-info-circle',
callback: () => {
this.dialogService.openMessage('Help',
`This application is under development.
Expect bugs and incomplete features.
Getting started:
Import one or more midi files.
Select scale and octave.
Invalid notes are marked in red.
Hover over them for more details.
Click on the channel to change it (left side).
Or right click on note to delete it.
`);
}
}]
};
this.initNoteTable();
this.init();
}
init() {
this.setState(null);
}
initNoteTable() {
var noteLetter = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
for (let i = 0; i < 128; i++) {
var octave = Math.floor(i / 12) - 2;
var note = noteLetter[i % 12];
this.noteTable[i] = octave + note;
}
}
getState() {
var state = {
projectName: this.projectName,
header: this.header,
notes: this.notes,
numNotes: this.numNotes,
octave: this.octave,
selectedScaleType: this.selectedScaleType.name,
noteScale: this.noteScale,
selectedNoteType: this.selectedNoteType,
noteDistance: this.noteDistance,
noteHeight: this.noteHeight,
noteWidth: this.noteWidth,
trackStart: this.trackStart,
trackShift: this.trackShift,
trackPadding: this.trackPadding,
trackPartLength: this.trackPartLength,
trackLength: this.trackLength
}
return state;
}
setState(state) {
if (state === null || state === undefined) {//if no state -> setDefaults
state = {};
}else{
console.log('Set state', state);
}
this.projectName = state.projectName || 'New Project';
this.header = state.header || {};
this.notes = state.notes || [];
this.numNotes = state.numNotes || 20;
this.octave = state.octave || 0;
this.selectedScaleType =this.getScaleType(state.selectedScaleType) || this.getScaleType(null);
this.noteScale = state.noteScale || this.generateNoteScale();
this.selectedNoteType = state.selectedNoteType || 'Circle';
this.noteDistance = state.noteDistance || 3;
this.noteHeight = state.noteHeight || 3;
this.noteWidth = state.noteWidth || 3;
this.trackStart = state.trackStart || 50;
this.trackShift = state.trackShift || 50;
this.trackPadding = state.trackPadding || 6.35;
this.trackPartLength = state.trackPartLength || 200;
this.trackLength = state.trackLength || 200;
this.updateNotes();
}
generateNoteScale(): number[] {
var result: number[] = [];
var offsetIndex = -1;
for (let i = 0; result.length < this.numNotes; i++) {
var midi;
if(offsetIndex == -1){
midi = this.selectedScaleType.start + this.octave * 12;
}else{
midi = result[i - 1] + this.selectedScaleType.offsets[offsetIndex];
}
offsetIndex += 1;
if(offsetIndex >= this.selectedScaleType.offsets.length){
offsetIndex = 0;
}
result.push(midi);
}
return result;
}
getScaleType(name: string): IScaleType{
if(name === null || name == undefined){
return this.scaleTypeOptions[0];
}
for(let i = 0; i < this.scaleTypeOptions.length; i++){
var st = this.scaleTypeOptions[i];
if(st.name == name){
return st;
}
}
return this.scaleTypeOptions[0];
}
isFirstNoteOnScale(midi: number): boolean{
var scaleStart = this.selectedScaleType.start;
if(midi % 12 === scaleStart % 12){
return true;
}
return false;
}
importNotes(newNotes: INote[]) {
for (let i = 0; i < newNotes.length; i++) {
this.notes.push(newNotes[i]);
}
this.sortNotes();
var lastNote = this.notes[this.notes.length - 1];
this.trackLength = lastNote.time * 16 + lastNote.duration * 16;
}
sortNotes() {
this.notes.sort(function (a, b) {
var aValue = a.time;
var bValue = b.time;
if (aValue < bValue) {
return -1;
}
if (aValue > bValue) {
return 1;
}
return 0;
});
}
updateNotes() {
var numTrackParts = this.getNumTrackParts();
this.trackParts = []; //Angular 2 ng-for trick.
for (let i = 0; i < numTrackParts; i++) {
this.trackParts.push(i);
}
}
parseFile(file) {
var reader = new FileReader();
reader.onload = (event: any) => {
var data = <any>MidiConvert.parse(event.target.result);
if (!data || !data.tracks || data.tracks.length === 0) {
return;
}
if (data.tracks.length > 1) {
var options = [];
for (let i = 0; i < data.tracks.length; i++) {
var t = data.tracks[i];
options.push({
key: i,
value: t.name
});
}
var select: IDialogSelect = {
text: 'Select track',
selected: options[0].key,
options: options
}
this.dialogService.openSelect('Multiple tracks in midi file', null, select, () => {
this.importNotes(data.tracks[select.selected].notes);
this.updateNotes();
});
} else {
this.importNotes(data.tracks[0].notes);
this.updateNotes();
}
};
reader.readAsBinaryString(file);
}
onChangeImportMidi(event: any) {
var files = event.target.files;
if (files.length > 0) {
var file = files[0];
this.parseFile(file);
}
}
onClickLoadProject() {
var element = <HTMLInputElement>document.getElementById('file-input');
element.accept = 'application/json';
element.value = null;
element.onchange = (event: any) => {
if(!event){
return;
}
var reader = new FileReader();
reader.onload = (event: any) => {
this.setState(JSON.parse(event.target.result));
};
reader.readAsText(event.path[0].files[0]);
};
element.click();
}
onClickSaveProject() {
var state = this.getState();
var stateAsJson = JSON.stringify(state);
var filename = this.projectName + '.json';
var blob = new Blob([stateAsJson], { type: 'application/json' });
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
} else {
var elem = <HTMLAnchorElement>document.getElementById('file-output');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
elem.click();
}
}
onChangeNumNotes(newValue) {
this.numNotes = newValue;
this.noteScale = this.generateNoteScale();
this.updateNotes();
}
onChangeScaleType(newValue) {
this.selectedScaleType = newValue;
this.noteScale = this.generateNoteScale();
this.updateNotes();
}
onChangeScaleOctave(newValue){
this.octave = newValue;
this.noteScale = this.generateNoteScale();
this.updateNotes();
}
onChangeNoteDistance(newValue) {
this.noteDistance = newValue;
this.updateNotes();
}
onChangeNoteHeight(newValue) {
this.noteHeight = newValue;
this.updateNotes();
}
onChangeNoteWidth(newValue) {
this.noteWidth = newValue;
this.updateNotes();
}
disableNoteWidth():boolean{
return this.isLongNoteType();
}
onChangeTrackLength(newValue) {
this.trackLength = newValue;
this.updateNotes();
}
onChangeTrackPartLength(newValue) {
this.trackPartLength = newValue;
this.updateNotes();
}
onChangeTrackPadding(newValue) {
this.trackPadding = newValue;
this.updateNotes();
}
onClickImportMidi() {
var element = <HTMLInputElement>document.getElementById('file-input');
element.accept = 'audio/midi';
element.value = null;
element.onchange = (event) => {
if(!event){
return;
}
this.onChangeImportMidi(event);
}
element.click();
}
onClickDownload() {
var svgString = this.generateSvg();
var filename = this.projectName + '.zip';
var useDownloadAsZip = true;
if (useDownloadAsZip) {
var svgStringArray = this.splitSvg(svgString);
var zip = new JSZip();
for (let i = 0; i < svgStringArray.length; i++) {
zip.file(this.projectName + i + '.svg', svgStringArray[i]);
}
zip.generateAsync({ type: "blob", compression: 'DEFLATE'})
.then(function (content) {
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(content, filename);
}
else {
var element = <HTMLAnchorElement>document.getElementById('file-output');
element.href = window.URL.createObjectURL(content);
element.download = filename;
element.click();
}
});
} else {
var blob = new Blob([svgString], { type: 'image/svg+xml' });
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
}
else {
var elem = <HTMLAnchorElement>document.getElementById('file-output');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
elem.click();
}
}
}
//Ghost note
showGhostNote(): boolean{
if(this.ghostNote != null){
return true;
}
return false;
}
onMouseEnterSvg(event: MouseEvent){
this.createGhostNote();
event.preventDefault();
}
onMouseLeaveSvg(event: MouseEvent){
this.ghostNote = null;
event.preventDefault();
}
onMouseDownNote(note: INote){
this.removingNote = true;
let i = this.notes.indexOf(note);
this.notes.splice(i, 1);
event.preventDefault();
}
onMouseUpSvg(event: MouseEvent){
if (!this.removingNote) {
this.notes.push(this.ghostNote);
this.sortNotes();
this.createGhostNote();
} else {
this.removingNote = false;
}
event.preventDefault();
}
onMouseOverSvg(event: MouseEvent){
var loc = this.getCursorInSvg(event);
var x = loc.x;
var y = loc.y - this.trackPadding;
//clamp
if(x < 0){
x = 0;
}
if(y < 0){
y = 0;
}
var test = this.noteDistance * (this.noteScale.length - 1);
if(y > test){
y = test;
}
//get data
var noteScaleIndex = (this.noteScale.length - 1) - Math.round(y / this.noteDistance);
var time = x / 16;
this.updateGhostNote(noteScaleIndex, time);
//console.log(`Position: { x: ${x}, y:${y} midi: ${noteScaleIndex}}`);
event.preventDefault();
}
getCursorInSvg(evt) {
var svg:SVGSVGElement = <any>document.getElementById("musicbox-svg");//slow
var pt=svg.createSVGPoint();
pt.x=evt.clientX;
pt.y=evt.clientY;
return pt.matrixTransform(svg.getScreenCTM().inverse());
}
createGhostNote(){
if(this.ghostNote != null){
var g: INote = {
name: this.ghostNote.name.toString(),
midi: this.ghostNote.midi,
time: this.ghostNote.time,
velocity: this.ghostNote.velocity,
duration: this.ghostNote.duration
};
this.ghostNote = g;
}else{
this.ghostNote = {
name: this.midiToNote(0),
midi: 0,
time: 0,
velocity: 0.5,
duration: 0.25
}
}
}
updateGhostNote(noteScaleIndex: number, time: number){
this.ghostNote.midi = this.noteScale[noteScaleIndex];
this.ghostNote.name = this.midiToNote(this.ghostNote.midi);
this.ghostNote.time = time;
}
generateSvg(): string {
var svg = document.getElementById('musicbox-svg');
var clone = svg.cloneNode(true);
//remove guidelines
var element = this.getChildById('defs', <Element>clone);
clone.removeChild(element);
element = this.getChildById('note-lines-group', <Element>clone);
clone.removeChild(element);
element = this.getChildById('note-guide-group', <Element>clone);
clone.removeChild(element);
element = this.getChildById('track-part-divider', <Element>clone);
clone.removeChild(element);
element = this.getChildById('ghost-note', <Element>clone);
if(element != null){
clone.removeChild(element);
}
var s = (<HTMLElement>clone).outerHTML.toString();
//remove binding code
s = s.replace(/<!--((.|\n)*?)-->/g, '');
s = s.replace(/(_ngcontent(?:.*?)"")/g, '');
s = s.replace(/(ng-reflect(?:.*?)".*?")/g, '');
return s;
}
splitSvg(svgAsString: string): string[] {
var element = this.stringToElement(svgAsString);
var numParts = this.getChildById('parts', element).children.length;
var partsAsStringArray = [];
for (let i = 0; i < numParts; i++) {
var clone = <HTMLElement>element.cloneNode(true);
var partGroup = this.getChildById('parts', clone);
var idGroup = this.getChildById('track-part-id', clone);
var noteGroup = this.getChildById('notes', clone);
var part = <SVGPathElement>partGroup.children[i];
var id = <SVGTextElement>idGroup.children[i];
var partBBox = this.getPathBBox(part);
//width="2320mm" height="89.7mm" viewBox="-60 -10 2320 89.7"
clone.setAttribute('width', (partBBox.width + 5) + 'mm');
clone.setAttribute('height', (partBBox.height + 5) + 'mm');
clone.setAttribute('viewBox', (partBBox.x - 5) + ' ' + (partBBox.y - 5) + ' ' + (partBBox.width + 10) + ' ' + (partBBox.height + 10));
for (let j = 0; j < noteGroup.children.length; j++) {
var note = <SVGEllipseElement | SVGRectElement>noteGroup.children[j];
var noteBBox;
if(note.tagName === 'ellipse'){
noteBBox = this.getEllipseBBox(<SVGEllipseElement>note);
}else{
noteBBox = this.getRectBBox(<SVGRectElement>note);
}
if (!this.isIntersecting(partBBox, noteBBox)) {
noteGroup.removeChild(note);
j--;
}
}
while (partGroup.firstChild) {
partGroup.removeChild(partGroup.firstChild);
}
partGroup.appendChild(part);
while (idGroup.firstChild) {
idGroup.removeChild(idGroup.firstChild);
}
idGroup.appendChild(id);
partsAsStringArray.push(clone.outerHTML.toString());
}
return partsAsStringArray;
}
getEllipseBBox(a: SVGEllipseElement): SVGRect {
var cx = parseFloat(a.getAttribute('cx'));
var cy = parseFloat(a.getAttribute('cy'));
var rx = parseFloat(a.getAttribute('rx'));
var ry = parseFloat(a.getAttribute('ry'));
return <SVGRect>{
x: cx - rx,
y: cy - ry,
width: rx + rx,
height: ry + ry
};
}
getRectBBox(a: SVGRectElement): SVGRect {
var x = parseFloat(a.getAttribute('x'));
var y = parseFloat(a.getAttribute('y'));
var width = parseFloat(a.getAttribute('width'));
var height = parseFloat(a.getAttribute('height'));
return <SVGRect>{
x: x,
y: y,
width: width,
height: height
};
}
getPathBBox(a: SVGPathElement): SVGRect {
const regex = /([+-]?(?:[0-9]*\.)?[0-9]+),([+-]?(?:[0-9]*\.)?[0-9]+)/g;
var d = a.getAttribute('d');
var match;
var minX, maxX, minY, maxY;
while ((match = regex.exec(d)) !== null) {
var x = parseFloat(match[1]);
var y = parseFloat(match[2]);
if(minX === undefined){
minX = x;
maxX = x;
minY = y;
maxY = y;
continue;
}
if(x < minX){
minX = x;
}
if(x > maxX){
maxX = x;
}
if(y < minY){
minY = y;
}
if(y > maxY){
maxY = y;
}
}
return {
x: minX,
y: minY,
width: maxX - minX,
height: maxY - minY
};
}
isIntersecting(a: SVGRect, b: SVGRect): boolean {
if (b.x > a.x + a.width || b.x + b.width < a.x ||
b.y > a.y + a.height || b.y + b.height < a.y) {
return false;
}
return true;
}
stringToElement(htmlAsString: string): HTMLElement {
var div = document.createElement('div');
div.innerHTML = htmlAsString;
return <HTMLElement>div.firstChild;
}
getChildById(id: string, element: Element): Element {
if (!element || !element.children) {
return null;
}
for (let i = 0; i < element.children.length; i++) {
let n = element.children[i];
if (!n) {
continue;
}
if (n.id === id) {
return n;
}
}
return null;
}
midiToNote(n: number) {
return this.noteTable[n];
}
isCircleNoteType(): boolean {
if (this.selectedNoteType === this.noteTypes[0]) {
return true;
}
return false;
}
isLongNoteType(): boolean{
if (this.selectedNoteType === this.noteTypes[2]) {
return true;
}
return false;
}
getPaperHeight(): number {
return this.trackPadding * 2 + (this.noteScale.length - 1) * this.noteDistance;
}
getTrackHeight(): number {
return (this.numNotes - 1) * this.noteDistance;
}
getNumTrackParts(): number {
if (this.trackLength <= 0) {
return 1;
}
return Math.ceil(this.trackLength / this.trackPartLength);
}
showTrack(): boolean {
if (!this.notes) {
return false;
}
return true;
}
//Scale
getScaleWidth() {
return '10mm';
}
getScaleHeight() {
return this.getPaperHeight() + 20 + 'mm';
}
getScaleViewBox() {
return '0 -10 ' + 10 + ' ' + (this.getPaperHeight() + 20);
}
onClickScale(event: MouseEvent, index: number) {
var options = {
x: event.clientX,
y: event.clientY,
menu: this.generateContextMenu(index)
}
this.contextMenuService.openContextMenu(options);
event.preventDefault();
}
generateContextMenu(index: number) {
var menu = [];
var test = index.toString();
for (let n in this.noteTable) {
var option: any = {
text: this.noteTable[n],
callback: () => {
var i = this.noteScale.indexOf(index);
if (i != -1) {
this.noteScale[i] = ~~n;
}
}
}
if (n == test) {
option.icon = 'int-icon-approve';
}
menu.push(option);
}
return menu;
}
onMouseDownScale() {
this.contextMenuService.closeContextMenu();
}
//ViewBox
getViewBoxWidth() {
var trackLength = this.getNumTrackParts() * this.trackPartLength;
return trackLength + this.trackStart + this.trackShift + 20 + 'mm';
}
getViewBoxHeight() {
return this.getPaperHeight() + 20 + 'mm';
}
getTrackViewBox() {
var trackLength = this.getNumTrackParts() * this.trackPartLength;
return (-this.trackStart - 10) + ' -10 ' + (trackLength + this.trackStart + this.trackShift + 20) + ' ' + (this.getPaperHeight() + 20);
}
//Text
getTextY(midi: number): number {
return this.getPaperHeight() - this.trackPadding - (this.getNoteYOffset(midi) * this.noteDistance) + 1;
}
//Note Lines
getNoteLineY(midi: number): number {
return this.getPaperHeight() - this.trackPadding - (this.getNoteYOffset(midi) * this.noteDistance);
}
getNoteLineLength(): number {
return this.trackLength;
}
getNoteLineColor(midi: number) {
if (this.isFirstNoteOnScale(midi)) {
return '#2f61ba';
}
return '#93CCEA';
}
//NoteGuide
getNoteGuideX():number{
return 0;
}
getNoteGuideY():number{
return this.trackPadding;
}
getNoteGuideWidth():number{
return this.trackLength;
}
getNoteGuideHeight():number{
return this.getTrackHeight();
}
//Notes
getNoteX(note: INote): number {
if (this.isCircleNoteType()) {
return note.time * 16;
}else if(this.isLongNoteType()){
return note.time * 16;
}
return note.time * 16 - (this.noteWidth / 2);
}
getNoteY(note: INote): number {
if (this.isCircleNoteType()) {
return this.getPaperHeight() - this.trackPadding - (this.getNoteYOffset(note.midi) * this.noteDistance);
}
return this.getPaperHeight() - this.trackPadding - (this.getNoteYOffset(note.midi) * this.noteDistance) - (this.noteHeight / 2);
}
getNoteYOffset(midi: number) {
var index = this.noteScale.indexOf(midi);
return index;
}
getNoteWidth(note: INote): number {
if (this.isCircleNoteType()) {
return this.noteWidth / 2;
}else if(this.isLongNoteType()){
return note.duration * 16;
}
return this.noteWidth;
}
getNoteHeight(): number {
if (this.isCircleNoteType()) {
return this.noteHeight / 2;
}
return this.noteHeight;
}
getNoteFillColor(note: INote): string {
if (this.getNoteYOffset(note.midi) === -1) {
return '#d73c3c';
}
return '#fff';
}
onClickContextMenu(event: MouseEvent, note) {
var index = this.notes.indexOf(note);
if (index != -1) {
this.notes.splice(index, 1);
}
event.preventDefault();
}
getHint(note: INote): string {
return this.noteTable[note.midi];
}
//Paper
getLineAX1(n: number): number {
return this.trackPartLength * n;
}
getLineAX2(n: number): number {
return this.trackPartLength * (n + 1);
}
getLineAY(n: number): number {
return 0;
}
getLineBY(n: number): number {
return this.getPaperHeight();
}
getTrackPartPath(n: number): string {
var extra = 0;
if (n == 0) {
extra -= this.trackStart;
}
var s = 'M' + (extra + this.trackPartLength * n) + ',' + this.getPaperHeight();
s += 'L' + (this.trackPartLength * (n + 1)) + ',' + this.getPaperHeight();
s += ' ' + (this.trackPartLength * (n + 1) + this.trackShift) + ',' + 0;
s += ' ' + (extra + this.trackPartLength * n + this.trackShift) + ',' + 0;
s += 'z';
return s;
}
getTrackPartPathDivider(n: number): string {
var delta = 40;
var s = 'M' + this.trackPartLength * (n + 1) + ',' + this.getPaperHeight();
s += 'L' + (this.trackPartLength * (n + 1) + this.trackShift) + ',' + 0;
return s;
}
//TrackID
getTrackIdX(index: number): number {
if (index === 0) {
return (this.trackPartLength * index) + 10;
}
return this.trackShift + (this.trackPartLength * index) + 10;
}
getTrackIdY(index: number): number {
return 4;
}
getTrackId(index: number): string {
return '' + (index + 1);
}
} | the_stack |
import { info } from 'console';
import { pathExists, writeJSON } from 'fs-extra';
import { defaultsDeep } from 'lodash';
import { dirname, resolve } from 'path';
import readPackage from 'read-pkg';
import resolvePackage from 'resolve-pkg';
import writePackage from 'write-pkg';
import { generateContent, getVariable, resolveContext } from './content';
import { linkFiles, loadFile, unlinkFiles, writeFiles } from './io';
import {
arePeerPackagesAutoInstalled,
getPackage,
reifyDependencies,
} from './package';
import { filter, isJSON, merge, template } from './template';
import type {
PresetAsset,
PresetContext,
PresetterConfig,
ResolvedPresetContext,
Template,
} from './types';
/** presetter configuration filename */
const PRESETTERRC = '.presetterrc';
const JSON_INDENT = 2;
/**
* get the .presetterrc configuration file content
* @param root the base directory in which the configuration file should be located
* @returns content of the configuration file
*/
export async function getPresetterRC(root: string): Promise<PresetterConfig> {
const potentialConfigFiles = ['', '.json'].map((ext) =>
resolve(root, `${PRESETTERRC}${ext}`),
);
for (const path of potentialConfigFiles) {
if (await pathExists(path)) {
// return the first customisation file found
const custom = await loadFile(path, 'json');
assertPresetterRC(custom);
return custom;
}
}
throw new Error('Missing preset defined in .presetterrc');
}
/**
* update .presetterrc configuration file content
* @param root the base directory in which the configuration file should be located
* @param config content to be merged with the existing configuration file
*/
export async function updatePresetterRC(
root: string,
config: PresetterConfig,
): Promise<void> {
const existingPresetterRC = await getPresetterRC(root).catch(() => ({}));
await writeJSON(
resolve(root, `${PRESETTERRC}.json`),
merge(existingPresetterRC, config),
{ spaces: JSON_INDENT },
);
}
/**
* check that the configuration is valid
* @param value content from a configuration file
*/
export function assertPresetterRC(
value: unknown,
): asserts value is PresetterConfig {
if (
!isJSON(value) ||
(typeof value['preset'] !== 'string' && !Array.isArray(value['preset']))
) {
throw new Error(`invalid presetter configuration file`);
}
}
/**
* get the preset package name from package.json
* @param context context about the target project and any customisation in .presetterrc
* @returns name of the preset package
*/
export async function getPresetAssets(
context: PresetContext,
): Promise<PresetAsset[]> {
// get the preset name
const { preset } = context.custom;
const presets = Array.isArray(preset) ? preset : [preset];
const assets: PresetAsset[] = [];
for (const preset of presets) {
try {
// get the preset
const module = resolvePackage(preset, {
cwd: context.target.root,
});
const { default: presetPresetAsset } = (await import(module!)) as {
default: (args: PresetContext) => Promise<PresetAsset>;
};
const asset = await presetPresetAsset(context);
// add extended assets first
const extensions =
asset.extends?.map(async (extension) =>
getPresetAssets({
...context,
custom: { ...context.custom, preset: extension },
}),
) ?? [];
assets.push(...(await Promise.all(extensions)).flat());
// then asset from this preset so that this preset can override the extended ones
assets.push(asset);
} catch {
throw new Error(`cannot resolve preset ${preset}`);
}
}
return assets;
}
/**
* merge all scripts templates
* @param context context about the target project and any customisation in .presetterrc
* @returns scripts template
*/
export async function getScripts(
context: PresetContext,
): Promise<Record<string, string>> {
const { custom } = context;
// get assets from all configured presets
const assets = await getPresetAssets(context);
// compute the final variable to be used in the scripts template
const variable = getVariable(assets, context);
// load templated scripts from presets
const scripts = await Promise.all(
assets
.map((asset) => asset.scripts)
.filter((path): path is string => typeof path === 'string')
.map(
async (path) =>
(await loadFile(path, 'yaml')) as Record<string, string>,
),
);
// merge all template scripts from presets
const scriptsFromPreset = scripts.reduce(
(merged, scripts) => merge(merged, scripts),
{},
);
// merge customised scripts with the preset scripts
const scriptsWithCustomConfig = merge(scriptsFromPreset, custom.scripts);
// replace the template variables
return template(scriptsWithCustomConfig, variable);
}
/**
* adopt a preset to the project
* @param uris list of name or git url of the preset
*/
export async function setupPreset(...uris: string[]): Promise<void> {
// NOTE: comparing packages before and after installation is the only reliable way
// to extract the name of the preset in case it's given as a git url or file path etc.
const { path } = await getPackage();
const root = dirname(path);
const packageBefore = (await readPackage({ cwd: root })).devDependencies;
// install presetter & the preset
info(`Installing ${uris.join(' ')}... it may take a few moment...`);
await reifyDependencies({
root,
add: ['presetter', ...uris],
saveAs: 'dev',
lockFile: true,
});
// extract the name of the installed preset
const packageAfter = (await readPackage({ cwd: root })).devDependencies;
const newPackages = getNewPackages({ ...packageBefore }, { ...packageAfter });
const preset = newPackages.filter((name) => name !== 'presetter');
info('Updating .presetterrc.json & package.json');
// update .presetterrc.json
await updatePresetterRC(root, { preset });
// bootstrap configuration files with the new .presetterrc.json
const context = await getContext();
await bootstrapContent(context);
// insert post install script if not preset
await writePackage(
root,
defaultsDeep(context.target.package, {
scripts: { prepare: 'presetter bootstrap' },
}),
);
info('Done. Enjoy coding!');
}
/**
* bootstrap the preset to the current project root
* @param options options on how to bootstrap the preset
* @param options.force do all steps despite potential step saving
*/
export async function bootstrapPreset(options?: {
force?: boolean;
}): Promise<void> {
const { force = false } = { ...options };
const context = await getContext();
// install all related packages first
if (force || !arePeerPackagesAutoInstalled()) {
await reifyDependencies({ root: context.target.root });
}
// generate configurations
await bootstrapContent(context);
}
/**
* generate files from templates and link them to the target project root
* @param context context about the target project and any customisation in .presetterrc
*/
export async function bootstrapContent(context: PresetContext): Promise<void> {
const assets = await getPresetAssets(context);
const content = await generateContent(assets, context);
const resolvedContext = await resolveContext(assets, context);
const filteredContent = filter(content, ...(context.custom.ignores ?? []));
const destinationMap = await getDestinationMap(
filteredContent,
resolvedContext,
);
await writeFiles(context.target.root, filteredContent, destinationMap);
await linkFiles(context.target.root, destinationMap);
}
/**
* uninstall the preset from the current project root
*/
export async function unsetPreset(): Promise<void> {
const context = await getContext();
const assets = await getPresetAssets(context);
const content = await generateContent(assets, context);
const resolvedContext = await resolveContext(assets, context);
const configurationLink = await getDestinationMap(content, resolvedContext);
await unlinkFiles(context.target.root, configurationLink);
}
/**
* get context about the target project and any customisation in .presetterrc
* @returns context about the target project and any customisation in .presetterrc
*/
export async function getContext(): Promise<PresetContext> {
const { json, path } = await getPackage();
const root = dirname(path);
const target = { name: json.name, root, package: json };
const custom = await getPresetterRC(root);
return {
target,
custom,
};
}
/**
* compute the output paths of all configuration files to be generated
* @param template resolved template map
* @param context resolved context about the target project and customisation
* @returns mapping of configuration symlinks to its real path
*/
export async function getDestinationMap(
template: Record<string, Template>,
context: ResolvedPresetContext<'noSymlinks'>,
): Promise<Record<string, string>> {
const {
custom: { noSymlinks },
target: { root },
} = context;
// make sure we use the path of presetter under the target project, not the one via npx
const presetterDir = resolvePackage('presetter', { cwd: root });
const outDir = resolve(presetterDir!, 'generated', context.target.name);
const relativePaths = [...Object.keys(template)];
return Object.fromEntries([
...relativePaths.map((relativePath): [string, string] => [
relativePath,
resolve(
// output on the project root if it's specified as not a symlink
noSymlinks.includes(relativePath) ? context.target.root : outDir,
relativePath,
),
]),
]);
}
/**
* get a list of new packages installed by comparing the before and after state of devDependencies in package.json
* @param before before state of devDependencies in package.json
* @param after after state of devDependencies in package.json
* @returns list of new package names
*/
function getNewPackages(
before: Record<string, string>,
after: Record<string, string>,
): string[] {
return Object.keys(after).filter((name): name is string => !before[name]);
} | the_stack |
import { join, resolve, sep } from "path";
import { expect } from "chai";
import * as mock from "mock-fs";
import * as sinon from "sinon";
import {
_files,
_findPackage,
_resolvePackageMap,
dependencies,
INpmPackage,
INpmPackageMap,
readPackage,
readPackages,
} from "../../../src/lib/util/dependencies";
import { toPosixPath } from "../../../src/lib/util/files";
const posixifyKeys = (obj: INpmPackageMap): INpmPackageMap => Object.keys(obj)
.reduce((memo, key) => ({ ...memo, [toPosixPath(key)]: obj[key] }), {});
const toNativePath = (filePath: string) => filePath.split("/").join(sep);
const nativifyKeys = (obj: INpmPackageMap): INpmPackageMap => Object.keys(obj)
.reduce((memo, key) => ({ ...memo, [toNativePath(key)]: obj[key] }), {});
const fillNpmPkg = (obj: object): INpmPackage => ({
dependencies: {},
devDependencies: {},
name: "",
range: "",
version: "",
...obj,
});
describe("lib/util/dependencies", () => {
let sandbox: sinon.SinonSandbox;
beforeEach(() => {
sandbox = sinon.createSandbox();
});
afterEach(() => {
sandbox.restore();
mock.restore();
});
describe("readPackage", () => {
beforeEach(() => {
sandbox.spy(_files, "readJson");
});
[
{ desc: "without cache", useCache: false },
{ desc: "with cache", useCache: true },
].forEach(({ desc, useCache }) => {
describe(desc, () => {
it("returns null for missed packages", () => {
mock({});
const cache = useCache ? {} : undefined;
return Promise.all([
readPackage("./package.json", cache),
readPackage("./package.json", cache),
readPackage("./package.json", cache),
])
.then((results) => {
expect(results).to.eql([null, null, null]);
expect(_files.readJson).to.have.callCount(useCache ? 1 : 3);
});
});
it("returns objects for found packages", () => {
const pkg = {
name: "foo",
version: "1.0.0",
};
mock({
"package.json": JSON.stringify(pkg),
});
const cache = useCache ? {} : undefined;
return Promise.all([
readPackage("./package.json", cache),
readPackage("./package.json", cache),
readPackage("./NOT_FOUND/package.json", cache),
readPackage("./package.json", cache),
])
.then((results) => {
expect(results).to.eql([pkg, pkg, null, pkg]);
expect(_files.readJson).to.have.callCount(useCache ? 2 : 4);
});
});
it("errors on bad JSON", () => {
mock({
"package.json": "THIS_IS_NOT_JSON",
});
const cache = useCache ? {} : undefined;
return Promise.all([
readPackage("./package.json", cache),
readPackage("./package.json", cache),
readPackage("./NOT_FOUND/package.json", cache),
readPackage("./package.json", cache),
])
.then(() => {
throw new Error("Should not reach then");
})
.catch((err) => {
expect(err)
.to.be.an.instanceOf(SyntaxError).and
.to.have.property("message").that.contains("Unexpected token");
// **Potentially brittle**: Because we invoke all in parallel, we
// should have cache populated _first_ before any error strikes.
//
// **Note**: can remove this assert if it ends up being flaky.
expect(_files.readJson).to.have.callCount(useCache ? 2 : 4);
});
});
});
});
});
describe("readPackages", () => {
beforeEach(() => {
sandbox.spy(_files, "readJson");
});
it("handles no root package.json", () => {
mock({});
return readPackages(".")
.then(_resolvePackageMap)
.then((pkgs) => {
expect(pkgs).to.eql({});
});
});
it("errors on bad package.json's", () => {
const pkg = {
name: "foo",
version: "1.0.0",
};
mock({
"node_modules": {
bad: {
"package.json": "THIS_IS_NOT_JSON",
},
},
"package.json": JSON.stringify(pkg),
});
return readPackages(".")
.then(_resolvePackageMap)
.then(() => {
throw new Error("Should not reach then");
})
.catch((err) => {
expect(err)
.to.be.an.instanceOf(SyntaxError).and
.to.have.property("message").that.contains("Unexpected token");
});
});
it("inflates a flattened tree", () => {
const bar = {
name: "bar",
version: "1.0.0",
};
const baz = {
name: "@scoped/baz",
version: "1.0.0",
};
const foo = {
name: "foo",
version: "1.0.0",
};
mock({
"node_modules": {
"@scoped": {
baz: {
"package.json": JSON.stringify(baz),
},
},
"bar": {
"package.json": JSON.stringify(bar),
},
},
"package.json": JSON.stringify(foo),
});
return readPackages(".")
.then(_resolvePackageMap)
.then(posixifyKeys)
.then((pkgs) => {
expect(pkgs).to.eql({
"node_modules/@scoped/baz/package.json": baz,
"node_modules/bar/package.json": bar,
"package.json": foo,
});
});
});
it("inflates an unflattened tree", () => {
const bar = {
name: "bar",
version: "1.0.0",
};
const baz = {
name: "@scoped/baz",
version: "1.0.0",
};
const foo = {
name: "foo",
version: "1.0.0",
};
mock({
"node_modules": {
bar: {
"node_modules": {
"@scoped": {
baz: {
"package.json": JSON.stringify(baz),
},
},
},
"package.json": JSON.stringify(bar),
},
},
"package.json": JSON.stringify(foo),
});
return readPackages(".")
.then(_resolvePackageMap)
.then(posixifyKeys)
.then((pkgs) => {
expect(pkgs).to.eql({
"node_modules/bar/node_modules/@scoped/baz/package.json": baz,
"node_modules/bar/package.json": bar,
"package.json": foo,
});
});
});
it("includes multiple deps", () => {
const foo1 = {
name: "foo",
version: "1.0.0",
};
const diffFoo = {
dependencies: {
foo: "^3.0.0",
},
name: "different-foo",
version: "1.0.1",
};
const foo3 = {
name: "foo",
version: "3.0.0",
};
const base = {
dependencies: {
"different-foo": "1.0.0",
"foo": "^3.0.0",
},
name: "base",
version: "1.0.2",
};
mock({
"node_modules": {
"different-foo": {
"node_modules": {
foo: {
"package.json": JSON.stringify(foo3),
},
},
"package.json": JSON.stringify(diffFoo),
},
"foo": {
"package.json": JSON.stringify(foo1),
},
},
"package.json": JSON.stringify(base),
});
return readPackages(".")
.then(_resolvePackageMap)
.then(posixifyKeys)
.then((pkgs) => {
expect(pkgs).to.eql({
"node_modules/different-foo/node_modules/foo/package.json": foo3,
"node_modules/different-foo/package.json": diffFoo,
"node_modules/foo/package.json": foo1,
"package.json": base,
});
});
});
});
describe("_findPackage", () => {
const _baseArgs = { filePath: "base", name: "foo", pkgMap: {} };
const _emptyResp = { isFlattened: false, pkgObj: null, pkgPath: null };
it("handles empty cases", () => {
const base = fillNpmPkg({
dependencies: {
foo: "^3.0.0",
},
name: "base",
version: "1.0.2",
});
expect(_findPackage(_baseArgs)).to.eql(_emptyResp);
expect(_findPackage({
..._baseArgs,
name: "bar",
pkgMap: nativifyKeys({
"base/node_modules/foo/package.json": fillNpmPkg({
name: "foo",
version: "1.0.0",
}),
"base/package.json": base,
}),
})).to.eql(_emptyResp);
});
it("finds unflattened packages", () => {
const base = fillNpmPkg({
dependencies: {
foo: "^3.0.0",
},
name: "base",
version: "1.0.2",
});
const foo = fillNpmPkg({
name: "foo",
version: "3.0.0",
});
expect(_findPackage({
..._baseArgs,
pkgMap: nativifyKeys({
"base/node_modules/foo/package.json": foo,
"base/package.json": base,
}),
})).to.eql({
isFlattened: false,
pkgObj: foo,
pkgPath: toNativePath("base/node_modules/foo"),
});
});
it("finds hidden roots packages outside of file path", () => {
const myPkg = fillNpmPkg({
dependencies: {
foo: "^3.0.0",
},
name: "my-pkg",
version: "1.0.2",
});
const foo = fillNpmPkg({
name: "foo",
version: "3.0.0",
});
// Note: Base _doesn't_ have `foo` dependency.
const base = fillNpmPkg({
name: "base",
version: "1.0.0",
});
expect(_findPackage({
..._baseArgs,
filePath: "base/packages/my-pkg",
pkgMap: nativifyKeys({
"base/node_modules/foo/package.json": foo,
"base/package.json": base,
"base/packages/my-pkg/package.json": myPkg,
}),
})).to.eql({
isFlattened: true,
pkgObj: foo,
pkgPath: toNativePath("base/node_modules/foo"),
});
});
});
describe("dependencies", () => {
it("handles empty root path", () => {
mock({});
return dependencies(".")
.then((deps) => {
expect(deps).to.equal(null);
});
});
it("handles no dependencies root package", () => {
mock({
"package.json": JSON.stringify({
name: "hi",
}),
});
const filePath = resolve(".");
return dependencies(filePath)
.then((deps) => {
expect(deps).to.eql({
dependencies: [],
filePath,
name: "hi",
range: "*",
version: "*",
});
});
});
it("handles empty dependencies root package", () => {
mock({
"package.json": JSON.stringify({
dependencies: {},
name: "hi",
version: "1.2.3",
}),
});
const filePath = resolve(".");
return dependencies(filePath)
.then((deps) => {
expect(deps).to.eql({
dependencies: [],
filePath,
name: "hi",
range: "1.2.3",
version: "1.2.3",
});
});
});
it("tolerates missing modules.", () => {
mock({
"node_modules": {
foo: {
"node_modules": {
bar: {
"package.json": JSON.stringify({
dependencies: {
baz: "^4.0.0",
},
name: "bar",
version: "3.4.7",
}),
},
},
"package.json": JSON.stringify({
dependencies: {
bar: "^3.4.5",
},
name: "foo",
version: "2.3.5",
}),
},
},
"package.json": JSON.stringify({
dependencies: {
baz: "^4.0.0",
foo: "^2.3.4",
},
name: "hi",
version: "1.2.3",
}),
});
const filePath = resolve(".");
return dependencies(filePath)
.then((deps) => {
expect(deps).to.eql({
dependencies: [
{
dependencies: [
{
dependencies: [],
filePath: join(filePath, "node_modules/foo/node_modules/bar"),
name: "bar",
range: "^3.4.5",
version: "3.4.7",
},
],
filePath: join(filePath, "node_modules/foo"),
name: "foo",
range: "^2.3.4",
version: "2.3.5",
},
],
filePath,
name: "hi",
range: "1.2.3",
version: "1.2.3",
});
});
});
it("handles unflattened trees", () => {
mock({
"node_modules": {
baz: {
"package.json": JSON.stringify({
name: "baz",
version: "4.0.0",
}),
},
foo: {
"node_modules": {
bar: {
"node_modules": {
baz: {
"package.json": JSON.stringify({
name: "baz",
version: "4.0.0",
}),
},
},
"package.json": JSON.stringify({
dependencies: {
baz: "^4.0.0",
},
name: "bar",
version: "3.4.7",
}),
},
},
"package.json": JSON.stringify({
dependencies: {
bar: "^3.4.5",
},
name: "foo",
version: "2.3.5",
}),
},
},
"package.json": JSON.stringify({
dependencies: {
baz: "^4.0.0",
foo: "^2.3.4",
},
name: "hi",
version: "1.2.3",
}),
});
const filePath = resolve(".");
return dependencies(filePath)
.then((deps) => {
expect(deps).to.eql({
dependencies: [
{
dependencies: [],
filePath: join(filePath, "node_modules/baz"),
name: "baz",
range: "^4.0.0",
version: "4.0.0",
},
{
dependencies: [
{
dependencies: [
{
dependencies: [],
filePath: join(filePath,
"node_modules/foo/node_modules/bar/node_modules/baz"),
name: "baz",
range: "^4.0.0",
version: "4.0.0",
},
],
filePath: join(filePath, "node_modules/foo/node_modules/bar"),
name: "bar",
range: "^3.4.5",
version: "3.4.7",
},
],
filePath: join(filePath, "node_modules/foo"),
name: "foo",
range: "^2.3.4",
version: "2.3.5",
},
],
filePath,
name: "hi",
range: "1.2.3",
version: "1.2.3",
});
});
});
it("handles flattened trees", () => {
mock({
"node_modules": {
baz: {
"package.json": JSON.stringify({
name: "baz",
version: "4.0.0",
}),
},
catpower: {
"package.json": JSON.stringify({
dependencies: {
baz: "^4.0.0",
},
name: "catpower",
version: "1.0.0",
}),
},
foo: {
"node_modules": {
bar: {
"package.json": JSON.stringify({
dependencies: {
baz: "^4.0.0",
},
name: "bar",
version: "3.4.7",
}),
},
},
"package.json": JSON.stringify({
dependencies: {
bar: "^3.4.5",
catpower: "^1.0.0",
},
name: "foo",
version: "2.3.5",
}),
},
},
"package.json": JSON.stringify({
dependencies: {
baz: "^4.0.0",
foo: "^2.3.4",
},
name: "hi",
version: "1.2.3",
}),
});
const filePath = resolve(".");
// Convenience variable for our flattened package.
const baz = {
dependencies: [],
filePath: join(filePath, "node_modules/baz"),
name: "baz",
range: "^4.0.0",
version: "4.0.0",
};
return dependencies(filePath)
.then((deps) => {
expect(deps).to.eql({
dependencies: [
baz,
{
dependencies: [
{
dependencies: [
baz,
],
filePath: join(filePath, "node_modules/foo/node_modules/bar"),
name: "bar",
range: "^3.4.5",
version: "3.4.7",
},
{
dependencies: [
baz,
],
filePath: join(filePath, "node_modules/catpower"),
name: "catpower",
range: "^1.0.0",
version: "1.0.0",
},
],
filePath: join(filePath, "node_modules/foo"),
name: "foo",
range: "^2.3.4",
version: "2.3.5",
},
],
filePath,
name: "hi",
range: "1.2.3",
version: "1.2.3",
});
});
});
it("handles scoped packages mixed in tree", () => {
mock({
"node_modules": {
"@baz": {
baz: {
"package.json": JSON.stringify({
name: "@baz/baz",
version: "4.0.0",
}),
},
},
"catpower": {
"package.json": JSON.stringify({
dependencies: {
"@baz/baz": "^4.0.0",
},
name: "catpower",
version: "1.0.0",
}),
},
"foo": {
"node_modules": {
"@bar": {
bar: {
"package.json": JSON.stringify({
dependencies: {
"@baz/baz": "^4.0.0",
},
name: "@bar/bar",
version: "3.4.7",
}),
},
},
},
"package.json": JSON.stringify({
dependencies: {
"@bar/bar": "^3.4.5",
"catpower": "^1.0.0",
},
name: "foo",
version: "2.3.5",
}),
},
},
"package.json": JSON.stringify({
dependencies: {
"@baz/baz": "^4.0.0",
"foo": "^2.3.4",
},
name: "hi",
version: "1.2.3",
}),
});
const filePath = resolve(".");
// Convenience variable for our flattened package.
const baz = {
dependencies: [],
filePath: join(filePath, "node_modules/@baz/baz"),
name: "@baz/baz",
range: "^4.0.0",
version: "4.0.0",
};
return dependencies(filePath)
.then((deps) => {
expect(deps).to.eql({
dependencies: [
baz,
{
dependencies: [
{
dependencies: [
baz,
],
filePath: join(filePath, "node_modules/foo/node_modules/@bar/bar"),
name: "@bar/bar",
range: "^3.4.5",
version: "3.4.7",
},
{
dependencies: [
baz,
],
filePath: join(filePath, "node_modules/catpower"),
name: "catpower",
range: "^1.0.0",
version: "1.0.0",
},
],
filePath: join(filePath, "node_modules/foo"),
name: "foo",
range: "^2.3.4",
version: "2.3.5",
},
],
filePath,
name: "hi",
range: "1.2.3",
version: "1.2.3",
});
});
});
it("handles missing dependencies permissively", () => {
mock({
"node_modules": {
catpower: {
"package.json": JSON.stringify({
dependencies: {
baz: "^4.0.0",
},
name: "catpower",
version: "1.0.0",
}),
},
foo: {
"node_modules": {
bar: {
"package.json": JSON.stringify({
dependencies: {
baz: "^4.0.0",
},
name: "bar",
version: "3.4.7",
}),
},
},
"package.json": JSON.stringify({
dependencies: {
bar: "^3.4.5",
catpower: "^1.0.0",
},
name: "foo",
version: "2.3.5",
}),
},
},
"package.json": JSON.stringify({
dependencies: {
baz: "^4.0.0",
foo: "^2.3.4",
},
name: "hi",
version: "1.2.3",
}),
});
const filePath = resolve(".");
return dependencies(filePath)
.then((deps) => {
expect(deps).to.eql({
dependencies: [
{
dependencies: [
{
dependencies: [],
filePath: join(filePath, "node_modules/foo/node_modules/bar"),
name: "bar",
range: "^3.4.5",
version: "3.4.7",
},
{
dependencies: [],
filePath: join(filePath, "node_modules/catpower"),
name: "catpower",
range: "^1.0.0",
version: "1.0.0",
},
],
filePath: join(filePath, "node_modules/foo"),
name: "foo",
range: "^2.3.4",
version: "2.3.5",
},
],
filePath,
name: "hi",
range: "1.2.3",
version: "1.2.3",
});
});
});
it("handles deeply flattened, circular trees", () => {
mock({
"node_modules": {
"@baz": {
baz: {
"package.json": JSON.stringify({
dependencies: {
foo: "^2.3.4",
},
name: "@baz/baz",
version: "4.0.0",
}),
},
},
"catpower": {
"package.json": JSON.stringify({
dependencies: {
"@baz/baz": "^4.0.0",
},
name: "catpower",
version: "1.0.0",
}),
},
"foo": {
"node_modules": {
"@bar": {
bar: {
"package.json": JSON.stringify({
dependencies: {
"@baz/baz": "^4.0.0",
},
name: "@bar/bar",
version: "3.4.7",
}),
},
},
},
"package.json": JSON.stringify({
dependencies: {
"@bar/bar": "^3.4.5",
"catpower": "^1.0.0",
},
name: "foo",
version: "2.3.5",
}),
},
},
"package.json": JSON.stringify({
dependencies: {
"@baz/baz": "^4.0.0",
"foo": "^2.3.4",
},
name: "hi",
version: "1.2.3",
}),
});
const filePath = resolve(".");
// These are the default circular (shorter) references for baz, foo
const baz = {
dependencies: [],
filePath: join(filePath, "node_modules/@baz/baz"),
name: "@baz/baz",
range: "^4.0.0",
version: "4.0.0",
};
const foo = {
dependencies: [
{
dependencies: [],
filePath: join(filePath, "node_modules/foo/node_modules/@bar/bar"),
name: "@bar/bar",
range: "^3.4.5",
version: "3.4.7",
},
{
dependencies: [],
filePath: join(filePath, "node_modules/catpower"),
name: "catpower",
range: "^1.0.0",
version: "1.0.0",
},
],
filePath: join(filePath, "node_modules/foo"),
name: "foo",
range: "^2.3.4",
version: "2.3.5",
};
return dependencies(filePath)
.then((deps) => {
expect(deps).to.eql({
dependencies: [
// Root level (non-circular) of baz will have deps.
{
...baz,
dependencies: [foo],
},
{
...foo,
dependencies: foo.dependencies.map((dep) => ({
...dep,
dependencies: [baz],
})),
},
],
filePath,
name: "hi",
range: "1.2.3",
version: "1.2.3",
});
});
});
it("handles circular trees", () => {
mock({
"node_modules": {
baz: {
"package.json": JSON.stringify({
dependencies: {
foo: "^4.0.0",
},
name: "baz",
version: "4.0.0",
}),
},
foo: {
"package.json": JSON.stringify({
dependencies: {
baz: "^4.0.0",
},
name: "foo",
version: "4.0.0",
}),
},
},
"package.json": JSON.stringify({
dependencies: {
baz: "^4.0.0",
foo: "^4.0.0",
},
name: "hi",
version: "1.2.3",
}),
});
const filePath = resolve(".");
return dependencies(filePath)
.then((deps) => {
expect(deps).to.eql({
dependencies: [
{
dependencies: [
{
dependencies: [],
filePath: join(filePath, "node_modules/foo"),
name: "foo",
range: "^4.0.0",
version: "4.0.0",
},
],
filePath: join(filePath, "node_modules/baz"),
name: "baz",
range: "^4.0.0",
version: "4.0.0",
},
{
dependencies: [
{
dependencies: [],
filePath: join(filePath, "node_modules/baz"),
name: "baz",
range: "^4.0.0",
version: "4.0.0",
},
],
filePath: join(filePath, "node_modules/foo"),
name: "foo",
range: "^4.0.0",
version: "4.0.0",
},
],
filePath,
name: "hi",
range: "1.2.3",
version: "1.2.3",
});
});
});
});
}); | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormCampaign {
interface Header extends DevKit.Controls.IHeader {
/** Type the expected revenue for the campaign for return on investment projections and post-campaign reporting. */
ExpectedRevenue: DevKit.Controls.Money;
/** Select whether the campaign is a template that can be copied when you create future campaigns. */
IsTemplate: DevKit.Controls.Boolean;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
/** Select the campaign's status. */
StatusCode: DevKit.Controls.OptionSet;
}
interface tab_DETAILS_Sections {
ADMINISTRATION: DevKit.Controls.Section;
DESCRIPTION: DevKit.Controls.Section;
FINANCIALS: DevKit.Controls.Section;
RESPONSES: DevKit.Controls.Section;
}
interface tab_SUMMARY_Sections {
CAMPAIGN: DevKit.Controls.Section;
CAMPAIGN_ACTIVITIES: DevKit.Controls.Section;
LEADS: DevKit.Controls.Section;
LISTS: DevKit.Controls.Section;
OFFER: DevKit.Controls.Section;
RELATED_PANE: DevKit.Controls.Section;
SCHEDULES: DevKit.Controls.Section;
}
interface tab_DETAILS extends DevKit.Controls.ITab {
Section: tab_DETAILS_Sections;
}
interface tab_SUMMARY extends DevKit.Controls.ITab {
Section: tab_SUMMARY_Sections;
}
interface Tabs {
DETAILS: tab_DETAILS;
SUMMARY: tab_SUMMARY;
}
interface Body {
Tab: Tabs;
/** Enter the date when the campaign was closed or completed. */
ActualEnd: DevKit.Controls.Date;
/** Enter the actual start date and time for the campaign. */
ActualStart: DevKit.Controls.Date;
/** Type the amount budgeted for the campaign to define a limit for how much you can spend. */
BudgetedCost: DevKit.Controls.Money;
/** Type a number or other tracking code to identify the campaign. If no value is entered, a code will be generated automatically. */
CodeName: DevKit.Controls.String;
/** Date and time when the record was created. */
CreatedOn: DevKit.Controls.DateTime;
/** Type additional information to describe the campaign, such as the products or services offered or the targeted audience. */
Description: DevKit.Controls.String;
/** Type the expected response rate for the campaign as a full number between 0 and 100. */
ExpectedResponse: DevKit.Controls.Integer;
/** Shows who last updated the record. */
ModifiedBy: DevKit.Controls.Lookup;
/** Date and time when the record was modified. */
ModifiedOn: DevKit.Controls.DateTime;
/** Type a name for the campaign so that it is identified correctly in lists. */
Name: DevKit.Controls.String;
notescontrol: DevKit.Controls.Note;
/** Type the objective of the campaign, including products, services, discounts, and pricing. */
Objective: DevKit.Controls.String;
/** Type the sum of any miscellaneous campaign costs not included in the campaign activities to make sure the actual cost of the campaign is calculated correctly. */
OtherCost: DevKit.Controls.Money;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
/** Enter the date when the campaign is scheduled to end. */
ProposedEnd: DevKit.Controls.Date;
/** Enter the date when the campaign is scheduled to start. */
ProposedStart: DevKit.Controls.Date;
TmpRegardingObjectId: DevKit.Controls.String;
/** Shows the sum of the amounts entered in the Total Cost of Campaign Activities and Miscellaneous Costs fields. */
TotalActualCost: DevKit.Controls.Money;
/** Shows the sum of the values entered in the Actual Cost field on all campaign activities related to the campaign. */
TotalCampaignActivityActualCost: DevKit.Controls.Money;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.Controls.Lookup;
/** Select the type of the campaign. */
TypeCode: DevKit.Controls.OptionSet;
}
interface Grid {
Lists: DevKit.Controls.Grid;
Leads: DevKit.Controls.Grid;
Activities: DevKit.Controls.Grid;
Responses: DevKit.Controls.Grid;
}
}
class FormCampaign extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Campaign
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Campaign */
Body: DevKit.FormCampaign.Body;
/** The Header section of form Campaign */
Header: DevKit.FormCampaign.Header;
/** The Grid of form Campaign */
Grid: DevKit.FormCampaign.Grid;
}
class CampaignApi {
/**
* DynamicsCrm.DevKit CampaignApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Enter the date when the campaign was closed or completed. */
ActualEnd_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the actual start date and time for the campaign. */
ActualStart_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Type the amount budgeted for the campaign to define a limit for how much you can spend. */
BudgetedCost: DevKit.WebApi.MoneyValue;
/** Value of the Budget Allocated in base currency. */
BudgetedCost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Unique identifier of the campaign. */
CampaignId: DevKit.WebApi.GuidValue;
/** Type a number or other tracking code to identify the campaign. If no value is entered, a code will be generated automatically. */
CodeName: DevKit.WebApi.StringValue;
/** Shows who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who created the record on behalf of another user. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Type additional information to describe the campaign, such as the products or services offered or the targeted audience. */
Description: DevKit.WebApi.StringValue;
/** The primary email address for the entity. */
EmailAddress: DevKit.WebApi.StringValue;
/** The default image for the entity. */
EntityImage: DevKit.WebApi.StringValue;
EntityImage_Timestamp: DevKit.WebApi.BigIntValueReadonly;
EntityImage_URL: DevKit.WebApi.StringValueReadonly;
EntityImageId: DevKit.WebApi.GuidValueReadonly;
/** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */
ExchangeRate: DevKit.WebApi.DecimalValueReadonly;
/** Type the expected response rate for the campaign as a full number between 0 and 100. */
ExpectedResponse: DevKit.WebApi.IntegerValue;
/** Type the expected revenue for the campaign for return on investment projections and post-campaign reporting. */
ExpectedRevenue: DevKit.WebApi.MoneyValue;
/** Value of the Estimated Revenue in base currency. */
ExpectedRevenue_Base: DevKit.WebApi.MoneyValueReadonly;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Select whether the campaign is a template that can be copied when you create future campaigns. */
IsTemplate: DevKit.WebApi.BooleanValue;
/** Type the promotional message or marketing copy for the campaign. */
Message: DevKit.WebApi.StringValue;
/** Shows who last updated the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who created the record on behalf of another user. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Type a name for the campaign so that it is identified correctly in lists. */
Name: DevKit.WebApi.StringValue;
/** Type the objective of the campaign, including products, services, discounts, and pricing. */
Objective: DevKit.WebApi.StringValue;
/** Type the sum of any miscellaneous campaign costs not included in the campaign activities to make sure the actual cost of the campaign is calculated correctly. */
OtherCost: DevKit.WebApi.MoneyValue;
/** Value of the Miscellaneous Costs in base currency. */
OtherCost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the team that owns the record. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user that owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Choose the price list associated with this item to make sure the products associated with the campaign are offered at the correct prices. */
PriceListId: DevKit.WebApi.LookupValue;
PriceListName: DevKit.WebApi.StringValueReadonly;
/** Contains the id of the process associated with the entity. */
ProcessId: DevKit.WebApi.GuidValue;
/** Type a promotional code to track sales related to the campaign or allow customers to redeem a discount offer. */
PromotionCodeName: DevKit.WebApi.StringValue;
/** Enter the date when the campaign is scheduled to end. */
ProposedEnd_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the date when the campaign is scheduled to start. */
ProposedStart_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Contains the id of the stage where the entity is located. */
StageId: DevKit.WebApi.GuidValue;
/** Shows the status of the campaign. By default, campaigns are active and can't be deactivated. */
StateCode: DevKit.WebApi.OptionSetValue;
/** Select the campaign's status. */
StatusCode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
TmpRegardingObjectId: DevKit.WebApi.StringValue;
/** Shows the sum of the amounts entered in the Total Cost of Campaign Activities and Miscellaneous Costs fields. */
TotalActualCost: DevKit.WebApi.MoneyValueReadonly;
/** Value of the Total Cost of Campaign in base currency. */
TotalActualCost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the sum of the values entered in the Actual Cost field on all campaign activities related to the campaign. */
TotalCampaignActivityActualCost: DevKit.WebApi.MoneyValueReadonly;
/** Value of the Total Cost of Campaign Activities in base currency. */
TotalCampaignActivityActualCost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** A comma separated list of string values representing the unique identifiers of stages in a Business Process Flow Instance in the order that they occur. */
TraversedPath: DevKit.WebApi.StringValue;
/** Select the type of the campaign. */
TypeCode: DevKit.WebApi.OptionSetValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace Campaign {
enum StateCode {
/** 0 */
Active,
/** 1 */
Inactive
}
enum StatusCode {
/** 4 */
Canceled,
/** 3 */
Completed,
/** 6 */
Inactive,
/** 2 */
Launched,
/** 0 */
Proposed,
/** 1 */
Ready_To_Launch,
/** 5 */
Suspended
}
enum TypeCode {
/** 1 */
Advertisement,
/** 4 */
Co_branding,
/** 2 */
Direct_Marketing,
/** 3 */
Event,
/** 5 */
Other
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Campaign'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import Vue from 'vue';
import Vuex, {
CommitOptions,
DispatchOptions,
Module,
ModuleTree,
Payload,
Store,
StoreOptions,
} from 'vuex';
Vue.use(Vuex);
// Override dispatch and commit so that we can have them typed with the real mutations/actions.
interface VuexDispatch<P> {
<T extends keyof P>(type: T, payload?: P[T], options?: DispatchOptions): Promise<any>;
<T extends Payload>(payloadWithType: T, options?: DispatchOptions): Promise<any>;
}
interface VuexCommit<P> {
<T extends keyof P>(type: T, payload?: P[T], options?: CommitOptions): void;
<T extends Payload>(payloadWithType: T, options?: CommitOptions): void;
}
export abstract class VuexStore<S = any, A = any, M = any> extends Store<S> {
dispatch!: VuexDispatch<A>;
commit!: VuexCommit<M>;
getServerState?: () => any;
// Just so we can make options optional.
constructor(options?: StoreOptions<S>) {
super(options || {});
}
}
type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T];
type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>;
export function NamespaceVuexStore<T extends VuexStore, A, M>(
globalStore: VuexStore,
namespace: string
) {
class NamespacedStore {
get state() {
return globalStore.state[namespace] as NonFunctionProperties<T>;
}
dispatch<K extends keyof A>(
type: K,
payload?: A[K],
options?: DispatchOptions
): Promise<any> {
return globalStore.dispatch(namespace + '/' + type, payload, options);
}
commit<K extends keyof M>(type: K, payload?: M[K], options?: CommitOptions): void {
return globalStore.commit(namespace + '/' + type, payload, options);
}
}
return new NamespacedStore();
}
const storeInstance = new Vuex.Store({});
interface QueuedDecoratorCallback {
(store: any): void;
}
let queuedDecorators: QueuedDecoratorCallback[] = [];
interface VuexModuleOptions {
store?: boolean;
modules?: ModuleTree<any>;
namespaced?: boolean;
}
export function VuexModule(options: VuexModuleOptions = {}) {
const decorators = queuedDecorators;
queuedDecorators = [];
// A function that returns a function. Will be used as a constructor
// function.
return (target: any): any => () => {
const state: any = {};
// These are private helpers. Don't want them to show in vue-devtools.
Object.defineProperties(state, {
__vuexGetters: { enumerable: false, writable: true, value: [] },
__vuexArgGetters: { enumerable: false, writable: true, value: [] },
__vuexMutations: { enumerable: false, writable: true, value: [] },
__vuexActions: { enumerable: false, writable: true, value: [] },
__vuexGetterScope: { enumerable: false, writable: true },
__vuexActionScope: { enumerable: false, writable: true },
__vuexMutationScope: { enumerable: false, writable: true },
});
const storeOptions: Module<any, any> = {
modules: options.modules || {},
namespaced: !options.store,
state,
actions: {},
mutations: {},
};
// Copy over state.
const instance = new target();
for (const key of Object.getOwnPropertyNames(instance)) {
if (!(key in storeInstance)) {
state[key] = instance[key];
}
}
// Copy over getters.
for (const key of Object.getOwnPropertyNames(target.prototype)) {
if (key in Vuex.Store.prototype) {
continue;
}
const desc = Object.getOwnPropertyDescriptor(target.prototype, key);
const getter = desc && desc.get;
if (!getter) {
continue;
}
// We define getters on the state. We don't put them into vuex
// getters. This way they're available from any scope for any other
// getter, action, mutation, etc. Vuex getters are a bit mad to work
// with and can only be used in certain vuex scopes so they have
// limited usefulness.
Object.defineProperty(state, key, {
enumerable: true,
get: () => {
const scope = getGetterScope(state);
return getter.apply(scope);
},
});
state.__vuexGetters.push(key);
}
// Apply the mutation and action decorators.
for (const cb of decorators) {
cb(storeOptions);
}
// Create the store instance. If it's the main store, we create it, if
// it's not the main store we just use our options object.
if (!options.store) {
return storeOptions;
} else {
const _instance = new Vuex.Store(storeOptions) as VuexStore;
// Overload this so that we do our own replace state handler.
_instance.replaceState = (newState: any) =>
replaceState(_instance, newState, _instance.state);
_instance.getServerState = () => getServerState(_instance);
return _instance;
}
};
}
function isModule(store: any, key: string) {
return key in store._modules.root._children;
}
function replaceState(store: any, newState: any, currentState: any) {
for (const k in newState) {
if (currentState.__vuexGetters.indexOf(k) !== -1) {
// Don't overwrite getters when setting new state.
continue;
} else if (isModule(store, k)) {
// Recurse into submodules.
replaceState(store, newState[k], currentState[k]);
} else {
currentState[k] = newState[k];
}
}
}
function getServerState(store: any) {
const serverState = Object.assign({}, store.state);
// We remove any dynamic modules. They are always used for
// routes and we would rather bootstrap the route modules
// from the raw payload data.
const childModules = store._modules.root._children;
for (const childModuleName in childModules) {
const childModule = childModules[childModuleName];
if (childModule.runtime) {
delete serverState[childModuleName];
}
}
return serverState;
}
/**
* Creates a getter function that can take parameters. Will be accessible in
* getters, actions, and mutations. Can't modify the state in any way, though.
*/
export function VuexGetter(target: any, name: string) {
const method = target[name];
queuedDecorators.push(store => {
store.state.__vuexArgGetters.push(name);
// We set this as non-enumerable so that it doesn't show up in
// vue-devtools and similar state freezing events.
Object.defineProperty(store.state, name, {
enumerable: false,
get: () => (...args: any[]) => {
const scope = getGetterScope(store.state);
return method.apply(scope, args);
},
});
});
}
export function VuexMutation(target: any, name: string) {
const method = target[name];
queuedDecorators.push(store => {
store.state.__vuexMutations.push(name);
store.mutations![name] = (state: any, ...args: any[]) => {
const scope = getMutationScope(state);
return method.apply(scope, args);
};
});
}
export function VuexAction(target: any, name: string) {
const method = target[name];
queuedDecorators.push(store => {
store.state.__vuexActions.push(name);
store.actions[name] = (storeContext: any, ...args: any[]) => {
const scope = getActionScope(storeContext);
return method.apply(scope, args);
};
});
}
function getGetterScope(state: any) {
if (!state.__vuexGetterScope) {
const scope: any = {};
scopeNoStateChange('getter', scope, state);
scopeNoCallers('getter', scope, state);
state.__vuexGetterScope = scope;
}
return state.__vuexGetterScope;
}
function getActionScope(store: any) {
if (!store.state.__vuexActionScope) {
const scope: any = {};
scopeNoStateChange('action', scope, store.state);
// Mutations and actions will just funnel off to theire
// store.(commit/dispatch) equivalents so that we continue to funnel
// through vuex.
for (const key of store.state.__vuexMutations) {
scope[key] = (...args: any[]) => store.commit(key, ...args);
}
for (const key of store.state.__vuexActions) {
scope[key] = (...args: any[]) => store.dispatch(key, ...args);
}
// Pull these into the scope so that parent modules can call into their
// nested namespaced modules.
scope.commit = (...args: any[]) => store.commit(...args);
scope.dispatch = (...args: any[]) => store.dispatch(...args);
store.state.__vuexActionScope = scope;
}
return store.state.__vuexActionScope;
}
function getMutationScope(state: any) {
if (!state.__vuexMutationScope) {
const scope: any = {};
scopeState('mutation', scope, state);
scopeNoCallers('mutation', scope, state);
state.__vuexMutationScope = scope;
}
return state.__vuexMutationScope;
}
/**
* Sets up the scope so that you can access and modify state.
*/
function scopeState(_caller: string, scope: any, state: any) {
for (const key of Object.getOwnPropertyNames(state)) {
Object.defineProperty(scope, key, {
enumerable: true,
get: () => state[key],
set: (val: any) => (state[key] = val),
});
}
}
/**
* Sets up the scope so that you can't modify state.
*/
function scopeNoStateChange(caller: string, scope: any, state: any) {
// Make a passthrough for all state to get. This allows us to throw an error
// when they try setting within the action.
for (const key of Object.getOwnPropertyNames(state)) {
Object.defineProperty(scope, key, {
get: () => state[key],
set: () => stateMutateError(caller, key),
});
}
}
/**
* Sets up the scope so that you can't call mutations/actions on it.
*/
function scopeNoCallers(caller: string, scope: any, state: any) {
// Define these as properties so that we don't ovewrite the prototype's data
// for these methods.
for (const key of state.__vuexMutations) {
Object.defineProperty(scope, key, {
get: () => () => mutationError(caller, key),
});
}
for (const key of state.__vuexActions) {
Object.defineProperty(scope, key, {
get: () => () => actionError(caller, key),
});
}
return scope;
}
function stateMutateError(caller: string, field: string) {
throwError(`Couldn't modify field ${field}. You can't modify state within a ${caller}.`);
}
function mutationError(caller: string, mutation: string) {
throwError(`Couldn't commit ${mutation}. You can't call mutations within a ${caller}.`);
}
function actionError(caller: string, action: string) {
throwError(`Couldn't dispatch ${action}. You can't call actions within a ${caller}.`);
}
/**
* Not all errors will be caught. This ensures that they see the error even if
* it's not caught and shown.
*/
function throwError(msg: string) {
const error = new Error(msg);
console.error(error);
throw error;
} | the_stack |
import {
LitElement,
css,
PropertyValues,
html,
nothing,
render,
TemplateResult,
} from 'lit';
import {DirectiveResult} from 'lit/directive.js';
import {customElement, property, query, state} from 'lit/decorators.js';
import {ifDefined} from 'lit/directives/if-defined.js';
import {CodeMirror} from './internal/codemirror.js';
import playgroundStyles from './playground-styles.js';
import './internal/overlay.js';
import type {Diagnostic} from 'vscode-languageserver';
import type {
Doc,
Editor,
EditorChange,
Hint,
Hints,
Position,
ShowHintOptions,
} from 'codemirror';
import {
EditorCompletion,
EditorCompletionDetails,
EditorPosition,
EditorToken,
CodeEditorChangeData,
} from './shared/worker-api.js';
// TODO(aomarks) Could we upstream this to lit-element? It adds much stricter
// types to the ChangedProperties type.
interface TypedMap<T> extends Map<keyof T, unknown> {
get<K extends keyof T>(key: K): T[K];
set<K extends keyof T>(key: K, value: T[K]): this;
delete<K extends keyof T>(key: K): boolean;
keys(): IterableIterator<keyof T>;
values(): IterableIterator<T[keyof T]>;
entries(): IterableIterator<{[K in keyof T]: [K, T[K]]}[keyof T]>;
}
export interface CodeEditorHint {
details?: Promise<EditorCompletionDetails>;
text: string;
displayText?: string | undefined;
render?:
| ((element: HTMLLIElement, data: Hints, cur: Hint) => void)
| undefined;
}
const unreachable = (n: never) => n;
/**
* A basic text editor with syntax highlighting for HTML, CSS, and JavaScript.
*/
@customElement('playground-code-editor')
export class PlaygroundCodeEditor extends LitElement {
static styles = [
css`
:host {
display: block;
}
#focusContainer {
height: 100%;
position: relative;
}
#focusContainer:focus {
outline: none;
}
.CodeMirror {
height: 100% !important;
border-radius: inherit;
}
.CodeMirror-foldmarker {
font-family: sans-serif;
}
.CodeMirror-foldmarker:hover {
cursor: pointer;
/* Pretty much any color from the theme is good enough. */
color: var(--playground-code-keyword-color, #770088);
}
#keyboardHelp {
font-size: 18px;
font-family: sans-serif;
padding: 10px 20px;
}
.diagnostic {
position: relative;
}
.diagnostic::before {
/* It would be nice to use "text-decoration: red wavy underline" here,
but unfortunately it renders nothing at all for single characters.
See https://bugs.chromium.org/p/chromium/issues/detail?id=668042. */
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJDw4cOCW1/KIAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAHElEQVQI12NggIL/DAz/GdA5/xkY/qPKMDAwAADLZwf5rvm+LQAAAABJRU5ErkJggg==');
content: '';
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 3px;
}
#tooltip {
position: absolute;
padding: 7px;
z-index: 4;
font-family: var(--playground-code-font-family, monospace);
}
#tooltip > div {
background: var(--playground-code-background, #fff);
color: var(--playground-code-default-color, #000);
/* Kind of hacky... line number color tends to work out as a good
default border, because it's usually visible on top of the
background, but slightly muted. */
border: 1px solid var(--playground-code-linenumber-color, #ccc);
padding: 5px;
}
`,
playgroundStyles,
];
protected _codemirror?: ReturnType<typeof CodeMirror>;
get cursorPosition(): EditorPosition {
const cursor = this._codemirror?.getCursor('start');
if (!cursor) return {ch: 0, line: 0};
return {
ch: cursor.ch,
line: cursor.line,
};
}
get cursorIndex(): number {
const cm = this._codemirror;
if (!cm) return 0;
const cursorPosition = cm.getCursor('start');
return cm.indexFromPos(cursorPosition);
}
get tokenUnderCursor(): EditorToken {
const cm = this._codemirror;
if (!cm) return {start: 0, end: 0, string: ''};
const cursorPosition = cm.getCursor('start');
const token = cm.getTokenAt(cursorPosition);
return {
start: token.start,
end: token.end,
string: token.string,
};
}
// We store _value ourselves, rather than using a public reactive property, so
// that we can set this value internally without triggering an update.
private _value?: string;
@property()
get value() {
return this._value;
}
set value(v: string | undefined) {
const oldValue = this._value;
this._value = v;
this.requestUpdate('value', oldValue);
}
/**
* Provide a `documentKey` to create a CodeMirror document instance which
* isolates history and value changes per `documentKey`.
*
* Use to keep edit history separate between files while reusing the same
* playground-code-editor instance.
*/
@property({attribute: false})
// eslint-disable-next-line @typescript-eslint/ban-types
documentKey?: object;
/**
* WeakMap associating a `documentKey` with CodeMirror document instance.
* A WeakMap is used so that this component does not become the source of
* memory leaks.
*/
// eslint-disable-next-line @typescript-eslint/ban-types
private readonly _docCache = new WeakMap<object, Doc>();
/**
* The type of the file being edited, as represented by its usual file
* extension.
*/
@property()
type: 'js' | 'ts' | 'html' | 'css' | 'json' | undefined;
/**
* If true, display a left-hand-side gutter with line numbers. Default false
* (hidden).
*/
@property({type: Boolean, attribute: 'line-numbers', reflect: true})
lineNumbers = false;
/**
* If true, wrap for long lines. Default false
*/
@property({type: Boolean, attribute: 'line-wrapping', reflect: true})
lineWrapping = false;
/**
* If true, this editor is not editable.
*/
@property({type: Boolean, reflect: true})
readonly = false;
/**
* If true, will disable code completions in the code-editor.
*/
@property({type: Boolean, attribute: 'no-completions'})
noCompletions = false;
/**
* Diagnostics to display on the current file.
*/
@property({attribute: false})
diagnostics?: Array<Diagnostic>;
@state()
_completions?: EditorCompletion[];
@state()
_completionsOpen = false;
private _onCompletionSelectedChange?: () => void;
private _currentCompletionSelectionLabel = '';
private _currentCompletionRequestId = 0;
/**
* How to handle `playground-hide` and `playground-fold` comments.
*
* See https://github.com/google/playground-elements#hiding--folding for
* more details.
*
* Options:
* - on: Hide and fold regions, and hide the special comments.
* - off: Don't hide or fold regions, but still hide the special comments.
* - off-visible: Don't hide or fold regions, and show the special comments as
* literal text.
*/
@property()
pragmas: 'on' | 'off' | 'off-visible' = 'on';
@state()
private _tooltipDiagnostic?: {
diagnostic: Diagnostic;
position: string;
};
@state()
private _showKeyboardHelp = false;
@query('#focusContainer')
private _focusContainer?: HTMLDivElement;
@query('.CodeMirror-code')
private _codemirrorEditable?: HTMLDivElement;
private _resizeObserver?: ResizeObserver;
private _resizing = false;
private _valueChangingFromOutside = false;
private _cmDom?: HTMLElement;
private _diagnosticMarkers: Array<CodeMirror.TextMarker> = [];
private _diagnosticsMouseoverListenerActive = false;
update(changedProperties: PropertyValues) {
const cm = this._codemirror;
if (cm === undefined) {
this._createView();
} else {
const changedTyped = changedProperties as TypedMap<
Omit<PlaygroundCodeEditor, keyof LitElement | 'render' | 'update'>
>;
for (const prop of changedTyped.keys()) {
switch (prop) {
case 'documentKey': {
const docKey = this.documentKey ?? {};
let docInstance = this._docCache.get(docKey);
let createdNewDoc = false;
if (!docInstance) {
docInstance = new CodeMirror.Doc(
this.value ?? '',
this._getLanguageMode()
);
this._docCache.set(docKey, docInstance);
createdNewDoc = true;
} else if (docInstance.getValue() !== this.value) {
// The retrieved document instance has contents which don't
// match the currently set `value`.
docInstance.setValue(this.value ?? '');
}
this._valueChangingFromOutside = true;
cm.swapDoc(docInstance);
if (createdNewDoc) {
// Swapping to a document instance doesn't trigger a change event
// which is required for document folding. Manually fold once on
// document instantiation.
this._applyHideAndFoldRegions();
}
this._valueChangingFromOutside = false;
break;
}
case 'value':
if (changedTyped.has('documentKey')) {
// If the `documentKey` has changed then all `value` change logic
// is handled in the documentKey case.
break;
}
this._valueChangingFromOutside = true;
cm.setValue(this.value ?? '');
this._valueChangingFromOutside = false;
break;
case 'lineNumbers':
cm.setOption('lineNumbers', this.lineNumbers);
break;
case 'lineWrapping':
if (this.lineWrapping) {
cm.on('renderLine', this._onRenderLine);
} else {
cm.off('renderLine', this._onRenderLine);
}
cm.setOption('lineWrapping', this.lineWrapping);
break;
case 'type':
cm.setOption('mode', this._getLanguageMode());
break;
case 'readonly':
cm.setOption('readOnly', this.readonly);
break;
case 'pragmas':
this._applyHideAndFoldRegions();
break;
case 'diagnostics':
this._showDiagnostics();
break;
case 'cursorIndex':
cm.setCursor(this.cursorIndex ?? 0);
break;
case 'cursorPosition':
cm.setCursor(this.cursorPosition ?? {ch: 0, line: 0});
break;
case '_completions':
this._showCompletions();
break;
case 'tokenUnderCursor':
case 'noCompletions':
case '_completionsOpen':
// Ignored
break;
default:
unreachable(prop);
}
}
}
super.update(changedProperties);
}
render() {
if (this.readonly) {
return this._cmDom;
}
return html`
<div
id="focusContainer"
tabindex="0"
@mousedown=${this._onMousedown}
@focus=${this._onFocus}
@blur=${this._onBlur}
@keydown=${this._onKeyDown}
>
${this._showKeyboardHelp
? html`<playground-internal-overlay>
<p id="keyboardHelp" part="dialog">
Press <strong>Enter</strong> to start editing<br />
Press <strong>Escape</strong> to exit editor
</p>
</playground-internal-overlay>`
: nothing}
${this._cmDom}
<div
id="tooltip"
?hidden=${!this._tooltipDiagnostic}
style=${ifDefined(this._tooltipDiagnostic?.position)}
>
<div part="diagnostic-tooltip">
${this._tooltipDiagnostic?.diagnostic.message}
</div>
</div>
</div>
`;
}
connectedCallback() {
// CodeMirror uses JavaScript to control whether scrollbars are visible. It
// does so automatically on interaction, but won't notice container size
// changes. If the browser doesn't have ResizeObserver, scrollbars will
// sometimes be missing, but typing in the editor will fix it.
if (typeof ResizeObserver === 'function') {
this._resizeObserver = new ResizeObserver(() => {
if (this._resizing) {
// Don't get in a resize loop.
return;
}
this._resizing = true;
this._codemirror?.refresh();
this._resizing = false;
});
this._resizeObserver.observe(this);
}
super.connectedCallback();
}
disconnectedCallback() {
this._resizeObserver?.disconnect();
this._resizeObserver = undefined;
super.disconnectedCallback();
}
private _createView() {
const cm: CodeMirror.Editor = CodeMirror(
(dom) => {
this._cmDom = dom;
this._resizing = true;
requestAnimationFrame(() => {
requestAnimationFrame(() => {
// It seems that some dynamic layouts confuse CodeMirror, causing it
// to measure itself too soon, which then causes the position of
// interactions to be interpreted incorrectly. Here we hackily force
// a refresh after initial layout is usually done.
this._codemirror?.refresh();
this._resizing = false;
});
});
},
{
value: this.value ?? '',
lineNumbers: this.lineNumbers,
lineWrapping: this.lineWrapping,
mode: this._getLanguageMode(),
readOnly: this.readonly,
inputStyle: 'contenteditable',
// Don't allow naturally tabbing into the editor, because it's a
// tab-trap. Instead, the container is focusable, and Enter/Escape are
// used to explicitly enter the editable area.
tabindex: -1,
// Tab key inserts spaces instead of tab character
extraKeys: {
Tab: () => {
cm.replaceSelection(
Array(cm.getOption('indentUnit') ?? 2).join(' ')
);
},
// Ctrl + Space requests code completions.
['Ctrl-Space']: () => {
const tokenUnderCursor = this.tokenUnderCursor.string.trim();
this._requestCompletions({
isRefinement: false,
tokenUnderCursor,
});
},
['Ctrl-/']: () => cm.toggleComment(),
['Cmd-/']: () => cm.toggleComment(),
},
}
);
cm.on('change', (_editorInstance: Editor, changeObject: EditorChange) => {
this._value = cm.getValue();
// External changes are usually things like the editor switching which
// file it is displaying.
if (this._valueChangingFromOutside) {
// Users can't change hide/fold regions.
this._applyHideAndFoldRegions();
this._showDiagnostics();
} else {
this.dispatchEvent(new Event('change'));
this._requestCompletionsIfNeeded(changeObject);
}
});
if (this.lineWrapping) {
cm.on('renderLine', this._onRenderLine);
}
this._codemirror = cm;
}
private _onRenderLine(
editorInstance: Editor,
line: CodeMirror.LineHandle,
elt: HTMLElement
) {
// When wrapping a line the subsequent wrapped code
// needs to keep the same formatting and have the
// same amount of indentation.
//
// Each line has an initial `padding-left`, this needs
// to be preserved with the indent:
// - playground-styles.css#L39 - standard padding.
// - playground-styles.css#L72 - extra with line numbers.
const basePadding = 4;
const gutter = editorInstance.getOption('lineNumbers')
? '0.7em'
: `${basePadding}px`;
const tabSize = editorInstance.getOption('tabSize') || basePadding;
const off = CodeMirror.countColumn(line.text, null, tabSize);
if (off > 0) {
elt.style.textIndent = `-${off}ch`;
elt.style.paddingLeft = `calc(${gutter} + ${off}ch)`;
}
}
private _requestCompletionsIfNeeded(changeObject: EditorChange) {
if (
this.noCompletions ||
!this._currentFiletypeSupportsCompletion() ||
!this._codemirror
)
return;
const previousToken = this._codemirror.getTokenAt(changeObject.from);
const tokenUnderCursor = this.tokenUnderCursor.string.trim();
const tokenUnderCursorAsString = tokenUnderCursor.trim();
// To help reduce round trips to a language service or a completion provider, we
// are providing a flag if the completion is building on top of the earlier recommendations.
// If the flag is true, the completion system can just filter the already stored
// collection of completions again with the more precise input.
// On deletion events, we want to query the LS again, since we might be in a new context after
// removing characters from our code.
const isInputEvent = changeObject.origin === '+input';
const isRefinement =
(tokenUnderCursor.length > 1 || previousToken.string === '.') &&
isInputEvent;
const changeWasCodeCompletion = changeObject.origin === 'complete';
if (tokenUnderCursorAsString.length <= 0) return;
if (changeWasCodeCompletion) {
// If the case that the user triggered a code completion,
// we want to empty out the completions until
// a letter is input.
this._completions = [];
return;
}
this._requestCompletions({
isRefinement,
tokenUnderCursor,
});
}
private _requestCompletions({
isRefinement,
tokenUnderCursor,
}: Pick<CodeEditorChangeData, 'isRefinement' | 'tokenUnderCursor'>) {
if (
this.noCompletions ||
!this._currentFiletypeSupportsCompletion() ||
!this._codemirror
)
return;
const id = ++this._currentCompletionRequestId;
const cursorIndexOnRequest = this.cursorIndex;
this.dispatchEvent(
new CustomEvent('request-completions', {
detail: {
isRefinement,
fileContent: this.value,
tokenUnderCursor,
cursorIndex: this.cursorIndex,
provideCompletions: (completions: EditorCompletion[]) =>
this._onCompletionsProvided(id, completions, cursorIndexOnRequest),
},
})
);
}
private _onCompletionsProvided(
id: number,
completions: EditorCompletion[],
cursorIndex: number
) {
// To prevent race conditioning, check that the completions provided
// are from the latest completions request.
// We also check that the cursor hasn't moved to another position since the
// completion request, causing the completion to be applied in a wrong spot.
if (
id !== this._currentCompletionRequestId ||
cursorIndex !== this.cursorIndex
) {
return;
}
this._completions = completions;
}
private _currentFiletypeSupportsCompletion() {
// Currently we are only supporting code completion for TS. Change
// this in a case that we start to support it for other languages too.
return this.type === 'ts';
}
focus() {
this._codemirrorEditable?.focus();
}
private _completionsAsHints(cm: Editor): Hints {
const cursorPosition = cm.getCursor('start');
const token = cm.getTokenAt(cursorPosition);
const lineNumber = cursorPosition.line;
const hintList =
this._completions?.map(
(comp, i) =>
({
text: comp.text,
displayText: comp.displayText,
render: (element, _data, hint) => {
const codeEditorHint = hint as CodeEditorHint;
this._renderHint(
element,
_data,
codeEditorHint,
i === 0 ? comp.details : undefined // Only render the detail on the first item
);
},
get details() {
return comp.details;
},
} as CodeEditorHint)
) ?? [];
const hints: Hints = {
from: {line: lineNumber, ch: token.start} as Position,
to: {line: lineNumber, ch: token.end} as Position,
list: hintList,
};
CodeMirror.on(
hints,
'select',
async (hint: Hint | string, element: Element) => {
if (!this._isCodeEditorHint(hint)) return;
// If the current selection is the same, e.g. the completions were just
// updated by user input, instead of moving through completions, we don't
// want to re-render and re-fetch the details.
if (this._currentCompletionSelectionLabel === hint.text) return;
this._onCompletionSelectedChange?.();
this._renderHint(element as HTMLElement, hints, hint, hint.details);
}
);
// As CodeMirror doesn't let us directly query if the completion hints are shown,
// we want to have our own local state following the completions menu state.
CodeMirror.on(hints, 'shown', () => {
// Delay updating the status by a frame so that key listeners still have
// access to the correct state for the current situation.
window.requestAnimationFrame(() => {
this._completionsOpen = true;
});
});
CodeMirror.on(hints, 'close', () => {
window.requestAnimationFrame(() => {
this._completionsOpen = false;
});
});
return hints;
}
private _isCodeEditorHint(hint: Hint | string): hint is CodeEditorHint {
return (
typeof hint !== 'string' &&
Object.prototype.hasOwnProperty.call(hint, 'details')
);
}
private _renderHint(
element: HTMLElement | undefined,
_data: Hints,
hint: CodeEditorHint,
detail?: Promise<EditorCompletionDetails>
) {
if (!element) return;
const itemIndex = _data.list.indexOf(hint);
const completionData = this._completions?.[itemIndex];
const objectName = this._buildHintObjectName(
hint.displayText,
completionData
);
// Render the actual completion item first
this._renderCompletionItem(objectName, element);
// And if we have the detail promise passed into this function,
// we want to asynchronously update the detail info into our completion
// item. We don't want to block the rendering, so we don't use await.
//
// The detail promise is passed into this function only for the item
// currently highlighted from the completions list.
if (detail !== undefined) {
detail.then((detailResult: EditorCompletionDetails) => {
this._renderCompletionItemWithDetails(
objectName,
detailResult,
element
);
// Set the current onSelectedChange to a callback to re-render
// the currently selected element, but without the details. This is
// then triggered when moving to another selection, removing the details
// text from the previously selected element.
this._onCompletionSelectedChange = () =>
this._renderHint(element, _data, hint);
this._currentCompletionSelectionLabel = hint.text;
});
}
}
private _renderCompletionItem(
objectName: string | TemplateResult,
target: HTMLElement
) {
render(html`<span class="hint-object-name">${objectName}</span>`, target);
}
private _renderCompletionItemWithDetails(
objectName: DirectiveResult,
details: EditorCompletionDetails,
target: HTMLElement
) {
render(
html`<span class="hint-object-name">${objectName}</span>
<span class="hint-object-details">${details.text}</span> `,
target
);
}
/**
* Builds the name of the completable item for use in the completion UI.
* Using marks, we can highlight the matching characters in the typed input
* matching with the completion suggestion.
*/
private _buildHintObjectName(
objectName: string | undefined,
completionData: EditorCompletion | undefined
): TemplateResult | string {
const markedObjectName = objectName ?? '';
const matches = completionData?.matches ?? [];
if (matches.length <= 0) {
// In the situation, that none of the input matches with the
// completion item suggestion, we exit early, leaving the objectName unmarked.
return markedObjectName;
}
const firstMatch = matches[0];
const firstMatchingIndex = firstMatch.indices[0];
const start = firstMatchingIndex[0];
const end = firstMatchingIndex[1];
const preMarkContent = markedObjectName?.substring(0, start);
const markedContent = markedObjectName?.substring(start, end + 1);
const postMarkedContent = markedObjectName?.substring(end + 1);
return html`
${preMarkContent}<mark>${markedContent}</mark>${postMarkedContent}
`;
}
private _showCompletions() {
const cm = this._codemirror;
if (!cm || !this._completions || this._completions.length <= 0) return;
const options: ShowHintOptions = {
hint: this._completionsAsHints.bind(this),
completeSingle: false,
closeOnPick: true,
closeOnUnfocus: true,
container: this._focusContainer,
alignWithWord: true,
};
cm.showHint(options);
}
private _onMousedown() {
// Directly focus editable region.
this._codemirrorEditable?.focus();
}
private _onFocus() {
// Outer container was focused, either by tabbing from outside, or by
// pressing Escape.
this._showKeyboardHelp = true;
}
private _onBlur() {
// Outer container was unfocused, either by tabbing away from it, or by
// pressing Enter.
this._showKeyboardHelp = false;
}
private _onKeyDown(event: KeyboardEvent) {
if (event.key === 'Enter' && event.target === this._focusContainer) {
this._codemirrorEditable?.focus();
// Prevent typing a newline from this same event.
event.preventDefault();
} else if (event.key === 'Escape') {
// If the user has completions selection UI opened up, Escape's default action
// is to close the completion UI instead of escaping the code editor instance.
// Therefore we only focus on the focusContainer in situations where the completions
// UI is not open.
if (!this._completionsOpen) {
// Note there is no API for "select the next naturally focusable element",
// so instead we just re-focus the outer container, from which point the
// user can tab to move focus entirely elsewhere.
this._focusContainer?.focus();
}
}
}
/**
* Create hidden and folded regions for playground-hide and playground-fold
* comments.
*/
private async _applyHideAndFoldRegions() {
const cm = this._codemirror;
if (!cm) {
return;
}
// Reset any existing hide/fold regions.
for (const mark of cm.getAllMarks()) {
mark.clear();
}
if (this.pragmas === 'off-visible') {
return;
}
const pattern = this._maskPatternForLang();
if (pattern === undefined) {
return;
}
const doc = cm.getDoc();
const fold = (fromIdx: number, toIdx: number) => {
cm.foldCode(/* ignored by our rangeFinder */ 0, {
widget: '…',
rangeFinder: () => ({
from: doc.posFromIndex(fromIdx),
to: doc.posFromIndex(toIdx),
}),
});
};
const hide = (fromIdx: number, toIdx: number, readOnly: boolean) => {
doc.markText(doc.posFromIndex(fromIdx), doc.posFromIndex(toIdx), {
collapsed: true,
readOnly,
});
};
const value = cm.getValue();
for (const match of value.matchAll(pattern)) {
const [, opener, kind, content, closer] = match;
const openerStart = match.index;
if (openerStart === undefined) {
continue;
}
const openerEnd = openerStart + opener.length;
hide(openerStart, openerEnd, false);
const contentStart = openerEnd;
let contentEnd;
if (content && closer) {
contentEnd = contentStart + content.length;
const closerStart = contentEnd;
const closerEnd = contentEnd + closer.length;
hide(closerStart, closerEnd, false);
} else {
// No matching end comment. Include the entire rest of the file.
contentEnd = value.length;
}
if (this.pragmas === 'on') {
if (kind === 'fold') {
fold(contentStart, contentEnd);
} else if (kind === 'hide') {
hide(contentStart, contentEnd, true);
}
}
}
}
private _maskPatternForLang(): RegExp | undefined {
switch (this.type) {
case 'js':
case 'ts':
case 'css':
// We consume all leading whitespace and one trailing newline for each
// start/end comment. This lets us put start/end comments on their own
// line and indent them like the surrounding without affecting the
// selected region.
return /( *\/\* *playground-(?<kind>hide|fold) *\*\/\n?)(?:(.*?)( *\/\* *playground-\k<kind>-end *\*\/\n?))?/gs;
case 'html':
return /( *<!-- *playground-(?<kind>hide|fold) *-->\n?)(?:(.*?)( *<!-- *playground-\k<kind>-end *-->\n?))?/gs;
default:
return undefined;
}
}
private _getLanguageMode() {
switch (this.type) {
case 'ts':
return 'google-typescript';
case 'js':
case 'json':
// While the stock CodeMirror JavaScript mode has a restricted "json"
// mode, the google-javascript mode does not (which we use because it
// supports html-in-js highlighting). Adding the CodeMirror JavaScript
// mode would add ~50KiB minified + brotli, so let's just put up with
// the fact that you'll get highlighting for JS even though it's not
// valid JSON.
return 'google-javascript';
case 'html':
return 'google-html';
case 'css':
return 'css';
}
return undefined;
}
private _showDiagnostics() {
const cm = this._codemirror;
if (cm === undefined) {
return;
}
cm.operation(() => {
this._tooltipDiagnostic = undefined;
while (this._diagnosticMarkers.length > 0) {
this._diagnosticMarkers.pop()!.clear();
}
if (!this.diagnostics?.length) {
if (this._diagnosticsMouseoverListenerActive) {
this._cmDom?.removeEventListener(
'mouseover',
this._onMouseOverWithDiagnostics
);
this._diagnosticsMouseoverListenerActive = false;
}
return;
}
if (!this._diagnosticsMouseoverListenerActive) {
this._cmDom?.addEventListener(
'mouseover',
this._onMouseOverWithDiagnostics
);
this._diagnosticsMouseoverListenerActive = true;
}
for (let i = 0; i < this.diagnostics.length; i++) {
const diagnostic = this.diagnostics[i];
this._diagnosticMarkers.push(
cm.markText(
{
line: diagnostic.range.start.line,
ch: diagnostic.range.start.character,
},
{
line: diagnostic.range.end.line,
ch: diagnostic.range.end.character,
},
{
className: `diagnostic diagnostic-${i}`,
}
)
);
}
});
}
// Using property assignment syntax so that it's already bound to `this` for
// add/removeEventListener.
private _onMouseOverWithDiagnostics = (event: MouseEvent) => {
if (!this.diagnostics?.length) {
return;
}
// Find the diagnostic. Note we could use cm.findMarksAt() with the pointer
// coordinates (like the built-in linter plugin does), but since we've
// encoded the diagnostic index into a class, we can just extract it
// directly from the target.
const idxMatch = (event.target as Element).className?.match(
/diagnostic-(\d+)/
);
if (idxMatch === null) {
this._tooltipDiagnostic = undefined;
return;
}
const idx = Number(idxMatch[1]);
const diagnostic = this.diagnostics[idx];
if (diagnostic === this._tooltipDiagnostic?.diagnostic) {
// Already showing the tooltip for this diagnostic.
return;
}
// Position the tooltip relative to the squiggly code span. To maximize
// available space, place it above/below and left/right depending on which
// quadrant the span is in.
let position = '';
const hostRect = this.getBoundingClientRect();
const spanRect = (event.target as Element).getBoundingClientRect();
const hostCenterY = hostRect.y + hostRect.height / 2;
if (spanRect.y < hostCenterY) {
// Note the rects are viewport relative, so the extra subtractions here
// are to convert to host-relative.
position += `top:${spanRect.y + spanRect.height - hostRect.y}px;`;
} else {
position += `bottom:${hostRect.bottom - spanRect.y}px;`;
}
const hostCenterX = hostRect.x + hostRect.width / 2;
if (spanRect.left < hostCenterX) {
position += `left:${Math.max(0, spanRect.x - hostRect.x)}px`;
} else {
position += `right:${Math.max(0, hostRect.right - spanRect.right)}px`;
}
this._tooltipDiagnostic = {diagnostic, position};
};
}
declare global {
interface HTMLElementTagNameMap {
'playground-code-editor': PlaygroundCodeEditor;
}
} | the_stack |
import * as _ from 'lodash';
// The following line is important to keep in that format so it can be rendered into the page
export const config: IDashboardConfig = /*return*/ {
id: "mbf_advanced_health",
name: "MBF Advanced Health",
icon: "av_timer",
url: "mbf_advanced_health",
description: "Bot Framework Advanced Health Dashboard",
preview: "/images/default.png",
category: 'Bots - Advanced',
html: `POC - Additional info will be added in the future`,
config: {
connections: { },
layout: {
isDraggable: true,
isResizable: true,
rowHeight: 30,
verticalCompact: false,
cols: { lg: 12,md: 10,sm: 6,xs: 4,xxs: 2 },
breakpoints: { lg: 1200,md: 996,sm: 768,xs: 480,xxs: 0 }
}
},
dataSources: [
{
id: "timespan",
type: "Constant",
params: { values: ["24 hours","1 week","1 month","3 months"],selectedValue: "1 month" },
calculated: (state, dependencies) => {
var queryTimespan =
state.selectedValue === '24 hours' ? 'PT24H' :
state.selectedValue === '1 week' ? 'P7D' :
state.selectedValue === '1 month' ? 'P30D' :
'P90D';
var granularity =
state.selectedValue === '24 hours' ? '5m' :
state.selectedValue === '1 week' ? '1d' : '1d';
return { queryTimespan, granularity };
}
},
{
id: "samples",
type: "Constant",
params: { values: [],selectedValue: "" },
calculated: (state, dependencies) => {
let sampleJobs = [
{ name: 'Heist', lastExecution: new Date("2017-05-04T12:00:00Z") },
{ name: 'Quick Job', lastExecution: new Date("2017-05-04T12:00:00Z") },
{ name: 'Some Job', lastExecution: new Date("2017-05-03T12:00:00Z") },
{ name: 'Bad Job', lastExecution: new Date("2017-05-02T12:00:00Z") },
{ name: 'Good Job', lastExecution: new Date("2017-05-01T12:00:00Z") }
];
return { sampleJobs };
}
},
{
id: "filters",
type: "ApplicationInsights/Query",
dependencies: { timespan: "timespan",queryTimespan: "timespan:queryTimespan",granularity: "timespan:granularity" },
params: {
table: "customEvents",
queries: {
filterChannels: {
query: () => `` +
` where name == 'Activity' | ` +
` extend channel=customDimensions.channel | ` +
` summarize channel_count=count() by tostring(channel) | ` +
` order by channel_count`,
mappings: { channel: (val) => val || "unknown",channel_count: (val) => val || 0 },
calculated: (filterChannels) => {
const filters = filterChannels.map((x) => x.channel);
let { selectedValues } = filterChannels;
if (selectedValues === undefined) {
selectedValues = [];
}
return {
"channels-count": filterChannels,
"channels-filters": filters,
"channels-selected": selectedValues,
};
}
},
filterIntents: {
query: () => `
extend intent=customDimensions.intent, cslen = customDimensions.callstack_length |
where name startswith 'message.intent' and (cslen == 0 or strlen(cslen) == 0) and strlen(intent) > 0 |
summarize intent_count=count() by tostring(intent) |
order by intent_count`,
mappings: { intent: (val) => val || "unknown",intent_count: (val) => val || 0 },
calculated: (filterIntents) => {
const intents = filterIntents.map((x) => x.intent);
let { selectedValues } = filterIntents;
if (selectedValues === undefined) {
selectedValues = [];
}
return {
"intents-count": filterIntents,
"intents-filters": intents,
"intents-selected": selectedValues,
};
}
}
}
}
},
{
id: "nfl",
type: "ApplicationInsights/Query",
dependencies: { timespan: "timespan",queryTimespan: "timespan:queryTimespan",granularity: "timespan:granularity" },
params: {
table: "nflbot_CL",
queries: {
timeline: {
query: (dependencies) => {
var { granularity } = dependencies;
return `
where recordType == "serviceResult" |
summarize count=avg(serviceResultMilliseconds) by bin(timestamp, ${granularity}), service=serviceResultName |
order by timestamp asc`;
},
calculated: (timeline, dependencies) => {
// Timeline handling
// =================
let _timeline = {};
let _services = {};
let { timespan } = dependencies;
/**
* Looping through all results building timeline format values
* Expected result:
* {
* timestampValue1: { service1: count, service2: count ... }
* timestampValue2: { service1: count2, service2: count2 ... }
* }
*
* Services result:
* { service1_total: count, service2_total: count ... }
*/
timeline.forEach(row => {
var { service, timestamp, count } = row;
var timeValue = (new Date(timestamp)).getTime();
if (service.startsWith('serviceNameValue')) return;
if (!_timeline[timeValue]) _timeline[timeValue] = {
time: (new Date(timestamp)).toUTCString()
};
if (!_services[service]) _services[service] = { service, value: 0 };
_timeline[timeValue][service] = count;
_services[service].value += count;
});
// Going over all the services making sure that we add "0" count
// For every timestamp on the timeline (for no value services)
let services = Object.keys(_services);
let serviceUsage = _.values(_services);
let timelineValues = _.map(_timeline, value => {
services.forEach(service => {
if (!value[service]) value[service] = 0;
value[service] = Math.round(value[service]);
});
return value;
});
return {
"timeline-graphData": timelineValues,
"timeline-serviceUsage": serviceUsage,
"timeline-timeFormat": (timespan === "24 hours" ? 'hour' : 'date'),
"timeline-services": services
};
}
},
"service-success": {
query: () => `
where recordType == "serviceResult" |
summarize success=countif(serviceResultSuccess), failed=countif(not(serviceResultSuccess)) by service=serviceResultName |
order by service `,
calculated: (serviceSuccess) => {
_.remove(serviceSuccess, row => row['service'].startsWith("serviceNameValue"))
return {
"service-success": serviceSuccess,
"service-success-bars": [
{ name: 'success', color: "#00BFA5" },
{ name: 'failed', color: "#B71C1C" }
]
};
}
}
}
}
},
{
id: "errors",
type: "ApplicationInsights/Query",
dependencies: { timespan: "timespan",queryTimespan: "timespan:queryTimespan" },
params: {
query: () => `
exceptions |
summarize count_errors=count() by type=innermostType, message=innermostMessage, bin(timestamp, 1d) |
order by count_errors desc |
top 5 by count_errors `
}
}
],
filters: [
{
type: "TextFilter",
dependencies: { selectedValue: "timespan",values: "timespan:values" },
actions: { onChange: "timespan:updateSelectedValue" },
first: true
},
{
type: "MenuFilter",
title: "Channels",
subtitle: "Select channels",
icon: "forum",
dependencies: { selectedValues: "filters:channels-selected",values: "filters:channels-filters" },
actions: { onChange: "filters:updateSelectedValues:channels-selected" },
first: true
},
{
type: "MenuFilter",
title: "Intents",
subtitle: "Select intents",
icon: "textsms",
dependencies: { selectedValues: "filters:intents-selected",values: "filters:intents-filters" },
actions: { onChange: "filters:updateSelectedValues:intents-selected" },
first: true
}
],
elements: [
{
id: "timeline",
type: "Timeline",
title: "Service response times (ms)",
subtitle: "Average response times of each service per time unit",
size: { w: 6,h: 8 },
dependencies: { values: "nfl:timeline-graphData",lines: "nfl:timeline-services",timeFormat: "nfl:timeline-timeFormat" }
},
{
id: "topErrors",
type: "Table",
title: "Top Errors",
subtitle: "Most common errors on the selected time slot",
size: { w: 3,h: 8 },
dependencies: { values: "errors" },
props: {
compact: true,
cols: [{ header: "Top Errors",field: "type",secondaryField: "message" },{ header: "Count",field: "count_errors",type: "number" }]
}
},
{
id: "jobs",
type: "Table",
title: "Last Job Executions",
subtitle: "Most common errors on the selected time slot",
size: { w: 3,h: 8 },
dependencies: { values: "samples:sampleJobs" },
props: { compact: true,cols: [{ header: "Top Errors",field: "name" },{ header: "Last",field: "lastExecution",type: "ago" }] }
},
{
id: "service-success",
type: "BarData",
title: "Service success rate",
subtitle: "Intents usage per time",
size: { w: 6,h: 8 },
dependencies: { values: "nfl:service-success",bars: "nfl:service-success-bars" },
props: { nameKey: "service" }
}
],
dialogs: [
{
id: "intentsDialog",
width: "60%",
params: ["title","intent","queryspan"],
dataSources: [
{
id: "intentsDialog-data",
type: "ApplicationInsights/Query",
dependencies: { intent: "dialog_intentsDialog:intent",queryTimespan: "dialog_intentsDialog:queryspan" },
params: {
table: "nflbot_CL",
queries: {
"total-conversations": {
query: ({ intent }) => `
where recordType == "intent" and intentName == '${intent}' |
summarize count_intents=count(), maxTimestamp=max(timestamp) by conversationId`,
calculated: (conversations) => {
return {
"total-conversations": (conversations && conversations.length) || 0
}
}
},
utterances: {
query: ({ intent }) => `
where recordType == "intent" and intentName == '${intent}' |
summarize count_intents=count(), maxTimestamp=max(timestamp) by conversationId |
order by maxTimestamp`,
calculated: (utterances) => {
return {
"sample-utterances": [
{
intentName: 'Bla',
utterance: "What was BLA doing with BLA in BLA?",
count: 7
},
{
intentName: 'Bla',
utterance: "What was Kiki doing with Kuku in Koko?",
count: 4
},
{
intentName: 'Bla',
utterance: "What should K do with K in K?",
count: 4
},
{
intentName: 'Bla',
utterance: "K@K-K",
count: 2
},
{
intentName: 'Bla',
utterance: "Does K and K work with K?",
count: 1
}
],
"sample-success-rate": [
{
type: "Success",
percentage: "75%"
},
{
type: "Failure",
percentage: "10%"
},
{
type: "Ambiguous",
percentage: "15%"
}
],
"sample-response-types": [
{ name: "Disposition", success: 30, fail: 70 },
{ name: "Quality", default: 65, ambiguous: 20, normal: 15 },
{ name: "Type", card: 80, bubble: 20 },
{ name: "Image", success: 80, fail: 20 },
{ name: "Requests", "Logged In": 44, "Anonymous": 56 },
{ name: "Cache", hits: 90, misses: 10 }
],
"sample-response-types-bars": [
{ name: "success", color: "#00BFA5"}, { name: "fail", color: "#B71C1C" } ,
{ name: "default", color: "#64FFDA" }, { name: "ambiguous", color: "#1DE9B6" }, { name: "normal", color: "#00BFA5" },
{ name: "card", color: "#64FFDA" }, { name: "bubble", color: "#1DE9B6" },
{ name: "Logged In", color: "#00BFA5" }, { name: "Anonymous", color: "#B71C1C" },
{ name: "hits", color: "#00BFA5" }, { name: "misses", color: "#B71C1C" }
],
"sample-response-times_0": "100",
"sample-response-times_1": "20",
"sample-response-times_2": "7000000",
"sample-response-times_3": "1500",
};
}
},
"entities-usage": {
query: ({ intent }) => `where recordType == "entity" |
summarize entity_count=count() by entityType, conversationId |
summarize total_count=count() by entity_count, entityType |
order by entityType, entity_count asc |
where total_count <= 5 and entityType !startswith "kindNameValue"`,
calculated: (entityUsage) => {
let count_values = _.uniq(entityUsage.map(e => e.total_count));
let barResults = {};
let results = entityUsage.forEach(entity => {
barResults[entity.entityType] = barResults[entity.entityType] || { entityType: entity.entityType };
barResults[entity.entityType][entity.total_count] = entity.entity_count;
});
return {
"entities-usage": _.values(barResults),
"entities-usage-bars": count_values
};
}
}
}
}
}
],
elements: [
{
id: "conversations-count",
type: "Scorecard",
size: { w: 6,h: 2 },
dependencies: {
card_conversations_value: "intentsDialog-data:total-conversations",
card_conversations_heading: "::Conversations",
card_conversations_color: "::#2196F3",
card_conversations_icon: "::chat",
card_conversations_onClick: "::onConversationsClick",
card_responseTimes0_value: "intentsDialog-data:sample-response-times_0",
card_responseTimes0_heading: "::In <1 sec",
card_responseTimes0_color: "::#82B1FF",
card_responseTimes0_icon: "::av_timer",
card_responseTimes1_value: "intentsDialog-data:sample-response-times_1",
card_responseTimes1_heading: "::In <2 sec",
card_responseTimes1_color: "::#448AFF",
card_responseTimes1_icon: "::av_timer",
card_responseTimes2_value: "intentsDialog-data:sample-response-times_2",
card_responseTimes2_heading: "::In < 3 sec",
card_responseTimes2_color: "::#2979FF",
card_responseTimes2_icon: "::av_timer",
card_responseTimes3_value: "intentsDialog-data:sample-response-times_3",
card_responseTimes3_heading: "::In 3+",
card_responseTimes3_color: "::#2962FF",
card_responseTimes3_icon: "::av_timer"
},
actions: {
onConversationsClick: {
action: "dialog:conversations",
params: { title: "dialog_intentsDialog:title",intent: "dialog_intentsDialog:intent",queryspan: "dialog_intentsDialog:queryspan" }
}
}
},
{
id: "entity-usage",
type: "BarData",
title: "Entity count appearances in intent",
subtitle: "Entity usage and count for the selected intent",
size: { w: 3,h: 8 },
location: { x: 0,y: 1 },
dependencies: { values: "intentsDialog-data:entities-usage",bars: "intentsDialog-data:entities-usage-bars" },
props: { nameKey: "entityType" }
},
{
id: "response-statistics",
type: "BarData",
title: "Response Statistics",
subtitle: "Entity usage and count for the selected intent",
size: { w: 3,h: 8 },
location: { x: 3,y: 1 },
dependencies: { values: "intentsDialog-data:sample-response-types",bars: "intentsDialog-data:sample-response-types-bars" },
props: { nameKey: "name" }
}
]
},
{
id: "conversations",
width: "60%",
params: ["title","intent","queryspan"],
dataSources: [
{
id: "conversations-data",
type: "ApplicationInsights/Query",
dependencies: { intent: "dialog_conversations:intent",queryTimespan: "dialog_conversations:queryspan" },
params: {
table: "nflbot_CL",
queries: {
conversations: {
query: ({ intent }) => `
where recordType == "intent" and intentName == '${intent}' |
summarize count_intents=count(), maxTimestamp=max(timestamp) by conversationId |
order by maxTimestamp`,
mappings: { id: (val, row, idx) => `Conversation ${idx}` }
}
}
}
}
],
elements: [
{
id: "conversations-list",
type: "Table",
title: "Conversations",
size: { w: 12,h: 16 },
dependencies: { values: "conversations-data:conversations" },
props: {
hideBorders: true,
cols: [
{ header: "Conversation Id",field: "id" },
{ header: "Last Message",field: "maxTimestamp",type: "time",format: "MMM-DD HH:mm:ss" },
{ header: "Count",field: "count_intents" },
{ type: "button",value: "chat",click: "openMessagesDialog" }
]
},
actions: {
openMessagesDialog: {
action: "dialog:messages",
params: { title: "args:id",conversation: "args:conversationId",queryspan: "timespan:queryTimespan" }
}
}
}
]
},
{
id: "messages",
width: "50%",
params: ["title","conversation","queryspan"],
dataSources: [
{
id: "messages-data",
type: "ApplicationInsights/Query",
dependencies: { conversation: "dialog_messages:conversation",queryTimespan: "dialog_messages:queryspan" },
params: {
query: ({ conversation }) => ` customEvents` +
` | extend conversation = customDimensions.conversationId, intent=customDimensions.intent` +
` | where name in ("message.send", "message.received") and conversation == '${conversation}'` +
` | order by timestamp asc` +
` | project timestamp, eventName=name, message=customDimensions.text, customDimensions.userName, customDimensions.userId`
}
}
],
elements: [
{
id: "messages-list",
type: "Table",
title: "Messages",
size: { w: 12,h: 16 },
dependencies: { values: "messages-data" },
props: {
rowClassNameField: "eventName",
cols: [
{ header: "Timestamp",width: "50px",field: "timestamp",type: "time",format: "MMM-DD HH:mm:ss" },
{ header: "Message",field: "message" }
]
}
}
]
},
{
id: "errors",
width: "90%",
params: ["title","queryspan"],
dataSources: [
{
id: "errors-group",
type: "ApplicationInsights/Query",
dependencies: { queryTimespan: "dialog_errors:queryspan" },
params: {
query: () => ` exceptions` +
` | summarize error_count=count() by type, innermostMessage` +
` | project type, innermostMessage, error_count` +
` | order by error_count desc `
},
calculated: (state) => {
const { values } = state;
return {
groups: values
};
}
},
{
id: "errors-selection",
type: "ApplicationInsights/Query",
dependencies: { queryTimespan: "dialog_errors:queryspan",type: "args:type",innermostMessage: "args:innermostMessage" },
params: {
query: ({ type, innermostMessage }) => ` exceptions` +
` | where type == '${type}'` +
` | where innermostMessage == "${innermostMessage}"` +
` | extend conversationId=customDimensions["Conversation ID"]` +
` | project type, innermostMessage, handledAt, conversationId, operation_Id`
}
}
],
elements: [
{
id: "errors-list",
type: "SplitPanel",
title: "Errors",
size: { w: 12,h: 16 },
dependencies: { groups: "errors-group",values: "errors-selection" },
props: {
cols: [
{ header: "Type",field: "type",secondaryHeader: "Message",secondaryField: "innermostMessage" },
{ header: "Conversation Id",field: "conversationId",secondaryHeader: "Operation Id",secondaryField: "operation_Id" },
{ header: "HandledAt",field: "handledAt" },
{ type: "button",value: "more",click: "openErrorDetail" }
],
group: { field: "type",secondaryField: "innermostMessage",countField: "error_count" }
},
actions: {
select: {
action: "errors-selection:updateDependencies",
params: { title: "args:type",type: "args:type",innermostMessage: "args:innermostMessage",queryspan: "timespan:queryTimespan" }
},
openErrorDetail: {
action: "dialog:errordetail",
params: {
title: "args:operation_Id",
type: "args:type",
innermostMessage: "args:innermostMessage",
handledAt: "args:handledAt",
conversationId: "args:conversationId",
operation_Id: "args:operation_Id",
queryspan: "timespan:queryTimespan"
}
}
}
}
]
},
{
id: "errordetail",
width: "50%",
params: ["title","handledAt","type","operation_Id","queryspan"],
dataSources: [
{
id: "errordetail-data",
type: "ApplicationInsights/Query",
dependencies: { operation_Id: "dialog_errordetail:operation_Id",queryTimespan: "dialog_errordetail:queryspan" },
params: {
query: ({ operation_Id }) => ` exceptions` +
` | where operation_Id == '${operation_Id}'` +
` | extend conversationId=customDimensions["Conversation ID"]` +
` | project handledAt, type, innermostMessage, conversationId, operation_Id, timestamp, details `
}
}
],
elements: [
{
id: "errordetail-item",
type: "Detail",
title: "Error detail",
size: { w: 12,h: 16 },
dependencies: { values: "errordetail-data" },
props: {
cols: [
{ header: "Handle",field: "handledAt" },
{ header: "Type",field: "type" },
{ header: "Message",field: "innermostMessage" },
{ header: "Conversation ID",field: "conversationId" },
{ header: "Operation ID",field: "operation_Id" },
{ header: "Timestamp",field: "timestamp" },
{ header: "Details",field: "details" }
]
}
}
]
}
]
} | the_stack |
const mysql = require('mysql')
const pbkdf2 = require('pbkdf2')
const crypto = require('crypto')
const index = require('./index')
const jwt = require('jsonwebtoken')
const config = require('config')
import { FindUserResult, BlockGpsStat, MergedBlockGpsStat, MergeBlocksInput, WorkerShareStat, PoolStat, DatabaseGrinStat } from './types/types'
const util = require('util')
import { knex } from './index'
export const numberRounds = 656000
const jwtSecretKey = config.get('jwtSecretKey')
const maxBlockRange = config.get('maxBlockRange')
export const checkAuth = (req, res, next) => {
// console.log('inside checkAuth, req.token is: ', req.token)
try {
// console.log('req.token is: ', req.token)
const decoded: { id: number, username: string, iat: number, exp: number } = jwt.verify(req.token, jwtSecretKey)
// console.log('checkAuth decoded is: ', decoded)
req.userData = decoded
if (decoded.id !== parseInt(req.params.id)) {
// console.log('ids do not match')
res.json({ message: 'Cannot access that user data' }).end()
return
}
next()
} catch (e) {
console.log('checkAuth rejects: ', e)
return res.status(401).json({ message: e })
}
}
export const mergeBlocks = (results: MergeBlocksInput[] ): MergedBlockGpsStat[] => {
// console.log('a mergeBlocks result: ', results)
const output = []
results.forEach((resultsRow) => {
const index = output.findIndex(outputRow => outputRow.height === resultsRow.height)
// if it's a new row for the block
if (index === -1) {
const gps = [
{
edge_bits: resultsRow.edge_bits,
gps: resultsRow.gps
}
]
delete resultsRow.edge_bits
output.push({
...resultsRow,
gps
})
} else {
output[index].gps.push({
edge_bits: resultsRow.edge_bits,
gps: resultsRow.gps
})
}
})
// console.log('a mergeBlock output is: ', output[0])
return output
}
export const filterFields = (fields: string, results: Object[]): Object[] => {
const fieldsList = fields.split(',')
if (fieldsList.length > 0) {
const filteredResults = results.map((item) => {
let filteredItem = {}
fieldsList.forEach(field => {
filteredItem[field] = item[field]
})
return filteredItem
})
return filteredResults
}
}
// get the new format for the password hash based on the user row and entered password (result may not match db.extra1)
export const getNewPasswordHashFromFullPassword = (
userRow: FindUserResult, enteredPassword: string
): { modifiedPassword: string, fullHashedPassword: string} => {
const fullPassword = userRow.extra1 // grab the extra1 field
const salt = fullPassword.split('$')[3] // grab the salt portion
const derivedKey = crypto.pbkdf2Sync(enteredPassword, salt, numberRounds, 64, 'sha512') // derive the key from entered password
const modifiedPassword = derivedKey.toString('base64').toString().replace(/\=/g,'') // entered password hash put in acceptable format
const fullHashedPassword = `$6$rounds=${numberRounds}$${salt}$${modifiedPassword}` // final form from entered password
return ({ modifiedPassword, fullHashedPassword }) // return both formats
}
// creation of new password hash with new format, based on an entered password
export const createHashedPassword = (enteredPassword: string): Promise<{ modifiedPassword: string, fullHashedPassword: string }> => {
return new Promise((resolve, reject) => {
try {
const salt = crypto.randomBytes(16).toString('base64').replace(/\=/g,'')
const derivedKey = crypto.pbkdf2Sync(enteredPassword, salt, numberRounds, 64, 'sha512') // derive the key
const modifiedPassword = derivedKey.toString('base64').replace(/\=/g,'') // put in acceptable format
const fullHashedPassword = `$6$rounds=${numberRounds}$${salt}$${modifiedPassword}` // final form
resolve({ modifiedPassword, fullHashedPassword })
} catch (e) {
reject({ statusCode: 500, message: 'Password hashing error'})
}
})
}
export const aggregateShareCreditsFromUserStats = (sharesRows): { c29: number, c31: number} => {
// console.log('sharesRows item: ', sharesRows[0])
const credit = {
c29: 0,
c31: 0
}
sharesRows.forEach((row) => {
if (row.edge_bits === 29) {
const maximum = Math.max(29, row.secondary_scaling)
credit.c29 = credit.c29 + (row.valid * maximum)
} else if (row.edge_bits === 31) {
const weight = Math.pow(2, (1 + row.edge_bits - 24)) * row.edge_bits
credit.c31 = credit.c31 + (row.valid * weight)
}
})
return credit
}
export const aggregateShareCreditsFromPoolShares = (
sharesRows: Array<{ secondary_scaling: number, share_counts: null | string }>
): { c29: number, c31: number } => {
// console.log('aggregateShareCreditsFromPoolShares item is: ', aggregateShareCreditsFromPoolShares[0])
const credit = {
c29: 0,
c31: 0
}
sharesRows.forEach((row) => {
if (row.share_counts) {
const parsedShareCounts: { C29?: any, C31?: any } = JSON.parse(row.share_counts)
if (parsedShareCounts.C29) {
const maximum = Math.max(29, row.secondary_scaling)
credit.c29 = credit.c29 + (parsedShareCounts.C29.valid * maximum)
}
if (parsedShareCounts.C31) {
const weight = Math.pow(2, (1 + 31 - 24)) * 31
credit.c31 = credit.c31 + (parsedShareCounts.C31.valid * weight)
}
}
})
// console.log('aggregateShareCreditsFromPoolShares credit is: ', credit)
return credit
}
export const calculateCreditFromPoolStat = (row): number => {
let credit = {
c29: 0,
c31: 0
}
// console.log('row is: ', row)
if (row.share_counts) {
const shareCounts = JSON.parse(row.share_counts)
if (shareCounts.C29) {
const maximum = Math.max(29, row.secondary_scaling)
credit.c29 = credit.c29 + (shareCounts.C29.valid * maximum)
}
if (shareCounts.C31) {
const weight = Math.pow(2, (1 + 31 - 24)) * 31
credit.c31 = credit.c31 + (shareCounts.C31.valid * weight)
}
}
return credit.c29 + credit.c31
}
export const calculateBlockReward = (height: number, workerStats: WorkerShareStat[], poolStats: PoolStat[]) => {
// console.log('height is: ', height)
// console.log('workerStats: ', workerStats[0])
// console.log('poolStats: ', poolStats[0])
let aggregatedPoolCredit = 0
let aggregatedUserCredit = 0
poolStats.forEach(poolStat => {
if (poolStat.height <= height && poolStat.height > height - 59) {
aggregatedPoolCredit += calculateCreditFromPoolStat(poolStat)
}
})
workerStats.forEach(workerStat => {
if (workerStat.height <= height && workerStat.height > height - 59) {
const additionalCredit = calculateCreditFromUserStat(workerStat, workerStat.height)
aggregatedUserCredit += additionalCredit
// console.log('in calculateBlockReward and workerStat height is: ', workerStat.height, ' and additional credit is: ', additionalCredit)
}
})
if (aggregatedPoolCredit === 0) return 0
// console.log('height: ', height, ' aggregatedUserCredit: ', aggregatedUserCredit, ' aggregatedPoolCredit: ', aggregatedPoolCredit, 'portion: ', aggregatedUserCredit / aggregatedPoolCredit)
const portion = aggregatedUserCredit / aggregatedPoolCredit
const userReward = grinToNanoGrin(60) * portion
// console.log(height, ' userReward (block) is: ', userReward)
return userReward
}
export const calculateCreditFromUserStat = (row: WorkerShareStat, height: number): number => {
// console.log('calculatCreditFromUserStat row: ', row)
const credit = {
c29: 0,
c31: 0
}
if (row.share_edge_bits === 29) {
const maximum = Math.max(29, row.secondary_scaling)
credit.c29 += (row.valid * maximum)
} else if (row.share_edge_bits === 31) {
const weight = Math.pow(2, (1 + row.share_edge_bits - 24)) * row.share_edge_bits
credit.c31 += (row.valid * weight)
}
if (height === 104194) console.log('height 104194, ', 'row: ', row)
return credit.c29 + credit.c31
}
export const getLatestNetworkBlockHeight = (): Promise<number> => {
return new Promise((resolve, reject) => {
try {
index.cache.get('router_max_network_block_height', async (err, item: string) => {
let maxBlockHeight
if (err || !item) {
const maxBlockHeightResult = await knex('blocks').max({ height: 'height'}).limit(1)
maxBlockHeight = maxBlockHeightResult[0].height
index.cache.set('router_max_network_block_height', maxBlockHeight, 'EX', 20)
} else {
maxBlockHeight = parseInt(item)
}
resolve(maxBlockHeight)
})
} catch (e) {
throw { statusCode: 500, message: 'Error getting latest block height'}
}
})
}
export const getLatestPoolBlockHeight = (): Promise<number> => {
return new Promise((resolve, reject) => {
try {
index.cache.get('router_max_block_height', async (err, item) => {
let maxBlockHeight
if (err || !item) {
const maxBlockHeightResult = await knex('pool_blocks').max({ height: 'height'}).limit(1)
maxBlockHeight = maxBlockHeightResult[0].height
index.cache.set('router_max_pool_block_height', maxBlockHeight, 'EX', 20)
} else {
maxBlockHeight = parseInt(item)
}
resolve(maxBlockHeight)
})
} catch (e) {
throw { statusCode: 500, message: 'Error getting latest block height'}
}
})
}
export const limitRange = async (req, res, next) => {
// console.log('limitRange starting off with req.params.range: ', req.params.range)
const range: number = req.params.range
const maxRange = maxBlockRange
const defaultRange = maxBlockRange
let reducedRange = defaultRange
if (range) reducedRange = range
if (range > maxRange) reducedRange = maxRange
res.locals.range = range
// console.log('limitRange result is: ', range)
next()
}
export const sanitizeHeight = async (req, res, next) => {
// console.log('inside sanitizeHeight')
if (req.params && req.params.height && (parseInt(req.params.height) < 1)) {
// console.log('inside sanitizing height conditional')
index.cache.get(`router_/grin/block`, async (err, item: string) => {
// console.log('inside sanitizeHeight cache.get, err is: ', err)
if (err) throw { statusCode: 500, message: 'Could not retrieve max block height from cache'}
if (item) {
// console.log('inside sanitize height and found cached block')
const blockData = JSON.parse(item)
res.locals.block = blockData
next()
} else {
const maxHeightResult = await knex('blocks').select({ maxHeight: 'height' }).limit(1)
if (err) throw { statusCode: 500, message: 'Could not find max block height' }
// console.log('maxHeightResult: ', maxHeightResult)
const maxHeight = parseInt(maxHeightResult[0].maxHeight)
res.locals.height = maxHeight
index.cache.set(`router_/grin/block.height`, maxHeight, 'EX', 1)
// console.log('res.locals is: ', res.locals)
next()
}
})
} else {
next()
}
}
export const nanoGrinToGrin = (nanoGrin: number): number => {
return nanoGrin / 1000000000
}
export const grinToNanoGrin = (grin: number): number => {
return grin * 1000000000
} | the_stack |
import { AuditApp } from '../model/auditApp';
import { AuditAppPaging } from '../model/auditAppPaging';
import { AuditBodyUpdate } from '../model/auditBodyUpdate';
import { AuditEntryEntry } from '../model/auditEntryEntry';
import { AuditEntryPaging } from '../model/auditEntryPaging';
import { BaseApi } from './base.api';
import { throwIfNotDefined } from '../../../assert';
import { buildCollectionParam } from '../../../alfrescoApiClient';
/**
* Audit service.
* @module AuditApi
*/
export class AuditApi extends BaseApi {
/**
* Permanently delete audit entries for an audit application
*
* **Note:** this endpoint is available in Alfresco 5.2.2 and newer versions.
Permanently delete audit entries for an audit application **auditApplicationId**.
The **where** clause must be specified, either with an inclusive time period or for
an inclusive range of ids. The delete is within the context of the given audit application.
For example:
* where=(createdAt BETWEEN ('2017-06-02T12:13:51.593+01:00' , '2017-06-04T10:05:16.536+01:00')
* where=(id BETWEEN ('1234', '4321')
You must have admin rights to delete audit information.
*
* @param auditApplicationId The identifier of an audit application.
* @param where Audit entries to permanently delete for an audit application, given an inclusive time period or range of ids. For example:
* where=(createdAt BETWEEN ('2017-06-02T12:13:51.593+01:00' , '2017-06-04T10:05:16.536+01:00')
* where=(id BETWEEN ('1234', '4321')
* @return Promise<{}>
*/
deleteAuditEntriesForAuditApp(auditApplicationId: string, where: string): Promise<any> {
throwIfNotDefined(auditApplicationId, 'auditApplicationId');
throwIfNotDefined(where, 'where');
const postBody: null = null;
const pathParams = {
'auditApplicationId': auditApplicationId
};
const queryParams = {
'where': where
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/audit-applications/{auditApplicationId}/audit-entries', 'DELETE',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts );
}
/**
* Permanently delete an audit entry
*
* **Note:** this endpoint is available in Alfresco 5.2.2 and newer versions.
Permanently delete a single audit entry **auditEntryId**.
You must have admin rights to delete audit information.
*
* @param auditApplicationId The identifier of an audit application.
* @param auditEntryId The identifier of an audit entry.
* @return Promise<{}>
*/
deleteAuditEntry(auditApplicationId: string, auditEntryId: string): Promise<any> {
throwIfNotDefined(auditApplicationId, 'auditApplicationId');
throwIfNotDefined(auditEntryId, 'auditEntryId');
const postBody: null = null;
const pathParams = {
'auditApplicationId': auditApplicationId, 'auditEntryId': auditEntryId
};
const queryParams = {
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/audit-applications/{auditApplicationId}/audit-entries/{auditEntryId}', 'DELETE',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts );
}
/**
* Get audit application info
*
* **Note:** this endpoint is available in Alfresco 5.2.2 and newer versions.
Get status of an audit application **auditApplicationId**.
You must have admin rights to retrieve audit information.
You can use the **include** parameter to return the minimum and/or maximum audit record id for the application.
*
* @param auditApplicationId The identifier of an audit application.
* @param opts Optional parameters
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @param opts.include Also include the current minimum and/or maximum audit entry ids for the application. The following optional fields can be requested:
* max
* min
* @return Promise<AuditApp>
*/
getAuditApp(auditApplicationId: string, opts?: any): Promise<AuditApp> {
throwIfNotDefined(auditApplicationId, 'auditApplicationId');
opts = opts || {};
const postBody: null = null;
const pathParams = {
'auditApplicationId': auditApplicationId
};
const queryParams = {
'fields': buildCollectionParam(opts['fields'], 'csv'),
'include': buildCollectionParam(opts['include'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/audit-applications/{auditApplicationId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , AuditApp);
}
/**
* Get audit entry
*
* **Note:** this endpoint is available in Alfresco 5.2.2 and newer versions.
Gets audit entry **auditEntryId**.
You must have admin rights to access audit information.
*
* @param auditApplicationId The identifier of an audit application.
* @param auditEntryId The identifier of an audit entry.
* @param opts Optional parameters
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<AuditEntryEntry>
*/
getAuditEntry(auditApplicationId: string, auditEntryId: string, opts?: any): Promise<AuditEntryEntry> {
throwIfNotDefined(auditApplicationId, 'auditApplicationId');
throwIfNotDefined(auditEntryId, 'auditEntryId');
opts = opts || {};
const postBody: null = null;
const pathParams = {
'auditApplicationId': auditApplicationId, 'auditEntryId': auditEntryId
};
const queryParams = {
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/audit-applications/{auditApplicationId}/audit-entries/{auditEntryId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , AuditEntryEntry);
}
/**
* List audit applications
*
* **Note:** this endpoint is available in Alfresco 5.2.2 and newer versions.
Gets a list of audit applications in this repository.
This list may include pre-configured audit applications, if enabled, such as:
* alfresco-access
* CMISChangeLog
* Alfresco Tagging Service
* Alfresco Sync Service (used by Enterprise Cloud Sync)
You must have admin rights to retrieve audit information.
*
* @param opts Optional parameters
* @param opts.skipCount The number of entities that exist in the collection before those included in this list.
If not supplied then the default value is 0.
(default to 0)
* @param opts.maxItems The maximum number of items to return in the list.
If not supplied then the default value is 100.
(default to 100)
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<AuditAppPaging>
*/
listAuditApps(opts?: any): Promise<AuditAppPaging> {
opts = opts || {};
const postBody: null = null;
const pathParams = {
};
const queryParams = {
'skipCount': opts['skipCount'],
'maxItems': opts['maxItems'],
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/audit-applications', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , AuditAppPaging);
}
/**
* List audit entries for an audit application
*
* **Note:** this endpoint is available in Alfresco 5.2.2 and newer versions.
Gets a list of audit entries for audit application **auditApplicationId**.
You can use the **include** parameter to return additional **values** information.
The list can be filtered by one or more of:
* **createdByUser** person id
* **createdAt** inclusive time period
* **id** inclusive range of ids
* **valuesKey** audit entry values contains the exact matching key
* **valuesValue** audit entry values contains the exact matching value
The default sort order is **createdAt** ascending, but you can use an optional **ASC** or **DESC**
modifier to specify an ascending or descending sort order.
For example, specifying orderBy=createdAt DESC returns audit entries in descending **createdAt** order.
You must have admin rights to retrieve audit information.
*
* @param auditApplicationId The identifier of an audit application.
* @param opts Optional parameters
* @param opts.skipCount The number of entities that exist in the collection before those included in this list.
If not supplied then the default value is 0.
(default to 0)
* @param opts.orderBy A string to control the order of the entities returned in a list. You can use the **orderBy** parameter to
sort the list by one or more fields.
Each field has a default sort order, which is normally ascending order. Read the API method implementation notes
above to check if any fields used in this method have a descending default search order.
To sort the entities in a specific order, you can use the **ASC** and **DESC** keywords for any field.
* @param opts.maxItems The maximum number of items to return in the list.
If not supplied then the default value is 100.
(default to 100)
* @param opts.where Optionally filter the list. Here are some examples:
* where=(createdByUser='jbloggs')
* where=(id BETWEEN ('1234', '4321')
* where=(createdAt BETWEEN ('2017-06-02T12:13:51.593+01:00' , '2017-06-04T10:05:16.536+01:00')
* where=(createdByUser='jbloggs' and createdAt BETWEEN ('2017-06-02T12:13:51.593+01:00' , '2017-06-04T10:05:16.536+01:00')
* where=(valuesKey='/alfresco-access/login/user')
* where=(valuesKey='/alfresco-access/transaction/action' and valuesValue='DELETE')
* @param opts.include Returns additional information about the audit entry. The following optional fields can be requested:
* values
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<AuditEntryPaging>
*/
listAuditEntriesForAuditApp(auditApplicationId: string, opts?: any): Promise<AuditEntryPaging> {
throwIfNotDefined(auditApplicationId, 'auditApplicationId');
opts = opts || {};
const postBody: null = null;
const pathParams = {
'auditApplicationId': auditApplicationId
};
const queryParams = {
'skipCount': opts['skipCount'],
'orderBy': buildCollectionParam(opts['orderBy'], 'csv'),
'maxItems': opts['maxItems'],
'where': opts['where'],
'include': buildCollectionParam(opts['include'], 'csv'),
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/audit-applications/{auditApplicationId}/audit-entries', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , AuditEntryPaging);
}
/**
* List audit entries for a node
*
* **Note:** this endpoint is available in Alfresco 5.2.2 and newer versions.
Gets a list of audit entries for node **nodeId**.
The list can be filtered by **createdByUser** and for a given inclusive time period.
The default sort order is **createdAt** ascending, but you can use an optional **ASC** or **DESC**
modifier to specify an ascending or descending sort order.
For example, specifying orderBy=createdAt DESC returns audit entries in descending **createdAt** order.
This relies on the pre-configured 'alfresco-access' audit application.
*
* @param nodeId The identifier of a node.
* @param opts Optional parameters
* @param opts.skipCount The number of entities that exist in the collection before those included in this list.
If not supplied then the default value is 0.
(default to 0)
* @param opts.orderBy A string to control the order of the entities returned in a list. You can use the **orderBy** parameter to
sort the list by one or more fields.
Each field has a default sort order, which is normally ascending order. Read the API method implementation notes
above to check if any fields used in this method have a descending default search order.
To sort the entities in a specific order, you can use the **ASC** and **DESC** keywords for any field.
* @param opts.maxItems The maximum number of items to return in the list.
If not supplied then the default value is 100.
(default to 100)
* @param opts.where Optionally filter the list. Here are some examples:
* where=(createdByUser='-me-')
* where=(createdAt BETWEEN ('2017-06-02T12:13:51.593+01:00' , '2017-06-04T10:05:16.536+01:00')
* where=(createdByUser='jbloggs' and createdAt BETWEEN ('2017-06-02T12:13:51.593+01:00' , '2017-06-04T10:05:16.536+01:00')
* @param opts.include Returns additional information about the audit entry. The following optional fields can be requested:
* values
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<AuditEntryPaging>
*/
listAuditEntriesForNode(nodeId: string, opts?: any): Promise<AuditEntryPaging> {
throwIfNotDefined(nodeId, 'nodeId');
opts = opts || {};
const postBody: null = null;
const pathParams = {
'nodeId': nodeId
};
const queryParams = {
'skipCount': opts['skipCount'],
'orderBy': buildCollectionParam(opts['orderBy'], 'csv'),
'maxItems': opts['maxItems'],
'where': opts['where'],
'include': buildCollectionParam(opts['include'], 'csv'),
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/nodes/{nodeId}/audit-entries', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , AuditEntryPaging);
}
/**
* Update audit application info
*
* **Note:** this endpoint is available in Alfresco 5.2.2 and newer versions.
Disable or re-enable the audit application **auditApplicationId**.
New audit entries will not be created for a disabled audit application until
it is re-enabled (and system-wide auditing is also enabled).
Note, it is still possible to query &/or delete any existing audit entries even
if auditing is disabled for the audit application.
You must have admin rights to update audit application.
*
* @param auditApplicationId The identifier of an audit application.
* @param auditAppBodyUpdate The audit application to update.
* @param opts Optional parameters
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<AuditApp>
*/
updateAuditApp(auditApplicationId: string, auditAppBodyUpdate: AuditBodyUpdate, opts?: any): Promise<AuditApp> {
throwIfNotDefined(auditApplicationId, 'auditApplicationId');
throwIfNotDefined(auditAppBodyUpdate, 'auditAppBodyUpdate');
opts = opts || {};
const postBody = auditAppBodyUpdate;
const pathParams = {
'auditApplicationId': auditApplicationId
};
const queryParams = {
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/audit-applications/{auditApplicationId}', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , AuditApp);
}
} | the_stack |
import * as chai from 'chai';
import * as spies from 'chai-spies';
import * as os from 'os';
import { resolve } from 'path';
import { commands, Position, Range, Selection, Uri, window } from 'vscode';
import * as capitalizationOfMetadata from '../../../../controllers/cleanup/capitalizationOfMetadata';
import {
applyCleanup,
applyCleanupCommand,
applyCleanupFile,
applyCleanupFolder
} from '../../../../controllers/cleanup/cleanup-controller';
import * as singleValuedMetadata from '../../../../controllers/cleanup/handleSingleValuedMetadata';
import * as microsoftLinks from '../../../../controllers/cleanup/microsoftLinks';
import * as removeEmptyMetadata from '../../../../controllers/cleanup/removeEmptyMetadata';
import * as utilities from '../../../../controllers/cleanup/utilities';
import * as masterRedirection from '../../../../controllers/redirects/generateRedirectionFile';
import * as common from '../../../../helper/common';
import * as telemetry from '../../../../helper/telemetry';
import {
expectStringsToEqual,
extendedSleepTime,
loadDocumentAndGetItReady,
sleep,
sleepTime
} from '../../../test.common/common';
chai.use(spies);
import sinon = require('sinon');
const expect = chai.expect;
const filePath = resolve(
__dirname,
'../../../../../../src/test/data/repo/articles/docs-markdown.md'
);
const folderPath = resolve(__dirname, '../../../../../../src/test/data/repo/articles');
suite('Cleanup Controller', () => {
suiteSetup(async () => {
sinon.stub(telemetry, 'sendTelemetryData');
});
// Reset and tear down the spies
teardown(() => {
chai.spy.restore(common);
});
suiteTeardown(async () => {
await commands.executeCommand('workbench.action.closeAllEditors');
sinon.restore();
});
test('cleanup repo - applyCleanupCommand', () => {
const controllerCommands = [{ command: applyCleanup.name, callback: applyCleanup }];
expect(applyCleanupCommand()).to.deep.equal(controllerCommands);
});
test('cleanup repo - getCleanUpQuickPick', async () => {
const spy = chai.spy.on(utilities, 'getCleanUpQuickPick');
const stubShowQuickPick = sinon.stub(window, 'showQuickPick' as any);
stubShowQuickPick.onCall(0).resolves('');
await applyCleanup();
await sleep(sleepTime);
expect(spy).to.have.been.called();
stubShowQuickPick.restore();
});
test('cleanup repo - noActiveEditorMessage', async () => {
const spy = chai.spy.on(common, 'noActiveEditorMessage');
const stubShowQuickPick = sinon.stub(window, 'showQuickPick' as any);
stubShowQuickPick.onCall(0).resolves('selection');
await applyCleanup();
await sleep(sleepTime);
expect(spy).to.have.been.called();
stubShowQuickPick.restore();
});
test('cleanup repo - master redirection file', async () => {
await loadDocumentAndGetItReady(filePath);
const stubShowQuickPick = sinon.stub(window, 'showQuickPick');
stubShowQuickPick.onCall(0).resolves({ label: 'master redirection file', detail: '' });
const spy = chai.spy.on(masterRedirection, 'generateMasterRedirectionFile');
await applyCleanup();
await sleep(sleepTime);
stubShowQuickPick.restore();
expect(spy).to.have.been.called();
});
test('cleanup folder - single-valued metadata (recursive folders)', async () => {
const stubShowQuickPick = sinon.stub(window, 'showQuickPick');
stubShowQuickPick.onCall(0).resolves({ label: 'single-valued metadata', detail: '' });
const markdown = resolve(
__dirname,
'../../../../../../src/test/data/repo/articles/test/cleanup-test.md'
);
await loadDocumentAndGetItReady(markdown);
await applyCleanupFolder(
Uri.file(resolve(__dirname, '../../../../../../src/test/data/repo/articles/test'))
);
await sleep(400);
const actualText = window.activeTextEditor?.document.getText();
const expectedText = '---' + os.EOL + 'ms.author: "foo"' + os.EOL + '---' + os.EOL;
// cleanup the modified *.md to prevent false positives for future tests.
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { exec } = require('child_process');
exec('cd ' + __dirname + ' && git checkout ' + markdown);
chai.assert.equal(expectedText, actualText);
stubShowQuickPick.restore();
});
test('cleanup repo - recurseCallback - microsoft links', async () => {
await loadDocumentAndGetItReady(filePath);
const stubShowQuickPick = sinon.stub(window, 'showQuickPick');
stubShowQuickPick.onCall(0).resolves({ label: 'microsoft links', detail: '' });
const spy = chai.spy.on(utilities, 'recurseCallback');
await applyCleanup();
expect(spy).to.have.been.called();
stubShowQuickPick.restore();
});
test('cleanup repo - recurseCallback - capitalization of metadata values', async () => {
await loadDocumentAndGetItReady(filePath);
const stubShowQuickPick = sinon.stub(window, 'showQuickPick');
stubShowQuickPick
.onCall(0)
.resolves({ label: 'capitalization of metadata values', detail: '' });
const spy = chai.spy.on(utilities, 'recurseCallback');
await applyCleanup();
expect(spy).to.have.been.called();
stubShowQuickPick.restore();
});
test('cleanup repo - empty metadata - empty values', async () => {
await loadDocumentAndGetItReady(filePath);
const mockShowQuickPick = sinon.stub(window, 'showQuickPick');
mockShowQuickPick.onFirstCall().resolves({ label: 'empty metadata', detail: '' });
mockShowQuickPick
.onSecondCall()
.resolves({ label: 'remove metadata attributes with empty values', detail: '' });
const spy = chai.spy.on(removeEmptyMetadata, 'removeEmptyMetadata');
await applyCleanup();
await sleep(extendedSleepTime);
expect(spy).to.have.been.called();
mockShowQuickPick.restore();
});
test('cleanup repo - empty metadata - n/a', async () => {
await loadDocumentAndGetItReady(filePath);
const mockShowQuickPick = sinon.stub(window, 'showQuickPick');
mockShowQuickPick.onFirstCall().resolves({ label: 'empty metadata', detail: '' });
mockShowQuickPick
.onSecondCall()
.resolves({ label: `remove metadata attributes with "na" or "n/a"`, detail: '' });
const spy = chai.spy.on(removeEmptyMetadata, 'removeEmptyMetadata');
await applyCleanup();
await sleep(extendedSleepTime);
mockShowQuickPick.restore();
expect(spy).to.have.been.called();
});
test('cleanup repo - empty metadata - commented', async () => {
await loadDocumentAndGetItReady(filePath);
const mockShowQuickPick = sinon.stub(window, 'showQuickPick');
mockShowQuickPick.onFirstCall().resolves({ label: 'empty metadata', detail: '' });
mockShowQuickPick
.onSecondCall()
.resolves({ label: 'remove commented out metadata attributes', detail: '' });
const spy = chai.spy.on(removeEmptyMetadata, 'removeEmptyMetadata');
await applyCleanup();
await sleep(extendedSleepTime);
mockShowQuickPick.restore();
expect(spy).to.have.been.called();
});
test('cleanup repo - empty metadata - all', async () => {
await loadDocumentAndGetItReady(filePath);
const mockShowQuickPick = sinon.stub(window, 'showQuickPick');
mockShowQuickPick.onFirstCall().resolves({ label: 'empty metadata', detail: '' });
mockShowQuickPick.onSecondCall().resolves({ label: 'remove all', detail: '' });
const spy = chai.spy.on(removeEmptyMetadata, 'removeEmptyMetadata');
await applyCleanup();
await sleep(extendedSleepTime);
mockShowQuickPick.restore();
expect(spy).to.have.been.called();
});
test('cleanup file - getCleanUpQuickPick', async () => {
const spy = chai.spy.on(utilities, 'getCleanUpQuickPick');
const stubShowQuickPick = sinon.stub(window, 'showQuickPick' as any);
stubShowQuickPick.onCall(0).resolves('');
await applyCleanupFile(Uri.file(filePath));
expect(spy).to.have.been.called();
stubShowQuickPick.restore();
});
test('cleanup file - single-valued metadata', async () => {
const stubShowQuickPick = sinon.stub(window, 'showQuickPick');
stubShowQuickPick.onCall(0).resolves({ label: 'single-valued metadata', detail: '' });
const spy = chai.spy.on(singleValuedMetadata, 'handleSingleValuedMetadata');
await applyCleanupFile(Uri.file(filePath));
expect(spy).to.have.been.called();
stubShowQuickPick.restore();
});
test('cleanup file - microsoft links', async () => {
const stubShowQuickPick = sinon.stub(window, 'showQuickPick');
stubShowQuickPick.onCall(0).resolves({ label: 'microsoft links', detail: '' });
const spy = chai.spy.on(microsoftLinks, 'microsoftLinks');
await applyCleanupFile(Uri.file(filePath));
expect(spy).to.have.been.called();
stubShowQuickPick.restore();
});
test('cleanup file - capitalization of metadata values', async () => {
const stubShowQuickPick = sinon.stub(window, 'showQuickPick');
stubShowQuickPick
.onCall(0)
.resolves({ label: 'capitalization of metadata values', detail: '' });
const spy = chai.spy.on(capitalizationOfMetadata, 'capitalizationOfMetadata');
await applyCleanupFile(Uri.file(filePath));
expect(spy).to.have.been.called();
stubShowQuickPick.restore();
});
test('cleanup file - empty metadata - empty values', async () => {
const mockShowQuickPick = sinon.stub(window, 'showQuickPick');
mockShowQuickPick.onFirstCall().resolves({ label: 'empty metadata', detail: '' });
mockShowQuickPick
.onSecondCall()
.resolves({ label: 'remove metadata attributes with empty values', detail: '' });
const spy = chai.spy.on(removeEmptyMetadata, 'removeEmptyMetadata');
await applyCleanupFile(Uri.file(filePath));
mockShowQuickPick.restore();
expect(spy).to.have.been.called();
});
test('cleanup file - empty metadata - n/a', async () => {
const mockShowQuickPick = sinon.stub(window, 'showQuickPick');
mockShowQuickPick.onFirstCall().resolves({ label: 'empty metadata', detail: '' });
mockShowQuickPick
.onSecondCall()
.resolves({ label: `remove metadata attributes with "na" or "n/a"`, detail: '' });
const spy = chai.spy.on(removeEmptyMetadata, 'removeEmptyMetadata');
await applyCleanupFile(Uri.file(filePath));
mockShowQuickPick.restore();
expect(spy).to.have.been.called();
});
test('cleanup file - empty metadata - commented', async () => {
const mockShowQuickPick = sinon.stub(window, 'showQuickPick');
mockShowQuickPick.onFirstCall().resolves({ label: 'empty metadata', detail: '' });
mockShowQuickPick
.onSecondCall()
.resolves({ label: 'remove commented out metadata attributes', detail: '' });
const spy = chai.spy.on(removeEmptyMetadata, 'removeEmptyMetadata');
await applyCleanupFile(Uri.file(filePath));
mockShowQuickPick.restore();
expect(spy).to.have.been.called();
});
test('cleanup file - empty metadata - all', async () => {
const mockShowQuickPick = sinon.stub(window, 'showQuickPick');
mockShowQuickPick.onFirstCall().resolves({ label: 'empty metadata', detail: '' });
mockShowQuickPick.onSecondCall().resolves({ label: 'remove all', detail: '' });
const spy = chai.spy.on(removeEmptyMetadata, 'removeEmptyMetadata');
await applyCleanupFile(Uri.file(filePath));
mockShowQuickPick.restore();
expect(spy).to.have.been.called();
});
test('cleanup folder - getCleanUpQuickPick', async () => {
const spy = chai.spy.on(utilities, 'getCleanUpQuickPick');
const stubShowQuickPick = sinon.stub(window, 'showQuickPick' as any);
stubShowQuickPick.onCall(0).resolves('');
await applyCleanupFolder(Uri.file(folderPath));
expect(spy).to.have.been.called();
stubShowQuickPick.restore();
});
test('cleanup folder - single-valued metadata', async () => {
const mockShowQuickPick = sinon.stub(window, 'showQuickPick');
mockShowQuickPick.onFirstCall().resolves({ label: 'single-valued metadata', detail: '' });
const spy = chai.spy.on(singleValuedMetadata, 'handleSingleValuedMetadata');
await applyCleanupFolder(Uri.file(folderPath));
await sleep(extendedSleepTime);
expect(spy).to.have.been.called();
mockShowQuickPick.restore();
});
test('cleanup folder - microsoft links', async () => {
const mockShowQuickPick = sinon.stub(window, 'showQuickPick');
mockShowQuickPick.onFirstCall().resolves({ label: 'microsoft links', detail: '' });
const spy = chai.spy.on(microsoftLinks, 'microsoftLinks');
await applyCleanupFolder(Uri.file(folderPath));
await sleep(extendedSleepTime);
expect(spy).to.have.been.called();
mockShowQuickPick.restore();
});
test('cleanup folder - capitalization of metadata values', async () => {
const mockShowQuickPick = sinon.stub(window, 'showQuickPick');
mockShowQuickPick
.onFirstCall()
.resolves({ label: 'capitalization of metadata values', detail: '' });
const spy = chai.spy.on(capitalizationOfMetadata, 'capitalizationOfMetadata');
await applyCleanupFolder(Uri.file(folderPath));
await sleep(extendedSleepTime);
expect(spy).to.have.been.called();
mockShowQuickPick.restore();
});
test('cleanup folder - empty metadata - empty values', async () => {
const mockShowQuickPick = sinon.stub(window, 'showQuickPick');
mockShowQuickPick.onFirstCall().resolves({ label: 'empty metadata', detail: '' });
mockShowQuickPick
.onSecondCall()
.resolves({ label: 'remove metadata attributes with empty values', detail: '' });
const spy = chai.spy.on(removeEmptyMetadata, 'removeEmptyMetadata');
await applyCleanupFolder(Uri.file(folderPath));
await sleep(extendedSleepTime);
mockShowQuickPick.restore();
expect(spy).to.have.been.called();
});
test('cleanup folder - empty metadata - n/a', async () => {
const mockShowQuickPick = sinon.stub(window, 'showQuickPick');
mockShowQuickPick.onFirstCall().resolves({ label: 'empty metadata', detail: '' });
mockShowQuickPick
.onSecondCall()
.resolves({ label: `remove metadata attributes with "na" or "n/a"`, detail: '' });
const spy = chai.spy.on(removeEmptyMetadata, 'removeEmptyMetadata');
await applyCleanupFolder(Uri.file(folderPath));
await sleep(extendedSleepTime);
mockShowQuickPick.restore();
expect(spy).to.have.been.called();
});
test('cleanup folder - empty metadata - commented', async () => {
const mockShowQuickPick = sinon.stub(window, 'showQuickPick');
mockShowQuickPick.onFirstCall().resolves({ label: 'empty metadata', detail: '' });
mockShowQuickPick
.onSecondCall()
.resolves({ label: 'remove commented out metadata attributes', detail: '' });
const spy = chai.spy.on(removeEmptyMetadata, 'removeEmptyMetadata');
await applyCleanupFolder(Uri.file(folderPath));
await sleep(extendedSleepTime);
mockShowQuickPick.restore();
expect(spy).to.have.been.called();
});
test('cleanup folder - empty metadata - all', async () => {
const mockShowQuickPick = sinon.stub(window, 'showQuickPick');
mockShowQuickPick.onFirstCall().resolves({ label: 'empty metadata', detail: '' });
mockShowQuickPick.onSecondCall().resolves({ label: 'remove all', detail: '' });
const spy = chai.spy.on(removeEmptyMetadata, 'removeEmptyMetadata');
await applyCleanupFolder(Uri.file(folderPath));
await sleep(extendedSleepTime);
mockShowQuickPick.restore();
expect(spy).to.have.been.called();
});
test('dirty doc - skips cleanup', async () => {
const stubShowQuickPick = sinon.stub(window, 'showQuickPick');
stubShowQuickPick.onCall(0).resolves({ label: 'single-valued metadata', detail: '' });
const markdown = resolve(
__dirname,
'../../../../../../src/test/data/repo/markdown-stubs/cleanup-test.md'
);
await loadDocumentAndGetItReady(markdown);
const editor = window.activeTextEditor;
const content = 'some_content';
await common.insertContentToEditor(
editor,
content,
true,
new Selection(new Position(5, 0), new Position(5, 6))
);
await applyCleanupFolder(
Uri.file(resolve(__dirname, '../../../../../../src/test/data/repo/markdown-stubs'))
);
await sleep(500);
const actualText = window.activeTextEditor?.document.getText();
const expectedText = '---' + os.EOL + 'ms.author: ["foo"]' + os.EOL + '---' + os.EOL + content;
// cleanup the modified *.md to prevent false positives for future tests.
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { exec } = require('child_process');
exec('cd ' + __dirname + ' && git checkout ' + markdown);
expectStringsToEqual(expectedText, actualText);
stubShowQuickPick.restore();
});
}); | the_stack |
import log from "loglevel";
const rPlural = /(children|ies|ves|oes|ses|ches|shes|xes|s)$/i;
const mSingular: { [key: string]: string | number } = {
children: -3,
ies: "y",
ves: "f",
oes: -2,
ses: -2,
ches: -2,
shes: -2,
xes: -2,
s: -1,
};
function collectClassInfo(metadata: ClassInfo, className: string) {
// mostly rewritten in TypeScript based on lines 732-988 in https://github.com/SAP/openui5/blob/master/lib/jsdoc/ui5/plugin.js
const classDoclet: ClassDoclet = null; // TODO
/*
let baseType;
if ( classDoclet && classDoclet.augments && classDoclet.augments.length === 1 ) {
baseType = classDoclet.augments[0];
}
if ( extendCall.callee.type === Syntax.MemberExpression ) {
const baseCandidate = getResolvedObjectName(extendCall.callee.object);
if ( baseCandidate && baseType == null ) {
baseType = baseCandidate;
} else if ( baseCandidate !== baseType ) {
log.warn(`documented base type '${baseType}' doesn't match technical base type '${baseCandidate}'`);
}
}
*/
const oClassInfo: ClassInfo = {
name: className, // was: extendCall.arguments[0].value,
//baseType : baseType,
interfaces: [],
doc: classDoclet && classDoclet.description,
deprecation: classDoclet && classDoclet.deprecated,
since: classDoclet && classDoclet.since,
experimental: classDoclet && classDoclet.experimental,
specialSettings: {},
properties: {},
aggregations: {},
associations: {},
events: {},
methods: {},
annotations: {},
designtime: false,
designTime: false,
stereotype: null,
metadataClass: undefined,
defaultProperty: undefined,
defaultAggregation: undefined,
abstract: false,
final: false,
library: undefined,
};
function upper(n: string) {
return n.slice(0, 1).toUpperCase() + n.slice(1);
}
function each<APIMemberType extends APIMember>(
map: { [key: string]: APIMember },
defaultKey: string,
callback: (
n: string,
settings: APIMemberType,
doc: ClassDoclet,
apiMember: APIMember
) => void
) {
if (map) {
for (const n in map) {
if (Object.prototype.hasOwnProperty.call(map, n)) {
//const doclet = getLeadingDoclet(map[n]);
const settings = expandDefaultKey(map[n], defaultKey); // in simple cases just a string is given; this expands the string to a real configuration object
if (settings == null) {
log.warn(`no valid metadata for ${n} (AST type '${map[n].name}')`);
continue;
}
callback(
n,
settings as APIMemberType,
null /* was: doclet */,
map[n]
);
}
}
}
}
/*
if ( extendCall.arguments.length > 2 ) {
// new class defines its own metadata class type
const metadataClass = getResolvedObjectName(extendCall.arguments[2]);
if ( metadataClass ) {
oClassInfo.metadataClass = getResolvedObjectName(extendCall.arguments[2]);
debug(`found metadata class name '${oClassInfo.metadataClass}'`);
} else {
future(`cannot understand metadata class parameter (AST node type '${extendCall.arguments[2].type}')`);
}
}
const classInfoNode = extendCall.arguments[1];
const classInfoMap = createPropertyMap(classInfoNode);
if ( classInfoMap && classInfoMap.metadata && classInfoMap.metadata.value.type !== Syntax.ObjectExpression ) {
warning(`class metadata exists but can't be analyzed. It is not of type 'ObjectExpression', but a '${classInfoMap.metadata.value.type}'.`);
return null;
}
const metadata = classInfoMap && classInfoMap.metadata && createPropertyMap(classInfoMap.metadata.value);
*/
if (metadata) {
//log.debug(` analyzing metadata for '${oClassInfo.name}'`);
// Read the stereotype information from the metadata
oClassInfo.stereotype =
(metadata.stereotype && metadata.stereotype) || undefined;
oClassInfo.library = (metadata.library && metadata.library) || undefined;
oClassInfo["abstract"] = !!(metadata["abstract"] && metadata["abstract"]);
oClassInfo["final"] = !!(metadata["final"] && metadata["final"]);
//oClassInfo.dnd = metadata.dnd && convertDragDropValue(metadata.dnd);
if (metadata.interfaces) {
oClassInfo.interfaces = metadata.interfaces;
}
each<SpecialSetting>(
metadata.specialSettings,
"type",
(n, settings, doclet: ClassDoclet) => {
oClassInfo.specialSettings[n] = {
name: n,
doc: doclet && doclet.description,
since: doclet && doclet.since,
deprecation: doclet && doclet.deprecated,
experimental: doclet && doclet.experimental,
visibility: (settings.visibility && settings.visibility) || "public",
type: settings.type ? settings.type : "any",
};
}
);
oClassInfo.defaultProperty =
(metadata.defaultProperty && metadata.defaultProperty) || undefined;
each<Property>(
metadata.properties,
"type",
(n: string, settings, doclet: ClassDoclet) => {
const N = upper(n);
let methods: { [key: string]: string };
oClassInfo.properties[n] = {
name: n,
doc: doclet && doclet.description,
since: doclet && doclet.since,
deprecation: doclet && doclet.deprecated,
experimental: doclet && doclet.experimental,
visibility: settings.visibility || "public",
type: settings.type || "string",
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
defaultValue: settings.defaultValue, // ? convertValueWithRaw(settings.defaultValue, type, n) : null,
bindable: settings.bindable ? !!settings.bindable : false,
methods: (methods = {
get: "get" + N,
set: "set" + N,
}),
};
if (oClassInfo.properties[n].bindable) {
methods["bind"] = "bind" + N;
methods["unbind"] = "unbind" + N;
}
// if ( !settings.defaultValue ) {
// log.debug("property without defaultValue: " + oClassInfo.name + "." + n);
//}
}
);
oClassInfo.defaultAggregation =
(metadata.defaultAggregation && metadata.defaultAggregation) || undefined;
each<AggregationMetadata>(
metadata.aggregations,
"type",
(n: string, settings: AggregationMetadata, doclet: ClassDoclet) => {
const N = upper(n);
let methods: { [key: string]: string };
const aggr = (oClassInfo.aggregations[n] = {
name: n,
doc: doclet && doclet.description,
deprecation: doclet && doclet.deprecated,
since: doclet && doclet.since,
experimental: doclet && doclet.experimental,
visibility: (settings.visibility && settings.visibility) || "public",
type: settings.type ? settings.type : "sap.ui.core.Control",
altTypes: settings.altTypes ? settings.altTypes : undefined,
singularName: settings.singularName
? settings.singularName
: guessSingularName(n),
cardinality:
settings.multiple !== undefined && !settings.multiple
? "0..1"
: "0..n",
bindable: settings.bindable, // TODO: was: ? !!convertValue(settings.bindable) : false,
methods: (methods = {
get: "get" + N,
destroy: "destroy" + N,
}),
});
//aggr.dnd = settings.dnd && convertDragDropValue(settings.dnd, aggr.cardinality);
if (aggr.cardinality === "0..1") {
methods["set"] = "set" + N;
} else {
const N1 = upper(aggr.singularName);
methods["insert"] = "insert" + N1;
methods["add"] = "add" + N1;
methods["remove"] = "remove" + N1;
methods["indexOf"] = "indexOf" + N1;
methods["removeAll"] = "removeAll" + N;
}
if (aggr.bindable) {
methods["bind"] = "bind" + N;
methods["unbind"] = "unbind" + N;
}
}
);
each<AssociationMetadata>(
metadata.associations,
"type",
(n: string, settings: AssociationMetadata, doclet: ClassDoclet) => {
const N = upper(n);
let methods: { [key: string]: string };
oClassInfo.associations[n] = {
name: n,
doc: doclet && doclet.description,
deprecation: doclet && doclet.deprecated,
since: doclet && doclet.since,
experimental: doclet && doclet.experimental,
visibility: (settings.visibility && settings.visibility) || "public",
type: settings.type ? settings.type : "sap.ui.core.Control",
singularName: settings.singularName
? settings.singularName
: guessSingularName(n),
cardinality: settings.multiple && settings.multiple ? "0..n" : "0..1",
methods: (methods = {
get: "get" + N,
}),
};
if (oClassInfo.associations[n].cardinality === "0..1") {
methods["set"] = "set" + N;
} else {
const N1 = upper(oClassInfo.associations[n].singularName);
methods["add"] = "add" + N1;
methods["remove"] = "remove" + N1;
methods["removeAll"] = "removeAll" + N;
}
}
);
each<UI5Event>(
metadata.events,
null,
(n: string, settings, doclet: ClassDoclet) => {
const N = upper(n);
const info: UI5Event = (oClassInfo.events[n] = {
name: n,
doc: doclet && doclet.description,
deprecation: doclet && doclet.deprecated,
since: doclet && doclet.since,
experimental: doclet && doclet.experimental,
visibility:
/* (settings.visibility && settings.visibility) || */ "public",
allowPreventDefault: !!(
settings.allowPreventDefault && settings.allowPreventDefault
),
enableEventBubbling: !!(
settings.enableEventBubbling && settings.enableEventBubbling
),
parameters: {},
methods: {
attach: "attach" + N,
detach: "detach" + N,
fire: "fire" + N,
},
});
each<SpecialSetting>(
settings.parameters,
"type",
(pName: string, pSettings, pDoclet: ClassDoclet) => {
info.parameters[pName] = {
name: pName,
doc: pDoclet && pDoclet.description,
deprecation: pDoclet && pDoclet.deprecated,
since: pDoclet && pDoclet.since,
experimental: pDoclet && pDoclet.experimental,
type: pSettings && pSettings.type ? pSettings.type : "",
};
}
);
}
);
const designtime = metadata.designtime || metadata.designTime; // convertValue removed
if (typeof designtime === "string" || typeof designtime === "boolean") {
oClassInfo.designtime = designtime;
}
// log.debug(oClassInfo.name + ":" + JSON.stringify(oClassInfo, null, " "));
}
/*
if (currentModule.defaultExport
&& currentModule.localNames[currentModule.defaultExport]
&& currentModule.localNames[currentModule.defaultExport].class === oClassInfo.name) {
// debug("class " + oClassInfo.name + " identified as default export of module " + currentModule.module);
oClassInfo.export = "";
} else if (currentModule.defaultExportClass
&& currentModule.defaultExportClass === oClassInfo.name) {
// debug("class " + oClassInfo.name + " identified as default export of module " + currentModule.module + " (immediate return)");
oClassInfo.export = "";
}
// remember class info by name
classInfos[oClassInfo.name] = oClassInfo;
*/
return oClassInfo;
}
/**
* When for simplicitly the metadata for an API member only consists of a string instead of a full configuration
* object, then this function inflates the string to a full configuration object.
* "defaultKey" determines as which property in the configuration object the string should be used.
* Example: an association is configured as "SampleControl". This function converts this to {type: "SampleControl"}.
*/
function expandDefaultKey(node: APIMember, defaultKey: string) {
if (node != null) {
// if, instead of an object literal only a string is given and there is a defaultKey, then wrap the literal
if (typeof node === "string" && defaultKey != null) {
const result: { [key: string]: never } = {};
result[defaultKey] = node;
return result;
}
}
return node;
}
function guessSingularName(sPluralName: string) {
return sPluralName.replace(rPlural, ($, sPlural: string) => {
const vRepl = mSingular[sPlural.toLowerCase()];
return typeof vRepl === "string" ? vRepl : sPlural.slice(0, vRepl);
});
}
export default collectClassInfo; | the_stack |
import { ApexExecutionOverlayResultCommandSuccess } from '../../../src/commands/apexExecutionOverlayResultCommand';
import { ApexHeapDump } from '../../../src/core';
// Rather than duplicate a large heapdump in multiple places just have a common function return it. The
// heap dump for triggers is ends up bring pretty large but there are only 3 Account records in here.
// This method contains the elements necessary to test the Trigger variables in the heapdump.
export function createHeapDumpResultForTriggers(): ApexHeapDump {
// This particular heapdump was taken after an insert. The Trigger booleans for isafter and isinsert will
// be true. isbefore, isdelete, isundelete and isupdate will be false. The Trigger.new and Trigger.newmap
// will both be populated with 3 Account objects.
const heapdump = new ApexHeapDump('some ID', 'Foo', '', 10);
heapdump.setOverlaySuccessResult({
HeapDump: {
extents: [
{
collectionType: null,
count: 3,
definition: [{}],
extent: [
{
address: '0x5f163c72',
size: 0,
symbols: null,
value: {
entry: [
{
keyDisplayValue: 'LastModifiedDate',
value: {
value: 'Mon Jul 30 15:02:51 GMT 2018'
}
},
{
keyDisplayValue: 'IsDeleted',
value: {
value: 'false'
}
},
{
keyDisplayValue: 'CleanStatus',
value: {
value: 'Pending'
}
},
{
keyDisplayValue: 'OwnerId',
value: {
value: '005xx000001Uta8AAC'
}
},
{
keyDisplayValue: 'CreatedById',
value: {
value: '005xx000001Uta8AAC'
}
},
{
keyDisplayValue: 'CreatedDate',
value: {
value: 'Mon Jul 30 15:02:51 GMT 2018'
}
},
{
keyDisplayValue: 'Id',
value: {
value: '001xx000003Dv3YAAS'
}
},
{
keyDisplayValue: 'LastModifiedById',
value: {
value: '005xx000001Uta8AAC'
}
},
{
keyDisplayValue: 'SystemModstamp',
value: {
value: 'Mon Jul 30 15:02:51 GMT 2018'
}
},
{
keyDisplayValue: 'Name',
value: {
value: 'okToDelete0'
}
},
{
keyDisplayValue: 'AccountNumber',
value: {
value: 'xxx'
}
}
]
}
},
{
address: '0xf1fabe',
size: 0,
symbols: null,
value: {
entry: [
{
keyDisplayValue: 'LastModifiedDate',
value: {
value: 'Mon Jul 30 15:02:51 GMT 2018'
}
},
{
keyDisplayValue: 'IsDeleted',
value: {
value: 'false'
}
},
{
keyDisplayValue: 'CleanStatus',
value: {
value: 'Pending'
}
},
{
keyDisplayValue: 'OwnerId',
value: {
value: '005xx000001Uta8AAC'
}
},
{
keyDisplayValue: 'CreatedById',
value: {
value: '005xx000001Uta8AAC'
}
},
{
keyDisplayValue: 'CreatedDate',
value: {
value: 'Mon Jul 30 15:02:51 GMT 2018'
}
},
{
keyDisplayValue: 'Id',
value: {
value: '001xx000003Dv3ZAAS'
}
},
{
keyDisplayValue: 'LastModifiedById',
value: {
value: '005xx000001Uta8AAC'
}
},
{
keyDisplayValue: 'SystemModstamp',
value: {
value: 'Mon Jul 30 15:02:51 GMT 2018'
}
},
{
keyDisplayValue: 'Name',
value: {
value: 'okToDelete1'
}
},
{
keyDisplayValue: 'AccountNumber',
value: {
value: 'xxx'
}
}
]
}
},
{
address: '0x76e9852b',
size: 0,
symbols: null,
value: {
entry: [
{
keyDisplayValue: 'LastModifiedDate',
value: {
value: 'Mon Jul 30 15:02:51 GMT 2018'
}
},
{
keyDisplayValue: 'IsDeleted',
value: {
value: 'false'
}
},
{
keyDisplayValue: 'CleanStatus',
value: {
value: 'Pending'
}
},
{
keyDisplayValue: 'OwnerId',
value: {
value: '005xx000001Uta8AAC'
}
},
{
keyDisplayValue: 'CreatedById',
value: {
value: '005xx000001Uta8AAC'
}
},
{
keyDisplayValue: 'CreatedDate',
value: {
value: 'Mon Jul 30 15:02:51 GMT 2018'
}
},
{
keyDisplayValue: 'Id',
value: {
value: '001xx000003Dv3aAAC'
}
},
{
keyDisplayValue: 'LastModifiedById',
value: {
value: '005xx000001Uta8AAC'
}
},
{
keyDisplayValue: 'SystemModstamp',
value: {
value: 'Mon Jul 30 15:02:51 GMT 2018'
}
},
{
keyDisplayValue: 'Name',
value: {
value: 'okToDelete2'
}
},
{
keyDisplayValue: 'AccountNumber',
value: {
value: 'xxx'
}
}
]
}
}
],
totalSize: 0,
typeName: 'Account'
},
{
collectionType: 'Account',
count: 1,
definition: [],
extent: [
{
address: '0x7ac2777',
size: 16,
symbols: ['Trigger.new'],
value: {
value: [
{
value: '0x5f163c72'
},
{
value: '0xf1fabe'
},
{
value: '0x76e9852b'
}
]
}
}
],
totalSize: 16,
typeName: 'List<Account>'
},
{
collectionType: 'Account',
count: 1,
definition: [],
extent: [
{
address: '0x4266fa43',
size: 16,
symbols: ['Trigger.newmap'],
value: {
entry: [
{
keyDisplayValue: '0x5c288675',
value: {
value: '0x5f163c72'
}
},
{
keyDisplayValue: '0x5db01cb1',
value: {
value: '0xf1fabe'
}
},
{
keyDisplayValue: '0x1872dffb',
value: {
value: '0x76e9852b'
}
}
]
}
}
],
totalSize: 16,
typeName: 'Map<Id,Account>'
},
{
collectionType: null,
count: 2,
definition: [
{
name: 'value',
type: 'Boolean'
}
],
extent: [
{
address: '0x10954bcf',
size: 5,
symbols: [
'Trigger.isbefore',
'Trigger.isdelete',
'Trigger.isundelete',
'Trigger.isupdate'
],
value: {
value: false
}
},
{
address: '0x63903543',
size: 5,
symbols: ['Trigger.isafter', 'Trigger.isinsert'],
value: {
value: true
}
}
],
totalSize: 10,
typeName: 'Boolean'
},
{
collectionType: null,
count: 5,
definition: [
{
name: 'stringValue',
type: 'char[]'
}
],
extent: [
{
address: '0x72488407',
size: 15,
symbols: null,
value: {
value: 'currentinstance'
}
},
{
address: '0x5f87e37c',
size: 10,
symbols: null,
value: {
value: 'targettype'
}
},
{
address: '0x5c288675',
size: 18,
symbols: null,
value: {
value: '001xx000003Dv3YAAS'
}
},
{
address: '0x5db01cb1',
size: 18,
symbols: null,
value: {
value: '001xx000003Dv3ZAAS'
}
},
{
address: '0x1872dffb',
size: 18,
symbols: null,
value: {
value: '001xx000003Dv3aAAC'
}
}
],
totalSize: 79,
typeName: 'String'
}
]
}
} as ApexExecutionOverlayResultCommandSuccess);
return heapdump;
}
// HeapDump with no String typename entries entries
export function createHeapDumpWithNoStringTypes(): ApexHeapDump {
const heapdump = new ApexHeapDump('some ID', 'Foo', '', 10);
heapdump.setOverlaySuccessResult({
HeapDump: {
extents: [
{
collectionType: null,
count: 1,
definition: [{}],
extent: [
{
address: '0x7c6064ee',
isStatic: false,
size: 4,
symbols: ['theDate'],
value: {
value: '2018-09-13 00:00:00'
}
}
],
totalSize: 4,
typeName: 'Date'
},
{
collectionType: null,
count: 1,
definition: [
{
name: 'value',
type: 'Boolean'
}
],
extent: [
{
address: '0x557be9a9',
isStatic: false,
size: 5,
symbols: ['theBoolean'],
value: {
value: true
}
}
],
totalSize: 5,
typeName: 'Boolean'
},
{
collectionType: null,
count: 1,
definition: [
{
name: 'value',
type: 'Double'
}
],
extent: [
{
address: '0x6b112109',
isStatic: false,
size: 12,
symbols: ['theDouble'],
value: {
value: 3.14159
}
}
],
totalSize: 12,
typeName: 'Double'
},
{
collectionType: null,
count: 1,
definition: [
{
name: 'value',
type: 'Double'
}
],
extent: [
{
address: '0x74cb38fc',
isStatic: false,
size: 8,
symbols: ['theInt'],
value: {
value: 5
}
}
],
totalSize: 8,
typeName: 'Integer'
},
{
collectionType: null,
count: 1,
definition: [
{
name: 'value',
type: 'Double'
}
],
extent: [
{
address: '0x538519dc',
isStatic: false,
size: 12,
symbols: ['theLong'],
value: {
value: 4271990
}
}
],
totalSize: 12,
typeName: 'Long'
},
{
collectionType: null,
count: 2,
definition: [
{
name: 'MyBoolean',
type: 'Boolean'
},
{
name: 'MyDate',
type: 'Date'
},
{
name: 'MyDouble',
type: 'Double'
},
{
name: 'MyInteger',
type: 'Integer'
},
{
name: 'MyLong',
type: 'Long'
}
],
extent: [
{
address: '0x3557adc7',
isStatic: false,
size: 32,
symbols: ['foo'],
value: {
entry: [
{
keyDisplayValue: 'MyBoolean',
value: {
value: false
}
},
{
keyDisplayValue: 'MyDate',
value: {
value: 'Thu Sep 13 00:00:00 GMT 2018'
}
},
{
keyDisplayValue: 'MyDouble',
value: {
value: 4.37559
}
},
{
keyDisplayValue: 'MyInteger',
value: {
value: 10
}
},
{
keyDisplayValue: 'MyLong',
value: {
value: 4271993
}
}
]
}
}
],
totalSize: 64,
typeName: 'SomeTypeName'
}
]
}
} as ApexExecutionOverlayResultCommandSuccess);
return heapdump;
}
// Heapdump with typeName string entries
export function createHeapDumpWithStrings(): ApexHeapDump {
const heapdump = new ApexHeapDump('some ID', 'Foo', '', 10);
heapdump.setOverlaySuccessResult({
HeapDump: {
extents: [
{
collectionType: null,
count: 2,
definition: [
{
name: 'stringValue',
type: 'char[]'
}
],
extent: [
{
address: '0x47a32f5b',
isStatic: false,
size: 104,
symbols: ['theString'],
value: {
value:
'This is a longer string that will certainly get truncated until we hit a checkpoint and inspect it_extra'
}
},
{
address: '0x6cda5efc',
isStatic: false,
size: 9,
symbols: null,
value: {
value: '9/13/2018'
}
}
],
totalSize: 113,
typeName: 'String'
}
]
}
} as ApexExecutionOverlayResultCommandSuccess);
return heapdump;
}
// Partial heapdump with a nested reference, used to verify both leaf reference
// parsing and putting a variable together from the leaves.
export function createHeapDumpWithNestedRefs(): ApexHeapDump {
const heapdump = new ApexHeapDump('some ID', 'Foo', '', 10);
heapdump.setOverlaySuccessResult({
HeapDump: {
extents: [
{
collectionType: null,
count: 2,
definition: [
{
name: 'innerVariable',
type: 'NonStaticClassWithVariablesToInspect'
},
{
name: 'MyBoolean',
type: 'Boolean'
},
{
name: 'MyDate',
type: 'Date'
},
{
name: 'MyDouble',
type: 'Double'
},
{
name: 'MyInteger',
type: 'Integer'
},
{
name: 'MyLong',
type: 'Long'
},
{
name: 'MyString',
type: 'String'
}
],
extent: [
{
address: '0x3557adc7',
isStatic: false,
size: 32,
symbols: ['foo'],
value: {
entry: [
{
keyDisplayValue: 'innerVariable',
value: {
value: '0x55260a7a'
}
},
{
keyDisplayValue: 'MyBoolean',
value: {
value: false
}
},
{
keyDisplayValue: 'MyDate',
value: {
value: 'Thu Sep 13 00:00:00 GMT 2018'
}
},
{
keyDisplayValue: 'MyDouble',
value: {
value: 4.37559
}
},
{
keyDisplayValue: 'MyInteger',
value: {
value: 10
}
},
{
keyDisplayValue: 'MyLong',
value: {
value: 4271993
}
},
{
keyDisplayValue: 'MyString',
value: {
value: '0x47a32f5b'
}
}
]
}
},
{
address: '0x55260a7a',
isStatic: false,
size: 32,
symbols: null,
value: {
entry: [
{
keyDisplayValue: 'innerVariable',
value: {
value: null
}
},
{
keyDisplayValue: 'MyBoolean',
value: {
value: true
}
},
{
keyDisplayValue: 'MyDate',
value: {
value: 'Thu Sep 13 00:00:00 GMT 2018'
}
},
{
keyDisplayValue: 'MyDouble',
value: {
value: 3.14159
}
},
{
keyDisplayValue: 'MyInteger',
value: {
value: 5
}
},
{
keyDisplayValue: 'MyLong',
value: {
value: 4271990
}
},
{
keyDisplayValue: 'MyString',
value: {
value: '0x6cda5efc'
}
}
]
}
}
],
totalSize: 64,
typeName: 'NonStaticClassWithVariablesToInspect'
},
{
collectionType: null,
count: 2,
definition: [
{
name: 'stringValue',
type: 'char[]'
}
],
extent: [
{
address: '0x47a32f5b',
isStatic: false,
size: 104,
symbols: ['theString'],
value: {
value:
'This is a longer string that will certainly get truncated until we hit a checkpoint and inspect it_extra'
}
},
{
address: '0x6cda5efc',
isStatic: false,
size: 9,
symbols: null,
value: {
value: '9/13/2018'
}
}
],
totalSize: 113,
typeName: 'String'
}
]
}
} as ApexExecutionOverlayResultCommandSuccess);
return heapdump;
}
// Partial heapdump with a circular reference
export function createHeapDumpWithCircularRefs(): ApexHeapDump {
const heapdump = new ApexHeapDump('some ID', 'Foo', '', 10);
heapdump.setOverlaySuccessResult({
HeapDump: {
className: 'CircularRefTest',
extents: [
{
collectionType: null,
count: 1,
definition: [
{
name: 'cfList',
type: 'List<CircularReference>'
},
{
name: 'someInt',
type: 'Integer'
}
],
extent: [
{
address: '0x717304ef',
isStatic: false,
size: 12,
symbols: ['cf1'],
value: {
entry: [
{
keyDisplayValue: 'cfList',
value: {
value: '0x614edc98'
}
},
{
keyDisplayValue: 'someInt',
value: {
value: 5
}
}
]
}
}
],
totalSize: 12,
typeName: 'CircularReference'
},
{
collectionType: 'CircularReference',
count: 1,
definition: [],
extent: [
{
address: '0x614edc98',
isStatic: false,
size: 8,
symbols: null,
value: {
value: [
{
value: '0x717304ef'
}
]
}
}
],
totalSize: 8,
typeName: 'List<CircularReference>'
}
]
}
} as ApexExecutionOverlayResultCommandSuccess);
return heapdump;
} | the_stack |
import * as fs from 'fs-extra';
import * as path from 'path';
import * as rimraf from 'rimraf';
import {
addFunction,
addLayer,
addOptData,
addOptFile,
amplifyPushAuth,
amplifyPushLayer,
amplifyStatus,
createNewProjectDir,
deleteProject,
deleteProjectDir,
ExecutionContext,
expectDeployedLayerDescription,
expectEphemeralDataIsUndefined,
expectEphemeralPermissions,
functionCloudInvoke,
getCurrentLayerArnFromMeta,
getLayerDirectoryName,
getProjectConfig,
getProjectMeta,
initJSProjectWithProfile,
LayerOptions,
LayerPermission,
LayerPermissionName,
LayerRuntime,
loadFunctionTestFile,
overrideFunctionSrcNode,
overrideLayerCodeNode,
overrideLayerCodePython,
updateFunction,
updateLayer,
validatePushedVersion,
} from 'amplify-e2e-core';
import { v4 as uuid } from 'uuid';
describe('amplify add lambda layer with changes', () => {
let projRoot: string;
let projName: string;
const envName = 'integtest';
beforeEach(async () => {
projRoot = await createNewProjectDir('layers');
await initJSProjectWithProfile(projRoot, { envName });
({ projectName: projName } = getProjectConfig(projRoot));
});
afterEach(async () => {
await deleteProject(projRoot);
deleteProjectDir(projRoot);
});
it('simple layer, change future permission, no changes', async () => {
const [shortId] = uuid().split('-');
const layerName = `simplelayer${shortId}`;
const layerRuntime: LayerRuntime = 'nodejs';
const settings = {
runtimes: [layerRuntime],
layerName,
projName,
};
const settingsUpdate = {
runtimes: [layerRuntime],
layerName: layerName,
changePermissionOnFutureVersion: true,
permissions: ['Public (Anyone on AWS can use this layer)'],
numLayers: 1,
projName,
};
await addLayer(projRoot, settings);
await amplifyPushLayer(projRoot, {
acceptSuggestedLayerVersionConfigurations: true,
usePreviousPermissions: true,
});
await updateLayer(projRoot, settingsUpdate);
const expectedPerms: LayerPermission[] = [{ type: LayerPermissionName.public }];
validatePushedVersion(projRoot, { layerName, projName }, expectedPerms);
await amplifyStatus(projRoot, 'No Change');
});
it('simple layer, change latest permission, update status, no new layer version', async () => {
const [shortId] = uuid().split('-');
const layerName = `simplelayer${shortId}`;
const layerRuntime: LayerRuntime = 'nodejs';
const settings = {
runtimes: [layerRuntime],
layerName,
projName,
};
const settingsUpdate = {
runtimes: [layerRuntime],
layerName: layerName,
changePermissionOnLatestVersion: true,
permissions: ['Public (Anyone on AWS can use this layer)'],
numLayers: 1,
projName,
};
await addLayer(projRoot, settings);
await amplifyPushLayer(projRoot, {
acceptSuggestedLayerVersionConfigurations: true,
usePreviousPermissions: true,
});
const firstArn = getCurrentLayerArnFromMeta(projRoot, settingsUpdate);
await updateLayer(projRoot, settingsUpdate);
const expectedPerms: LayerPermission[] = [{ type: LayerPermissionName.public }];
expectEphemeralPermissions(projRoot, settingsUpdate, envName, 1, expectedPerms);
await amplifyStatus(projRoot, 'Update');
await amplifyPushAuth(projRoot);
expectEphemeralDataIsUndefined(projRoot, settingsUpdate);
const secondArn = getCurrentLayerArnFromMeta(projRoot, settings);
// Layer ARNs must match as no new version should have been deployed
expect(firstArn).toEqual(secondArn);
});
it('simple layer, change update layer, select NO to permissions, no changes', async () => {
const [shortId] = uuid().split('-');
const layerName = `simplelayer${shortId}`;
const layerRuntime: LayerRuntime = 'nodejs';
const settings = {
runtimes: [layerRuntime],
layerName,
projName,
};
const settingsUpdate = {
runtimes: [layerRuntime],
layerName: layerName,
dontChangePermissions: true,
numLayers: 1,
projName,
};
await addLayer(projRoot, settings);
await amplifyPushLayer(projRoot, {
acceptSuggestedLayerVersionConfigurations: true,
});
await updateLayer(projRoot, settingsUpdate);
await amplifyStatus(projRoot, 'No Change');
});
it('simple layer, update description during push', async () => {
const [shortId] = uuid().split('-');
const layerName = `simplelayer${shortId}`;
const layerRuntime: LayerRuntime = 'nodejs';
const settings = {
runtimes: [layerRuntime],
layerName,
projName,
};
const layerDescription = 'Custom Description from E2E';
await addLayer(projRoot, settings);
await amplifyPushLayer(projRoot, {
acceptSuggestedLayerVersionConfigurations: false,
usePreviousPermissions: true,
layerDescription,
});
await expectDeployedLayerDescription(projRoot, settings, getProjectMeta(projRoot), envName, layerDescription);
});
it('function with layer reference, change version, test invocation', async () => {
const lambdaTestString = 'Hello from Lambda!';
const helloWorldUpperCaseOutput = 'HELLO FROM LAMBDA!';
const helloWorldTitleCaseOutput = 'Hello From Lambda!';
const [shortId] = uuid().split('-');
const layerName = `reflayer${shortId}`;
const layerRuntime: LayerRuntime = 'nodejs';
// 1. Step
// - Create a layer
// - Create a function, referencing the layer
// - Add package.json and casing.js to layer code
// - Override function code to invoke the layer
// - Push
// - Invoke function, check result (upper cased)
const settings = {
runtimes: [layerRuntime],
layerName,
projName,
};
const functionName = `nodetestfunction${shortId}`;
await addLayer(projRoot, settings);
const packageJsonContent = loadFunctionTestFile('case-layer-package.json');
const caseLayerIndexV1 = loadFunctionTestFile('case-layer-v1.js');
const caseLayerIndexV2 = loadFunctionTestFile('case-layer-v2.js');
let functionCode = loadFunctionTestFile('case-function-for-layer.js');
functionCode = functionCode.replace('{{testString}}', lambdaTestString);
overrideLayerCodeNode(projRoot, settings.projName, settings.layerName, packageJsonContent, 'package.json');
addOptFile(projRoot, settings.projName, settings.layerName, caseLayerIndexV1, 'casing.js');
const layerOptions: LayerOptions = {
select: [`${settings.projName}${settings.layerName}`],
expectedListOptions: [`${settings.projName}${settings.layerName}`],
};
await addFunction(projRoot, { functionTemplate: 'Hello World', layerOptions, name: functionName }, layerRuntime);
overrideFunctionSrcNode(projRoot, functionName, functionCode);
await amplifyPushLayer(projRoot, {
acceptSuggestedLayerVersionConfigurations: true,
});
const payload = '{}';
let response = await functionCloudInvoke(projRoot, { funcName: functionName, payload: payload });
expect(JSON.parse(JSON.parse(response.Payload.toString()).body)).toEqual(helloWorldUpperCaseOutput);
// 2. Step
// - Update casing.js in layer
// - Update function to use V1 of the layer
// - Push
// - Invoke function, result must be the same as first time (upper cased)
addOptFile(projRoot, settings.projName, settings.layerName, caseLayerIndexV2, 'casing.js');
const fullLayerName = `${settings.projName}${settings.layerName}`;
const settingsUpdate = {
runtimes: [layerRuntime],
layerName,
projName,
layerOptions: {
select: [fullLayerName],
expectedListOptions: [fullLayerName],
versions: { [fullLayerName]: { version: 1, expectedVersionOptions: [1] } },
skipLayerAssignment: true,
layerAndFunctionExist: true,
},
};
await updateFunction(projRoot, settingsUpdate, layerRuntime);
await amplifyPushLayer(projRoot, {
acceptSuggestedLayerVersionConfigurations: true,
});
response = await functionCloudInvoke(projRoot, { funcName: functionName, payload: payload });
expect(JSON.parse(JSON.parse(response.Payload.toString()).body)).toEqual(helloWorldUpperCaseOutput);
// 3. Step
// - Update function to use latest version of the layer
// - Push
// - Invoke function, result must be the different (title cased)
const settingsUpdateToLatestVersion = {
runtimes: [layerRuntime],
layerName,
projName,
layerOptions: {
layerAndFunctionExist: true,
layerWalkthrough: (chain: ExecutionContext): void => {
chain
.wait('Provide existing layers')
.sendCarriageReturn()
.wait(`Select a version for ${fullLayerName}`)
.sendKeyUp(2) // Move from version 1 to Always choose latest version
.sendCarriageReturn();
},
},
};
await updateFunction(projRoot, settingsUpdateToLatestVersion, layerRuntime);
await amplifyPushAuth(projRoot);
response = await functionCloudInvoke(projRoot, { funcName: functionName, payload: payload });
expect(JSON.parse(JSON.parse(response.Payload.toString()).body)).toEqual(helloWorldTitleCaseOutput);
});
/*
add node layer
add files in opt
push
remove node_modules (simulate gitignore),
amplify status -> no change
delete yarn.lock
amplify status -> update
push
-> should not create layer version, (it should force a npm/yarn), node_module should exist with content, push should succeed
*/
it('add node layer, remove lock file, node_modules, verify status, push', async () => {
const [shortId] = uuid().split('-');
const layerName = `simplelayer${shortId}`;
const layerRuntime: LayerRuntime = 'nodejs';
const settings = {
runtimes: [layerRuntime],
layerName,
projName,
};
await addLayer(projRoot, settings);
const packageJsonContent = loadFunctionTestFile('case-layer-package.json');
overrideLayerCodeNode(projRoot, settings.projName, settings.layerName, packageJsonContent, 'package.json');
addOptData(projRoot, settings);
await amplifyPushLayer(projRoot, {
acceptSuggestedLayerVersionConfigurations: true,
usePreviousPermissions: true,
});
const firstArn = getCurrentLayerArnFromMeta(projRoot, { layerName, projName });
// 1. Remove node_modules
// 2. Check status: No Change
const layerPath = path.join(
projRoot,
'amplify',
'backend',
'function',
getLayerDirectoryName({ projName: settings.projName, layerName: settings.layerName }),
);
rimraf.sync(path.join(layerPath, 'lib', 'nodejs', 'node_modules'));
await amplifyStatus(projRoot, 'No Change');
// 3. Remove yarn.lock
// 4. Check status: Update
fs.removeSync(path.join(layerPath, 'lib', 'nodejs', 'yarn.lock'));
await amplifyStatus(projRoot, 'Update');
await amplifyPushLayer(projRoot, {
acceptSuggestedLayerVersionConfigurations: true,
usePreviousPermissions: true,
});
const secondArn = getCurrentLayerArnFromMeta(projRoot, settings);
// Layer ARNs must match as no new version should have been deployed, as
expect(firstArn).toEqual(secondArn);
});
/*
add python layer
add files in opt
push
remove lib/python3.8/site-packages (simulate gitignore),
amplify status -> no change
delete Pipfile.lock
amplify status -> update
push
-> should not create layer version, (it should force a pip install),
lib/python3.8/site-packages should exist with content, push should succeed
*/
it('add python layer, remove lock file, site-packages, verify status, push', async () => {
const [shortId] = uuid().split('-');
const layerName = `simplelayer${shortId}`;
const layerRuntime: LayerRuntime = 'python';
const settings = {
runtimes: [layerRuntime],
layerName,
projName,
};
await addLayer(projRoot, settings);
const pipfileContent = loadFunctionTestFile('titlecase.pipfile');
overrideLayerCodePython(projRoot, settings.projName, settings.layerName, pipfileContent, 'Pipfile');
addOptData(projRoot, settings);
await amplifyPushLayer(projRoot, {
acceptSuggestedLayerVersionConfigurations: true,
usePreviousPermissions: true,
});
const firstArn = getCurrentLayerArnFromMeta(projRoot, { layerName, projName });
// 1. Remove lib/python3.8/site-packages
// 2. Check status: No Change
const layerPath = path.join(
projRoot,
'amplify',
'backend',
'function',
getLayerDirectoryName({ projName: settings.projName, layerName: settings.layerName }),
);
rimraf.sync(path.join(layerPath, 'lib', 'python', 'lib'));
await amplifyStatus(projRoot, 'No Change');
// 3. Remove Pipfile.lock
// 4. Check status: Update
fs.removeSync(path.join(layerPath, 'lib', 'python', 'Pipfile.lock'));
await amplifyStatus(projRoot, 'Update');
await amplifyPushLayer(projRoot, {
acceptSuggestedLayerVersionConfigurations: true,
usePreviousPermissions: true,
});
const secondArn = getCurrentLayerArnFromMeta(projRoot, settings);
// Layer ARNs must match as no new version should have been deployed, as
expect(firstArn).toEqual(secondArn);
});
}); | the_stack |
import ts from 'typescript';
import {absoluteFrom} from '../../src/ngtsc/file_system';
import {runInEachFileSystem} from '../../src/ngtsc/file_system/testing';
import {loadStandardTestFiles} from '../../src/ngtsc/testing';
import {NgtscTestEnvironment} from './env';
const testFiles = loadStandardTestFiles();
runInEachFileSystem(() => {
describe('ngtsc incremental compilation (template typecheck)', () => {
let env!: NgtscTestEnvironment;
beforeEach(() => {
env = NgtscTestEnvironment.setup(testFiles);
env.enableMultipleCompilations();
env.tsconfig({strictTemplates: true});
});
describe('type-check api surface', () => {
it('should type-check correctly when a backing input field is renamed', () => {
// This test verifies that renaming the class field of an input is correctly reflected into
// the TCB.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
})
export class Dir {
@Input('dir')
dir!: string;
}
`);
env.write('cmp.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div [dir]="foo"></div>',
})
export class Cmp {
foo = 'foo';
}
`);
env.write('mod.ts', `
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {Dir} from './dir';
@NgModule({
declarations: [Cmp, Dir],
})
export class Mod {}
`);
env.driveMain();
// Now rename the backing field of the input; the TCB should be updated such that the `dir`
// input binding is still valid.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
})
export class Dir {
@Input('dir')
dirRenamed!: string;
}
`);
env.driveMain();
});
it('should type-check correctly when a backing output field is renamed', () => {
// This test verifies that renaming the class field of an output is correctly reflected into
// the TCB.
env.write('dir.ts', `
import {Directive, EventEmitter, Output} from '@angular/core';
@Directive({
selector: '[dir]',
})
export class Dir {
@Output('dir')
dir = new EventEmitter<string>();
}
`);
env.write('cmp.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div (dir)="foo($event)"></div>',
})
export class Cmp {
foo(bar: string) {}
}
`);
env.write('mod.ts', `
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {Dir} from './dir';
@NgModule({
declarations: [Cmp, Dir],
})
export class Mod {}
`);
env.driveMain();
// Now rename the backing field of the output; the TCB should be updated such that the `dir`
// input binding is still valid.
env.write('dir.ts', `
import {Directive, EventEmitter, Output} from '@angular/core';
@Directive({
selector: '[dir]',
})
export class Dir {
@Output('dir')
dirRenamed = new EventEmitter<string>();
}
`);
env.driveMain();
});
it('should type-check correctly when the backing field of an input is removed', () => {
// For inputs that are only declared in the decorator but for which no backing field is
// declared in the TypeScript class, the TCB should not contain a write to the field as it
// would be an error. This test verifies that the TCB is regenerated when a backing field
// is removed.
env.write('dir.ts', `
import {Directive} from '@angular/core';
@Directive({
selector: '[dir]',
inputs: ['dir'],
})
export class Dir {
dir!: string;
}
`);
env.write('cmp.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div [dir]="foo"></div>',
})
export class Cmp {
foo = true;
}
`);
env.write('mod.ts', `
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {Dir} from './dir';
@NgModule({
declarations: [Cmp, Dir],
})
export class Mod {}
`);
const diags = env.driveDiagnostics();
expect(diags.length).toBe(1);
expect(diags[0].messageText)
.toContain(`Type 'boolean' is not assignable to type 'string'.`);
// Now remove the backing field for the `dir` input. The compilation should now succeed
// as there are no type-check errors.
env.write('dir.ts', `
import {Directive} from '@angular/core';
@Directive({
selector: '[dir]',
inputs: ['dir'],
})
export class Dir {}
`);
env.driveMain();
});
it('should type-check correctly when the backing field of an input is made readonly', () => {
// When an input is declared as readonly and if `strictInputAccessModifiers` is disabled,
// the TCB contains an indirect write to the property to silence the error that a value
// cannot be assigned to a readonly property. This test verifies that changing a field to
// become readonly does result in the TCB being updated to use such an indirect write, as
// otherwise an error would incorrectly be reported.
env.tsconfig({strictTemplates: true, strictInputAccessModifiers: false});
env.write('dir.ts', `
import {Directive} from '@angular/core';
@Directive({
selector: '[dir]',
inputs: ['dir'],
})
export class Dir {
dir!: string;
}
`);
env.write('cmp.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div [dir]="foo"></div>',
})
export class Cmp {
foo = 'foo';
}
`);
env.write('mod.ts', `
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {Dir} from './dir';
@NgModule({
declarations: [Cmp, Dir],
})
export class Mod {}
`);
env.driveMain();
// Now change the `dir` input to be readonly. Because `strictInputAccessModifiers` is
// disabled this should be allowed.
env.write('dir.ts', `
import {Directive} from '@angular/core';
@Directive({
selector: '[dir]',
inputs: ['dir'],
})
export class Dir {
readonly dir!: string;
}
`);
env.driveMain();
});
it('should type-check correctly when an ngAcceptInputType field is declared', () => {
// Declaring a static `ngAcceptInputType` member requires that the TCB is regenerated, as
// writes to an input property should then be targeted against this static member instead
// of the input field itself.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
})
export class Dir {
@Input()
dir!: string;
}
`);
env.write('cmp.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div [dir]="foo"></div>',
})
export class Cmp {
foo = true;
}
`);
env.write('mod.ts', `
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {Dir} from './dir';
@NgModule({
declarations: [Cmp, Dir],
})
export class Mod {}
`);
const diags = env.driveDiagnostics();
expect(diags.length).toBe(1);
expect(diags[0].messageText)
.toContain(`Type 'boolean' is not assignable to type 'string'.`);
// Now add an `ngAcceptInputType` static member to the directive such that its `dir` input
// also accepts `boolean`, unlike the type of `dir`'s class field. This should therefore
// allow the compilation to succeed.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
})
export class Dir {
@Input()
dir!: string;
static ngAcceptInputType_dir: string | boolean;
}
`);
env.driveMain();
});
it('should type-check correctly when an ngTemplateContextGuard field is declared', () => {
// This test adds an `ngTemplateContextGuard` static member to verify that the TCB is
// regenerated for the template context to take effect.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
})
export class Dir {
@Input()
dir!: string;
}
`);
env.write('cmp.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div *dir="let bar">{{ foo(bar) }}</div>',
})
export class Cmp {
foo(bar: string) {}
}
`);
env.write('mod.ts', `
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {Dir} from './dir';
@NgModule({
declarations: [Cmp, Dir],
})
export class Mod {}
`);
env.driveMain();
// Now add the template context to declare the `$implicit` variable to be of type `number`.
// Doing so should report an error for `Cmp`, as the type of `bar` which binds to
// `$implicit` is no longer compatible with the method signature which requires a `string`.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
export interface TemplateContext {
$implicit: number;
}
@Directive({
selector: '[dir]',
})
export class Dir {
@Input()
dir!: string;
static ngTemplateContextGuard(dir: Dir, ctx: any): ctx is TemplateContext { return true; }
}
`);
const diags = env.driveDiagnostics();
expect(diags.length).toBe(1);
expect(diags[0].messageText)
.toContain(
`Argument of type 'number' is not assignable to parameter of type 'string'.`);
});
it('should type-check correctly when an ngTemplateGuard field is declared', () => {
// This test verifies that adding an `ngTemplateGuard` static member has the desired effect
// of type-narrowing the bound input expression within the template.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
})
export class Dir {
@Input()
dir!: boolean;
}
`);
env.write('cmp.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div *dir="foo !== null">{{ test(foo) }}</div>',
})
export class Cmp {
foo!: string | null;
test(foo: string) {}
}
`);
env.write('mod.ts', `
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {Dir} from './dir';
@NgModule({
declarations: [Cmp, Dir],
})
export class Mod {}
`);
const diags = env.driveDiagnostics();
expect(diags.length).toBe(1);
expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '\n'))
.toContain(
`Argument of type 'string | null' is not assignable to parameter of type 'string'.`);
// Now resolve the compilation error by adding the `ngTemplateGuard_dir` static member to
// specify that the bound expression for `dir` should be used as template guard. This
// should allow the compilation to succeed.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
export interface TemplateContext {
$implicit: number;
}
@Directive({
selector: '[dir]',
})
export class Dir {
@Input()
dir!: boolean;
static ngTemplateGuard_dir: 'binding';
}
`);
env.driveMain();
});
it('should type-check correctly when the type of an ngTemplateGuard field changes', () => {
// This test verifies that changing the type of an `ngTemplateGuard` static member has the
// desired effect of type-narrowing the bound input expression within the template according
// to the new type of the `ngTemplateGuard` static member. Initially, an "invocation" type
// context guard is used, but it's ineffective at narrowing an expression that explicitly
// compares against null. An incremental step changes the type of the guard to be of type
// `binding`.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
})
export class Dir<T> {
@Input()
dir!: T;
static ngTemplateGuard_dir<T>(dir: Dir<T>, expr: any): expr is NonNullable<T> { return true; };
}
`);
env.write('cmp.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div *dir="foo !== null">{{ test(foo) }}</div>',
})
export class Cmp {
foo!: string | null;
test(foo: string) {}
}
`);
env.write('mod.ts', `
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {Dir} from './dir';
@NgModule({
declarations: [Cmp, Dir],
})
export class Mod {}
`);
const diags = env.driveDiagnostics();
expect(diags.length).toBe(1);
expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '\n'))
.toContain(
`Argument of type 'string | null' is not assignable to parameter of type 'string'.`);
// Now change the type of the template guard into "binding" to achieve the desired narrowing
// of `foo`, allowing the compilation to succeed.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
export interface TemplateContext {
$implicit: number;
}
@Directive({
selector: '[dir]',
})
export class Dir<T> {
@Input()
dir!: T;
static ngTemplateGuard_dir: 'binding';
}
`);
env.driveMain();
});
it('should type-check correctly when the name of an ngTemplateGuard field changes', () => {
// This test verifies that changing the name of the field to which an `ngTemplateGuard`
// static member applies correctly removes its narrowing effect on the original input
// binding expression.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
})
export class Dir<T> {
@Input()
dir!: T;
static ngTemplateGuard_dir: 'binding';
}
`);
env.write('cmp.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div *dir="foo !== null">{{ test(foo) }}</div>',
})
export class Cmp {
foo!: string | null;
test(foo: string) {}
}
`);
env.write('mod.ts', `
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {Dir} from './dir';
@NgModule({
declarations: [Cmp, Dir],
})
export class Mod {}
`);
env.driveMain();
// Now change the `ngTemplateGuard` to target a different field. The `dir` binding should
// no longer be narrowed, causing the template of `Cmp` to become invalid.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
export interface TemplateContext {
$implicit: number;
}
@Directive({
selector: '[dir]',
})
export class Dir<T> {
@Input()
dir!: T;
static ngTemplateGuard_dir_renamed: 'binding';
}
`);
const diags = env.driveDiagnostics();
expect(diags.length).toBe(1);
expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '\n'))
.toContain(
`Argument of type 'string | null' is not assignable to parameter of type 'string'.`);
});
});
describe('type parameters', () => {
it('should type-check correctly when directive becomes generic', () => {
// This test verifies that changing a non-generic directive `Dir` into a generic directive
// correctly type-checks component `Cmp` that uses `Dir` in its template. The introduction
// of the generic type requires that `Cmp`'s local declaration of `Dir` is also updated,
// otherwise the prior declaration without generic type argument would be invalid.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
})
export class Dir {
@Input()
dir!: string;
}
`);
env.write('cmp.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div [dir]="foo"></div>',
})
export class Cmp {
foo = 'foo';
}
`);
env.write('mod.ts', `
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {Dir} from './dir';
@NgModule({
declarations: [Cmp, Dir],
})
export class Mod {}
`);
env.driveMain();
// Adding a generic type should still allow the compilation to succeed.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
})
export class Dir<T> {
@Input()
dir!: string;
}
`);
env.driveMain();
});
it('should type-check correctly when a type parameter is added to a directive', () => {
// This test verifies that adding an additional generic type to directive `Dir` correctly
// type-checks component `Cmp` that uses `Dir` in its template. The addition of a generic
// type requires that `Cmp`'s local declaration of `Dir` is also updated, otherwise the
// prior declaration with fewer generic type argument would be invalid.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
})
export class Dir<T> {
@Input()
dir!: T;
}
`);
env.write('cmp.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div [dir]="foo"></div>',
})
export class Cmp {
foo = 'foo';
}
`);
env.write('mod.ts', `
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {Dir} from './dir';
@NgModule({
declarations: [Cmp, Dir],
})
export class Mod {}
`);
env.driveMain();
// Add generic type parameter `U` should continue to allow the compilation to succeed.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
})
export class Dir<T, U> {
@Input()
dir!: T;
}
`);
env.driveMain();
});
it('should type-check correctly when directive removes its generic type parameter', () => {
// This test verifies that removing a type parameter from generic directive `Dir` such that
// it becomes non-generic correctly type-checks component `Cmp` that uses `Dir` in its
// template. The removal of the generic type requires that `Cmp`'s local declaration of
// `Dir` is also updated, as otherwise the prior declaration with a generic type argument
// would be invalid.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
})
export class Dir<T> {
@Input()
dir!: string;
}
`);
env.write('cmp.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div [dir]="foo"></div>',
})
export class Cmp {
foo = 'foo';
}
`);
env.write('mod.ts', `
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {Dir} from './dir';
@NgModule({
declarations: [Cmp, Dir],
})
export class Mod {}
`);
env.driveMain();
// Changing `Dir` to become non-generic should allow the compilation to succeed.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
})
export class Dir {
@Input()
dir!: string;
}
`);
env.driveMain();
});
it('should type-check correctly when a type parameter is removed from a directive', () => {
// This test verifies that removing a type parameter from generic directive `Dir` correctly
// type-checks component `Cmp` that uses `Dir` in its template. The removal of the generic
// type requires that `Cmp`'s local declaration of `Dir` is also updated, as otherwise the
// prior declaration with the initial number of generic type arguments would be invalid.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
})
export class Dir<T, U> {
@Input()
dir!: T;
}
`);
env.write('cmp.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div [dir]="foo"></div>',
})
export class Cmp {
foo = 'foo';
}
`);
env.write('mod.ts', `
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {Dir} from './dir';
@NgModule({
declarations: [Cmp, Dir],
})
export class Mod {}
`);
env.driveMain();
// Removing type parameter `U` should allow the compilation to succeed.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
})
export class Dir<T> {
@Input()
dir!: T;
}
`);
env.driveMain();
});
it('should type-check correctly when a generic type bound is added', () => {
// This test verifies that changing an unbound generic type parameter of directive `Dir`
// to have a type constraint properly applies the newly added type constraint during
// type-checking of `Cmp` that uses `Dir` in its template.
env.write('node_modules/foo/index.ts', `
export interface Foo {
a: boolean;
}
`);
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
})
export class Dir<T> {
@Input()
dir!: T;
}
`);
env.write('cmp.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div [dir]="foo"></div>',
})
export class Cmp {
foo: string;
}
`);
env.write('mod.ts', `
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {Dir} from './dir';
@NgModule({
declarations: [Cmp, Dir],
})
export class Mod {}
`);
env.driveMain();
// Update `Dir` such that its generic type parameter `T` is constrained to type `Foo`. The
// template of `Cmp` should now fail to type-check, as its bound value for `T` does not
// conform to the `Foo` constraint.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
import {Foo} from 'foo';
@Directive({
selector: '[dir]',
})
export class Dir<T extends Foo> {
@Input()
dir!: T;
}
`);
const diags = env.driveDiagnostics();
expect(diags.length).toBe(1);
expect(diags[0].messageText).toContain(`Type 'string' is not assignable to type 'Foo'.`);
// Now update `Dir` again to remove the constraint of `T`, which should allow the template
// of `Cmp` to succeed type-checking.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
})
export class Dir<T> {
@Input()
dir!: T;
}
`);
env.driveMain();
});
it('should type-check correctly when a generic type bound indirectly changes', () => {
// This test verifies the scenario where a generic type constraint is updated indirectly,
// i.e. without the type parameter itself changing. The setup of this test is as follows:
//
// - Have two external modules `foo-a` and `foo-b` that both export a type named `Foo`,
// each having an incompatible shape.
// - Have a directive `Dir` that has a type parameter constrained to `Foo` from `foo-a`.
// - Have a component `Cmp` that uses `Dir` in its template and binds a `Foo` from `foo-a`
// to an input of `Dir` of generic type `T`. This should succeed as it conforms to the
// constraint of `T`.
// - Perform an incremental compilation where the import of `Foo` is changed into `foo-b`.
// The binding in `Cmp` should now report an error, as its value of `Foo` from `foo-a`
// no longer conforms to the new type constraint of `Foo` from 'foo-b'.
env.write('node_modules/foo-a/index.ts', `
export interface Foo {
a: boolean;
}
`);
env.write('node_modules/foo-b/index.ts', `
export interface Foo {
b: boolean;
}
`);
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
import {Foo} from 'foo-a';
@Directive({
selector: '[dir]',
})
export class Dir<T extends Foo> {
@Input()
dir!: T;
}
`);
env.write('cmp.ts', `
import {Component} from '@angular/core';
import {Foo} from 'foo-a';
@Component({
selector: 'test-cmp',
template: '<div [dir]="foo"></div>',
})
export class Cmp {
foo: Foo = {a: true};
}
`);
env.write('mod.ts', `
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {Dir} from './dir';
@NgModule({
declarations: [Cmp, Dir],
})
export class Mod {}
`);
env.driveMain();
// Now switch the import of `Foo` from `foo-a` to `foo-b`. This should cause a type-check
// failure in `Cmp`, as its binding into `Dir` still provides an incompatible `Foo`
// from `foo-a`.
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
import {Foo} from 'foo-b';
@Directive({
selector: '[dir]',
})
export class Dir<T extends Foo> {
@Input()
dir!: T;
}
`);
const diags = env.driveDiagnostics();
expect(diags.length).toBe(1);
expect(diags[0].messageText)
.toContain(`Type 'import("${
absoluteFrom(
'/node_modules/foo-a/index')}").Foo' is not assignable to type 'import("${
absoluteFrom('/node_modules/foo-b/index')}").Foo'.`);
// For completeness, update `Cmp` to address the previous template type-check error by
// changing the type of the binding into `Dir` to also be the `Foo` from `foo-b`. This
// should result in a successful compilation.
env.write('cmp.ts', `
import {Component} from '@angular/core';
import {Foo} from 'foo-b';
@Component({
selector: 'test-cmp',
template: '<div [dir]="foo"></div>',
})
export class Cmp {
foo: Foo = {b: true};
}
`);
env.driveMain();
});
});
describe('inheritance', () => {
it('should type-check derived directives when the public API of the parent class is affected',
() => {
// This test verifies that an indirect change to the public API of `Dir` as caused by a
// change to `Dir`'s base class `Parent` causes the type-check result of component `Cmp`
// that uses `Dir` to be updated accordingly.
env.write('parent.ts', `
import {Directive, Input} from '@angular/core';
@Directive()
export class Parent {
@Input()
parent!: string;
}
`);
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
import {Parent} from './parent';
@Directive({
selector: '[dir]',
})
export class Dir extends Parent {
@Input()
dir!: string;
}
`);
env.write('cmp.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div [dir]="foo" [parent]="foo"></div>',
})
export class Cmp {
foo = 'foo';
}
`);
env.write('mod.ts', `
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {Dir} from './dir';
@NgModule({
declarations: [Cmp, Dir],
})
export class Mod {}
`);
env.driveMain();
// Now remove an input from `Parent`. This invalidates the binding in `Cmp`'s template,
// so an error diagnostic should be reported.
env.write('parent.ts', `
import {Directive, Input} from '@angular/core';
@Directive()
export class Parent {
}
`);
const diags = env.driveDiagnostics();
expect(diags.length).toBe(1);
expect(diags[0].messageText)
.toContain(`Can't bind to 'parent' since it isn't a known property of 'div'.`);
});
it('should type-check derived directives when the public API of the grandparent class is affected',
() => {
// This test verifies that an indirect change to the public API of `Dir` as caused by a
// change to `Dir`'s transitive base class `Grandparent` causes the type-check result of
// component `Cmp` that uses `Dir` to be updated accordingly.
env.write('grandparent.ts', `
import {Directive, Input} from '@angular/core';
@Directive()
export class Grandparent {
@Input()
grandparent!: string;
}
`);
env.write('parent.ts', `
import {Directive, Input} from '@angular/core';
import {Grandparent} from './grandparent';
@Directive()
export class Parent extends Grandparent {
@Input()
parent!: string;
}
`);
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
import {Parent} from './parent';
@Directive({
selector: '[dir]',
})
export class Dir extends Parent {
@Input()
dir!: string;
}
`);
env.write('cmp.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div [dir]="foo" [parent]="foo" [grandparent]="foo"></div>',
})
export class Cmp {
foo = 'foo';
}
`);
env.write('mod.ts', `
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {Dir} from './dir';
@NgModule({
declarations: [Cmp, Dir],
})
export class Mod {}
`);
env.driveMain();
// Now remove an input from `Grandparent`. This invalidates the binding in `Cmp`'s
// template, so an error diagnostic should be reported.
env.write('grandparent.ts', `
import {Directive, Input} from '@angular/core';
@Directive()
export class Grandparent {
}
`);
const diags = env.driveDiagnostics();
expect(diags.length).toBe(1);
expect(diags[0].messageText)
.toContain(`Can't bind to 'grandparent' since it isn't a known property of 'div'.`);
});
it('should type-check derived directives when a base class is added to a grandparent', () => {
// This test verifies that an indirect change to the public API of `Dir` as caused by
// adding a base class `Grandgrandparent` to `Dir`'s transitive base class `Grandparent`
// causes the type-check result of component `Cmp` that uses `Dir` to be
// updated accordingly.
env.write('grandgrandparent.ts', `
import {Directive, Input} from '@angular/core';
@Directive()
export class Grandgrandparent {
@Input()
grandgrandparent!: string;
}
`);
env.write('grandparent.ts', `
import {Directive, Input} from '@angular/core';
@Directive()
export class Grandparent {
@Input()
grandparent!: string;
}
`);
env.write('parent.ts', `
import {Directive, Input} from '@angular/core';
import {Grandparent} from './grandparent';
@Directive()
export class Parent extends Grandparent {
@Input()
parent!: string;
}
`);
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
import {Parent} from './parent';
@Directive({
selector: '[dir]',
})
export class Dir extends Parent {
@Input()
dir!: string;
}
`);
env.write('cmp.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div [dir]="foo" [parent]="foo" [grandgrandparent]="foo"></div>',
})
export class Cmp {
foo = 'foo';
}
`);
env.write('mod.ts', `
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {Dir} from './dir';
@NgModule({
declarations: [Cmp, Dir],
})
export class Mod {}
`);
// `Cmp` already binds to the `grandgrandparent` input but it's not available, as
// `Granparent` does not yet extend from `Grandgrandparent`.
const diags = env.driveDiagnostics();
expect(diags.length).toBe(1);
expect(diags[0].messageText)
.toContain(
`Can't bind to 'grandgrandparent' since it isn't a known property of 'div'.`);
// Now fix the issue by adding the base class to `Grandparent`; this should allow
// type-checking to succeed.
env.write('grandparent.ts', `
import {Directive, Input} from '@angular/core';
import {Grandgrandparent} from './grandgrandparent';
@Directive()
export class Grandparent extends Grandgrandparent {
@Input()
grandparent!: string;
}
`);
env.driveMain();
});
it('should type-check derived directives when a base class is removed from a grandparent',
() => {
// This test verifies that an indirect change to the public API of `Dir` as caused by
// removing a base class `Grandgrandparent` from `Dir`'s transitive base class
// `Grandparent` causes the type-check result of component `Cmp` that uses `Dir` to be
// updated accordingly.
env.write('grandgrandparent.ts', `
import {Directive, Input} from '@angular/core';
@Directive()
export class Grandgrandparent {
@Input()
grandgrandparent!: string;
}
`);
env.write('grandparent.ts', `
import {Directive, Input} from '@angular/core';
import {Grandgrandparent} from './grandgrandparent';
@Directive()
export class Grandparent extends Grandgrandparent {
@Input()
grandparent!: string;
}
`);
env.write('parent.ts', `
import {Directive, Input} from '@angular/core';
import {Grandparent} from './grandparent';
@Directive()
export class Parent extends Grandparent {
@Input()
parent!: string;
}
`);
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
import {Parent} from './parent';
@Directive({
selector: '[dir]',
})
export class Dir extends Parent {
@Input()
dir!: string;
}
`);
env.write('cmp.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div [dir]="foo" [parent]="foo" [grandgrandparent]="foo"></div>',
})
export class Cmp {
foo = 'foo';
}
`);
env.write('mod.ts', `
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {Dir} from './dir';
@NgModule({
declarations: [Cmp, Dir],
})
export class Mod {}
`);
env.driveMain();
// Removing the base class from `Grandparent` should start to report a type-check
// error in `Cmp`'s template, as its binding to the `grandgrandparent` input is no
// longer valid.
env.write('grandparent.ts', `
import {Directive, Input} from '@angular/core';
@Directive()
export class Grandparent {
@Input()
grandparent!: string;
}
`);
const diags = env.driveDiagnostics();
expect(diags.length).toBe(1);
expect(diags[0].messageText)
.toContain(
`Can't bind to 'grandgrandparent' since it isn't a known property of 'div'.`);
});
it('should type-check derived directives when the base class of a grandparent changes',
() => {
// This test verifies that an indirect change to the public API of `Dir` as caused by
// changing the base class of `Dir`'s transitive base class `Grandparent` causes the
// type-check result of component `Cmp` that uses `Dir` to be updated accordingly.
env.write('grandgrandparent-a.ts', `
import {Directive, Input} from '@angular/core';
@Directive()
export class GrandgrandparentA {
@Input()
grandgrandparentA!: string;
}
`);
env.write('grandgrandparent-b.ts', `
import {Directive, Input} from '@angular/core';
@Directive()
export class GrandgrandparentB {
@Input()
grandgrandparentB!: string;
}
`);
env.write('grandparent.ts', `
import {Directive, Input} from '@angular/core';
import {GrandgrandparentA} from './grandgrandparent-a';
@Directive()
export class Grandparent extends GrandgrandparentA {
@Input()
grandparent!: string;
}
`);
env.write('parent.ts', `
import {Directive, Input} from '@angular/core';
import {Grandparent} from './grandparent';
@Directive()
export class Parent extends Grandparent {
@Input()
parent!: string;
}
`);
env.write('dir.ts', `
import {Directive, Input} from '@angular/core';
import {Parent} from './parent';
@Directive({
selector: '[dir]',
})
export class Dir extends Parent {
@Input()
dir!: string;
}
`);
env.write('cmp.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div [dir]="foo" [parent]="foo" [grandgrandparentA]="foo"></div>',
})
export class Cmp {
foo = 'foo';
}
`);
env.write('mod.ts', `
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {Dir} from './dir';
@NgModule({
declarations: [Cmp, Dir],
})
export class Mod {}
`);
env.driveMain();
// Now switch the base class of `Grandparent` from `GrandgrandparentA` to
// `GrandgrandparentB` causes the input binding to `grandgrandparentA` to be reported as
// an error, as it's no longer available.
env.write('grandparent.ts', `
import {Directive, Input} from '@angular/core';
import {GrandgrandparentB} from './grandgrandparent-b';
@Directive()
export class Grandparent extends GrandgrandparentB {
@Input()
grandparent!: string;
}
`);
const diags = env.driveDiagnostics();
expect(diags.length).toBe(1);
expect(diags[0].messageText)
.toContain(
`Can't bind to 'grandgrandparentA' since it isn't a known property of 'div'.`);
});
});
});
}); | the_stack |
module android.view.menu {
import Resources = android.content.res.Resources;
import R = android.R;
import ListPopupWindow = android.widget.ListPopupWindow;
import KeyEvent = android.view.KeyEvent;
import LayoutInflater = android.view.LayoutInflater;
import MenuItem = android.view.MenuItem;
import Menu = android.view.Menu;
import View = android.view.View;
import MeasureSpec = android.view.View.MeasureSpec;
import ViewGroup = android.view.ViewGroup;
import Context = android.content.Context;
import ViewTreeObserver = android.view.ViewTreeObserver;
import AdapterView = android.widget.AdapterView;
import TextView = android.widget.TextView;
import ImageView = android.widget.ImageView;
import BaseAdapter = android.widget.BaseAdapter;
import FrameLayout = android.widget.FrameLayout;
import ListAdapter = android.widget.ListAdapter;
import PopupWindow = android.widget.PopupWindow;
import ArrayList = java.util.ArrayList;
/**
* Presents a menu as a small, simple popup anchored to another view.
*
* @hide
*/
export class MenuPopupHelper implements AdapterView.OnItemClickListener, View.OnKeyListener,
ViewTreeObserver.OnGlobalLayoutListener, PopupWindow.OnDismissListener
//, MenuPresenter
{
private static TAG:string = "MenuPopupHelper";
static ITEM_LAYOUT:string = R.layout.popup_menu_item_layout;
private mContext:Context;
private mInflater:LayoutInflater;
private mPopup:ListPopupWindow;
private mMenu:Menu;
private mPopupMaxWidth:number = 0;
private mAnchorView:View;
//private mOverflowOnly:boolean;
private mTreeObserver:ViewTreeObserver;
private mAdapter:MenuPopupHelper.MenuAdapter;
//private mPresenterCallback:Callback;
//mForceShowIcon:boolean;
private mMeasureParent:ViewGroup;
constructor(context:Context, menu:Menu, anchorView:View=null) {
this.mContext = context;
this.mInflater = LayoutInflater.from(context);
this.mMenu = menu;
//this.mOverflowOnly = overflowOnly;
const res:Resources = context.getResources();
this.mPopupMaxWidth = Math.max(res.getDisplayMetrics().widthPixels / 2, res.getDisplayMetrics().density * 320);
this.mAnchorView = anchorView;
//menu.addMenuPresenter(this);
}
setAnchorView(anchor:View):void {
this.mAnchorView = anchor;
}
//setForceShowIcon(forceShow:boolean):void {
// this.mForceShowIcon = forceShow;
//}
show():void {
if (!this.tryShow()) {
throw Error(`new IllegalStateException("MenuPopupHelper cannot be used without an anchor")`);
}
}
tryShow():boolean {
this.mPopup = new ListPopupWindow(this.mContext, R.attr.popupMenuStyle);
this.mPopup.setOnDismissListener(this);
this.mPopup.setOnItemClickListener(this);
this.mAdapter = new MenuPopupHelper.MenuAdapter(this.mMenu, this);
this.mPopup.setAdapter(this.mAdapter);
this.mPopup.setModal(true);
let anchor:View = this.mAnchorView;
if (anchor != null) {
const addGlobalListener:boolean = this.mTreeObserver == null;
// Refresh to latest
this.mTreeObserver = anchor.getViewTreeObserver();
if (addGlobalListener) {
this.mTreeObserver.addOnGlobalLayoutListener(this);
}
this.mPopup.setAnchorView(anchor);
} else {
return false;
}
this.mPopup.setContentWidth(Math.min(this.measureContentWidth(this.mAdapter), this.mPopupMaxWidth));
this.mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
this.mPopup.show();
this.mPopup.getListView().setOnKeyListener(this);
return true;
}
dismiss():void {
if (this.isShowing()) {
this.mPopup.dismiss();
}
}
onDismiss():void {
this.mPopup = null;
//this.mMenu.close();
if (this.mTreeObserver != null) {
if (!this.mTreeObserver.isAlive()) {
this.mTreeObserver = this.mAnchorView.getViewTreeObserver();
}
this.mTreeObserver.removeGlobalOnLayoutListener(this);
this.mTreeObserver = null;
}
}
isShowing():boolean {
return this.mPopup != null && this.mPopup.isShowing();
}
onItemClick(parent:AdapterView<any>, view:View, position:number, id:number):void {
let adapter:MenuPopupHelper.MenuAdapter = this.mAdapter;
let invoked:boolean = adapter.getItem(position).invoke();
if(invoked) this.mPopup.dismiss();
//adapter.mAdapterMenu.performItemAction(adapter.getItem(position), 0);
}
onKey(v:View, keyCode:number, event:KeyEvent):boolean {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_MENU) {
this.dismiss();
return true;
}
return false;
}
private measureContentWidth(adapter:ListAdapter):number {
// Menus don't tend to be long, so this is more sane than it looks.
let width:number = 0;
let itemView:View = null;
let itemType:number = 0;
const widthMeasureSpec:number = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
const heightMeasureSpec:number = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
const count:number = adapter.getCount();
for (let i:number = 0; i < count; i++) {
const positionType:number = adapter.getItemViewType(i);
if (positionType != itemType) {
itemType = positionType;
itemView = null;
}
if (this.mMeasureParent == null) {
this.mMeasureParent = new FrameLayout(this.mContext);
}
itemView = adapter.getView(i, itemView, this.mMeasureParent);
itemView.measure(widthMeasureSpec, heightMeasureSpec);
width = Math.max(width, itemView.getMeasuredWidth());
}
return width;
}
onGlobalLayout():void {
if (this.isShowing()) {
const anchor:View = this.mAnchorView;
if (anchor == null || !anchor.isShown()) {
this.dismiss();
} else if (this.isShowing()) {
// Recompute window size and position
try {
this.mPopup.setContentWidth(Math.min(this.measureContentWidth(this.mAdapter), this.mPopupMaxWidth));
} catch (e) {
}
this.mPopup.show();
}
}
}
//initForMenu(context:Context, menu:Menu):void {
//// Don't need to do anything; we added as a presenter in the constructor.
//}
//
//getMenuView(root:ViewGroup):MenuView {
// throw Error(`new UnsupportedOperationException("MenuPopupHelpers manage their own views")`);
//}
//
//updateMenuView(cleared:boolean):void {
// if (this.mAdapter != null) {
// this.mAdapter.notifyDataSetChanged();
// }
//}
//
//setCallback(cb:Callback):void {
// this.mPresenterCallback = cb;
//}
//
//androidui: sub menu not support yet
//onSubMenuSelected(subMenu:SubMenuBuilder):boolean {
// if (subMenu.hasVisibleItems()) {
// let subPopup:MenuPopupHelper = new MenuPopupHelper(this.mContext, subMenu, this.mAnchorView, false);
// subPopup.setCallback(this.mPresenterCallback);
// let preserveIconSpacing:boolean = false;
// const count:number = subMenu.size();
// for (let i:number = 0; i < count; i++) {
// let childItem:MenuItem = subMenu.getItem(i);
// if (childItem.isVisible() && childItem.getIcon() != null) {
// preserveIconSpacing = true;
// break;
// }
// }
// subPopup.setForceShowIcon(preserveIconSpacing);
// if (subPopup.tryShow()) {
// if (this.mPresenterCallback != null) {
// this.mPresenterCallback.onOpenSubMenu(subMenu);
// }
// return true;
// }
// }
// return false;
//}
//
//onCloseMenu(menu:Menu, allMenusAreClosing:boolean):void {
// // Only care about the (sub)menu we're presenting.
// if (menu != this.mMenu) {
// return;
// }
// this.dismiss();
// if (this.mPresenterCallback != null) {
// this.mPresenterCallback.onCloseMenu(menu, allMenusAreClosing);
// }
//}
//
//flagActionItems():boolean {
// return false;
//}
//
//expandItemActionView(menu:Menu, item:MenuItem):boolean {
// return false;
//}
//
//collapseItemActionView(menu:Menu, item:MenuItem):boolean {
// return false;
//}
//
//getId():number {
// return 0;
//}
//
//onSaveInstanceState():Parcelable {
// return null;
//}
//
//onRestoreInstanceState(state:Parcelable):void {
//}
}
export module MenuPopupHelper{
export class MenuAdapter extends BaseAdapter {
_MenuPopupHelper_this:MenuPopupHelper;
private mAdapterMenu:Menu;
//private mExpandedIndex:number = -1;
constructor(menu:Menu, arg:MenuPopupHelper){
super();
this._MenuPopupHelper_this = arg;
this.mAdapterMenu = menu;
//this.findExpandedIndex();
}
getCount():number {
let items:ArrayList<MenuItem> =
//this._MenuPopupHelper_this.mOverflowOnly ? this.mAdapterMenu.getNonActionItems() :
this.mAdapterMenu.getVisibleItems();
//if (this.mExpandedIndex < 0) {
return items.size();
//}
//return items.size() - 1;
}
getItem(position:number):MenuItem {
let items:ArrayList<MenuItem> =
//this._MenuPopupHelper_this.mOverflowOnly ? this.mAdapterMenu.getNonActionItems() :
this.mAdapterMenu.getVisibleItems();
//if (this.mExpandedIndex >= 0 && position >= this.mExpandedIndex) {
// position++;
//}
return items.get(position);
}
getItemId(position:number):number {
// ID for the item in the AdapterView
return position;
}
getView(position:number, convertView:View, parent:ViewGroup):View {
if (convertView == null) {
convertView = this._MenuPopupHelper_this.mInflater.inflate(MenuPopupHelper.ITEM_LAYOUT, parent, false);
}
let itemData = this.getItem(position);
convertView.setVisibility(itemData.isVisible() ? View.VISIBLE : View.GONE);
//setTitle
let titleView = <TextView>convertView.findViewById('title');
titleView.setText(itemData.getTitle());
//set short cut (summary)
//no short cut api yet
//set icon
let iconView = <ImageView>convertView.findViewById('icon');
let icon = itemData.getIcon();
iconView.setImageDrawable(icon);
if (icon != null) {
iconView.setImageDrawable(icon);
iconView.setVisibility(View.VISIBLE);
} else {
iconView.setVisibility(View.GONE);
}
//set enable
convertView.setEnabled(itemData.isEnabled());
//let itemView:MenuView.ItemView = <MenuView.ItemView> convertView;
//if (this._MenuPopupHelper_this.mForceShowIcon) {
// (<ListMenuItemView> convertView).setForceShowIcon(true);
//}
//itemView.initialize(this.getItem(position), 0);
return convertView;
}
//findExpandedIndex():void {
// const expandedItem:MenuItem = this._MenuPopupHelper_this.mMenu.getExpandedItem();
// if (expandedItem != null) {
// const items:ArrayList<MenuItem> = this._MenuPopupHelper_this.mMenu.getNonActionItems();
// const count:number = items.size();
// for (let i:number = 0; i < count; i++) {
// const item:MenuItem = items.get(i);
// if (item == expandedItem) {
// this.mExpandedIndex = i;
// return;
// }
// }
// }
// this.mExpandedIndex = -1;
//}
notifyDataSetChanged():void {
//this.findExpandedIndex();
super.notifyDataSetChanged();
}
}
}
} | the_stack |
import {TestBed} from '@angular/core/testing';
import * as tf from '@tensorflow/tfjs';
import fetchMock from 'fetch-mock';
import {AppComponent} from './app.component';
const weightsManifest: tf.io.WeightsManifestEntry[] =
[{name: 'Const', dtype: 'int32', shape: [1]}];
const SIMPLE_MODEL = {
node: [
{
name: 'Input',
op: 'Placeholder',
attr: {
dtype: {
type: 3,
},
shape: {shape: {dim: [{size: -1}, {size: 1}]}}
}
},
{
name: 'Const',
op: 'Const',
attr: {
dtype: {type: 3},
value: {
tensor: {
dtype: 3,
tensorShape: {dim: [{size: 1}]},
}
},
index: {i: 0},
length: {i: 4}
}
},
{name: 'Add1', op: 'Add', input: ['Input', 'Const'], attr: {}},
{name: 'Add', op: 'Add', input: ['Add1', 'Const'], attr: {}}
],
versions: {producer: 1.0, minConsumer: 3}
};
describe('AppComponent', () => {
beforeEach(async () => {
jasmine.clock().install();
await tf.setBackend('cpu');
await TestBed
.configureTestingModule({
declarations: [AppComponent],
})
.compileComponents();
});
afterEach(() => {
jasmine.clock().uninstall();
fetchMock.reset();
});
it('app should be successfully created', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it('app should trigger an error without metadata URL query parameter', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.ngOnInit).toThrowError();
});
it('fetchModel should correctly parse metadata', async () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
// Prepare test data.
const fakeModelMetadataUrl = 'https://modelMetadataUrl/metadata.json';
const fakeModelUrl = 'https://modelMetadataUrl/model.json';
const fakeTestImagesIndexPath = 'https://testImagesPath/index.json';
const fakeModelMetadata = {
tfjs_classifier_model_metadata: {},
test_images_index_path: fakeTestImagesIndexPath,
};
const customLoader: tf.io.IOHandler = {
load: async () => {
return {
modelTopology: SIMPLE_MODEL,
weightSpecs: weightsManifest,
weightData: new Int32Array([5]).buffer,
};
}
};
const simpleModel = await tf.loadGraphModel(customLoader);
// Mock calls.
fetchMock.get(fakeModelMetadataUrl, fakeModelMetadata);
spyOn(app, 'fetchModel').and.returnValue(Promise.resolve(simpleModel));
fetchMock.get(fakeTestImagesIndexPath, ['image1.jpg', 'image2.jpg']);
spyOn(app, 'testImageSelected');
await app.initApp(fakeModelMetadataUrl);
expect(app.testImageSelected)
.toHaveBeenCalledWith('https://testImagesPath/image1.jpg', 0);
expect(app.modelType).toEqual('classifier');
expect(app.testImages).toEqual([
{
imageUrl: 'https://testImagesPath/image1.jpg',
thumbnailUrl: 'https://testImagesPath/image1_thumb.jpg',
},
{
imageUrl: 'https://testImagesPath/image2.jpg',
thumbnailUrl: 'https://testImagesPath/image2_thumb.jpg',
},
]);
});
it('readImageFile should execute correctly with correct image', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
// Prepare test data.
app.uploadedImages = ['existingImageUrl'];
const dummyFile = new File([''], 'filename', {type: 'image/jpg'});
// Mock calls.
const dummyFileReader = {
error: null,
onabort: null,
onload: null,
onerror: null,
onloadend: null,
onprogress: null,
onloadstart: null,
readyState: null,
result: null,
abort: null,
readAsArrayBuffer: null,
readAsBinaryString: null,
readAsText: null,
DONE: null,
EMPTY: null,
LOADING: null,
addEventListener: null,
removeEventListener: null,
dispatchEvent: null,
readAsDataURL(file: File): void {
dummyFileReader.result = 'newImageUrl';
this.onload({});
}
};
spyOn(window, 'FileReader').and.returnValue(dummyFileReader);
spyOn(app, 'handleInputImage');
app.readImageFile(dummyFile);
expect(app.handleInputImage).toHaveBeenCalledWith('newImageUrl', 1);
expect(app.imageSelectedIndex).toEqual(1);
expect(app.uploadedImages).toEqual(['existingImageUrl', 'newImageUrl']);
});
it('fetchLabelmap should correctly parse the labelmap JSON', async () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
// Prepare test data.
const fakeLabelmapUrl = 'https://labelmapUrl/labelmap.json';
const fakeLabelmapName = 'labelmap.json';
app.modelMetadataUrl = 'https://labelmapUrl/metadata.json';
const fakeLabelmap = {
item: [
{
id: 2,
name: 'name2',
},
{
id: 1,
display_name: 'displayName1',
}
]
};
// Mock calls.
fetchMock.get(fakeLabelmapUrl, fakeLabelmap);
await app.fetchLabelmap(fakeLabelmapName);
expect(app.labelmap).toEqual(['unknown', 'displayName1', 'name2']);
});
it('runImageClassifier should correctly parse image classifier model outputs with correct labelmap',
async () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
// Prepare test data.
const fakeImage = new Image();
const fakeInputTensor = tf.tensor([[1.0, 2.0], [3.0, 4.0]]);
app.labelmap = ['someLabel', 'otherLabel', 'underThresholdLabel'];
app.modelMetadata = {
tfjs_classifier_model_metadata: {
input_tensor_metadata: [1, 2, 3, 4],
output_head_metadata: [{
score_threshold: 0.5,
}]
},
};
const customLoader: tf.io.IOHandler = {
load: async () => {
return {
modelTopology: SIMPLE_MODEL,
weightSpecs: weightsManifest,
weightData: new Int32Array([5]).buffer,
};
}
};
app.model = await tf.loadGraphModel(customLoader);
app.imageSelectedIndex = 0;
// Mock calls.
spyOn(app, 'prepareImageInput').and.returnValue(fakeInputTensor);
spyOn(app.model, 'executeAsync')
.and.returnValue(Promise.resolve(tf.tensor([[0.6, 0.8, 0.4]])));
await app.runImageClassifier(fakeImage, 0);
expect(app.classifierResults.length).toEqual(2);
expect(app.classifierResults[0].displayName).toEqual('otherLabel');
expect(app.classifierResults[0].score).toBeCloseTo(0.8);
expect(app.classifierResults[1].displayName).toEqual('someLabel');
expect(app.classifierResults[1].score).toBeCloseTo(0.6);
});
it('runImageClassifier should correctly parse image classifier model outputs with empty labelmap',
async () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
// Prepare test data.
const fakeImage = new Image();
const fakeInputTensor = tf.tensor([[1.0, 2.0], [3.0, 4.0]]);
app.labelmap = [];
app.modelMetadata = {
tfjs_classifier_model_metadata: {
input_tensor_metadata: [1, 2, 3, 4],
output_head_metadata: [{
score_threshold: 0.5,
}]
},
};
const customLoader: tf.io.IOHandler = {
load: async () => {
return {
modelTopology: SIMPLE_MODEL,
weightSpecs: weightsManifest,
weightData: new Int32Array([5]).buffer,
};
}
};
app.model = await tf.loadGraphModel(customLoader);
app.imageSelectedIndex = 0;
// Mock calls.
spyOn(app, 'prepareImageInput').and.returnValue(fakeInputTensor);
spyOn(app.model, 'executeAsync')
.and.returnValue(Promise.resolve(tf.tensor([[0.6, 0.8, 0.4]])));
await app.runImageClassifier(fakeImage, 0);
expect(app.classifierResults.length).toEqual(2);
expect(app.classifierResults[0].displayName).toEqual('unknown');
expect(app.classifierResults[0].score).toBeCloseTo(0.8);
expect(app.classifierResults[1].displayName).toEqual('unknown');
expect(app.classifierResults[1].score).toBeCloseTo(0.6);
});
it('runImageDetector should execute correctly',
async () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
// Prepare test data.
const fakeImage = new Image();
const fakeInputTensor = tf.tensor([[1.0, 2.0], [3.0, 4.0]]);
app.labelmap = ['someLabel', 'otherLabel'];
app.modelMetadata = {
tfjs_detector_model_metadata: {
input_tensor_metadata: [1, 2, 3, 4],
output_head_metadata: [{
score_threshold: 0.5,
}]
},
};
const customLoader: tf.io.IOHandler = {
load: async () => {
return {
modelTopology: SIMPLE_MODEL,
weightSpecs: weightsManifest,
weightData: new Int32Array([5]).buffer,
};
}
};
app.model = await tf.loadGraphModel(customLoader);
app.imageSelectedIndex = 0;
// Mock calls.
spyOn(app, 'prepareImageInput').and.returnValue(fakeInputTensor);
spyOn(app.model, 'executeAsync')
.and.returnValue(Promise.resolve([tf.tensor([4]),
tf.tensor([[[0.1, 0.2, 0.3, 0.4], [0.2, 0.3, 0.4, 0.5],
[0.3, 0.4, 0.5, 0.6], [0.4, 0.5, 0.6, 0.7]]]),
tf.tensor([[0.9, 0.8, 0.5, 0.4]]),
tf.tensor([[0, 1, 0, 1]])]));
spyOn(document, 'getElementById').and.returnValue(fakeImage);
await app.runImageDetector(fakeImage, 0);
jasmine.clock().tick(50);
expect(app.detectorResults.length).toEqual(4);
expect(app.detectorResults[0].displayName).toEqual('someLabel');
expect(app.detectorResults[0].score).toBeCloseTo(0.9);
expect(app.detectorResults[0].id).toEqual(0);
expect(app.detectorResults[1].displayName).toEqual('otherLabel');
expect(app.detectorResults[1].score).toBeCloseTo(0.8);
expect(app.detectorResults[1].id).toEqual(1);
expect(app.detectorResults[2].displayName).toEqual('someLabel');
expect(app.detectorResults[2].score).toBeCloseTo(0.5);
expect(app.detectorResults[2].id).toEqual(2);
expect(app.detectorResults[3].displayName).toEqual('otherLabel');
expect(app.detectorResults[3].score).toBeCloseTo(0.4);
expect(app.detectorResults[3].id).toEqual(3);
});
it('runImageSegmenter should execute correctly',
async () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
// Prepare test data.
const fakeImage = new Image();
const fakeCanvas = document.createElement('canvas');
const fakeInputTensor = tf.tensor([[1.0, 2.0], [3.0, 4.0]]);
app.labelmap = ['someLabel', 'otherLabel'];
app.modelMetadata = {
tfjs_segmenter_model_metadata: {
input_tensor_metadata: [1, 2, 3, 4],
output_head_metadata: [{
semantic_predictions_tensor_name: 'tensor_name',
}],
},
};
const customLoader: tf.io.IOHandler = {
load: async () => {
return {
modelTopology: SIMPLE_MODEL,
weightSpecs: weightsManifest,
weightData: new Int32Array([5]).buffer,
};
}
};
app.model = await tf.loadGraphModel(customLoader);
app.imageSelectedIndex = 0;
// Mock calls.
spyOn(app, 'prepareImageInput').and.returnValue(fakeInputTensor);
spyOn(app.model, 'executeAsync')
.and.returnValue(Promise.resolve(
tf.tensor([[0, 0, 1], [0, 0, 1], [0, 1, 1]])));
spyOn(document, 'getElementById').and.callFake((elementId) => {
switch (elementId) {
case 'query-image':
return fakeImage;
break;
case 'query-canvas-overlay':
return fakeCanvas;
break;
}
});
await app.runImageSegmenter(fakeImage, 0);
expect(app.segmenterPredictions.length).toEqual(3);
expect(app.segmenterPredictions[0].length).toEqual(3);
expect(app.segmenterLabelList.length).toEqual(2);
expect(app.segmenterLabelList[0].displayName).toEqual('someLabel');
expect(app.segmenterLabelList[0].frequencyPercent).toBeCloseTo(56);
expect(app.segmenterLabelList[0].color).toEqual('rgb(0, 0, 0)');
expect(app.segmenterLabelList[1].displayName).toEqual('otherLabel');
expect(app.segmenterLabelList[1].frequencyPercent).toBeCloseTo(45);
expect(app.segmenterLabelList[1].color).toEqual('rgb(128.000055, 0, 0)');
});
}); | the_stack |
import BigNumber from 'bignumber.js';
import { assert } from 'chai';
import { DODOContext, getDODOContext } from '../utils-v1/ProxyContextV1';
import { ProxyContext, getProxyContext } from '../utils/ProxyContextV2';
import { decimalStr, MAX_UINT256, fromWei, mweiStr } from '../utils-v1/Converter';
import { logGas } from '../utils-v1/Log';
import * as contracts from '../utils-v1/Contracts';
import { Contract } from 'web3-eth-contract';
let lp: string;
let trader: string;
async function initDODO_USDT(ctx: DODOContext): Promise<void> {
await ctx.setOraclePrice(ctx.DODO_USDT_ORACLE, mweiStr("0.1"));
lp = ctx.spareAccounts[0];
trader = ctx.spareAccounts[1];
let DODO = ctx.DODO;
let USDT = ctx.USDT;
let DODO_USDT = ctx.DODO_USDT;
await ctx.approvePair(DODO, USDT, DODO_USDT.options.address, lp);
await ctx.approvePair(DODO, USDT, DODO_USDT.options.address, trader);
await ctx.mintToken(DODO, USDT, lp, decimalStr("10000000"), mweiStr("1000000"));
await ctx.mintToken(DODO, USDT, trader, decimalStr("1000"), mweiStr("1000"));
await DODO_USDT.methods
.depositBaseTo(lp, decimalStr("10000000"))
.send(ctx.sendParam(lp));
await DODO_USDT.methods
.depositQuoteTo(lp, mweiStr("1000000"))
.send(ctx.sendParam(lp));
}
async function initUSDT_USDC(ctx: DODOContext): Promise<void> {
await ctx.setOraclePrice(ctx.USDT_USDC_ORACLE, decimalStr("1"));
lp = ctx.spareAccounts[0];
trader = ctx.spareAccounts[1];
let USDT = ctx.USDT;
let USDC = ctx.USDC;
let USDT_USDC = ctx.USDT_USDC;
await ctx.approvePair(USDT, USDC, USDT_USDC.options.address, lp);
await ctx.mintToken(USDT, USDC, lp, mweiStr("1000000"), mweiStr("1000000"));
await USDT_USDC.methods
.depositBaseTo(lp, mweiStr("1000000"))
.send(ctx.sendParam(lp));
await USDT_USDC.methods
.depositQuoteTo(lp, mweiStr("1000000"))
.send(ctx.sendParam(lp));
}
async function initWETH_USDC(ctx: DODOContext): Promise<void> {
await ctx.setOraclePrice(ctx.WETH_USDC_ORACLE, mweiStr("450"));
lp = ctx.spareAccounts[0];
trader = ctx.spareAccounts[1];
let WETH = ctx.WETH;
let USDC = ctx.USDC;
let WETH_USDC = ctx.WETH_USDC;
await ctx.approvePair(WETH, USDC, WETH_USDC.options.address, lp);
await ctx.mintToken(null, USDC, lp, decimalStr("0"), mweiStr("3600"));
await ctx.mintToken(null, USDC, trader, decimalStr("0"), mweiStr("100"));
await WETH.methods.deposit().send(ctx.sendParam(lp, '8'));
await WETH_USDC.methods
.depositBaseTo(lp, decimalStr("8"))
.send(ctx.sendParam(lp));
await WETH_USDC.methods
.depositQuoteTo(lp, mweiStr("3600"))
.send(ctx.sendParam(lp));
}
//mock sdk logic
async function calcRoute(ctx: ProxyContext, fromTokenAmount: string, slippage: number, routes: any[], pairs: any[]) {
let swapAmount = fromTokenAmount
let tmpDirections: number[] = []
let strDirections: string = ''
let dodoPairs: string[] = []
for (let i = 0; i < pairs.length; i++) {
let curPair = pairs[i]
dodoPairs.push(curPair.pair)
let curContact = pairs[i].pairContract
if (routes[i].address == '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE') {
tmpDirections[i] = 0;
swapAmount = await curContact.methods.querySellBaseToken(swapAmount).call();
} else if (curPair.base === routes[i].address) {
tmpDirections[i] = 0;
swapAmount = await curContact.methods.querySellBaseToken(swapAmount).call();
} else {
tmpDirections[i] = 1;
swapAmount = await ctx.DODOSellHelper.methods.querySellQuoteToken(curPair.pair, swapAmount).call();
}
}
for (let i = tmpDirections.length - 1; i >= 0; i--) {
strDirections += tmpDirections[i].toString()
}
let toAmount = new BigNumber(swapAmount).multipliedBy(1 - slippage).toFixed(0, BigNumber.ROUND_DOWN)
let deadline = Math.floor(new Date().getTime() / 1000 + 60 * 10);
return ctx.DODOProxyV2.methods.dodoSwapV1(
routes[0].address,
routes[routes.length - 1].address,
fromTokenAmount,
toAmount,
dodoPairs,
parseInt(strDirections,2),
false,
deadline
)
}
describe("AddLiquidity", () => {
let snapshotId1: string;
let snapshotId2: string;
let ctxV1: DODOContext;
let ctxV2: ProxyContext;
let DODO_LP: Contract;
let WETH_LP: Contract;
let USDT_LP: Contract;
let USDC_LP: Contract;
before(async () => {
let ETH = await contracts.newContract(
contracts.WETH_CONTRACT_NAME
);
ctxV1 = await getDODOContext(ETH.options.address);
ctxV2 = await getProxyContext(ETH.options.address);
await initDODO_USDT(ctxV1);
await initUSDT_USDC(ctxV1);
await initWETH_USDC(ctxV1);
var dodo_dlp = await ctxV1.DODO_USDT.methods._BASE_CAPITAL_TOKEN_().call();
var usdt_dlp = await ctxV1.DODO_USDT.methods._QUOTE_CAPITAL_TOKEN_().call();
DODO_LP = contracts.getContractWithAddress(contracts.DODO_LP_TOKEN_CONTRACT_NAME, dodo_dlp);
USDT_LP = contracts.getContractWithAddress(contracts.DODO_LP_TOKEN_CONTRACT_NAME, usdt_dlp);
var weth_dlp = await ctxV1.WETH_USDC.methods._BASE_CAPITAL_TOKEN_().call();
var usdc_dlp = await ctxV1.WETH_USDC.methods._QUOTE_CAPITAL_TOKEN_().call();
WETH_LP = contracts.getContractWithAddress(contracts.DODO_LP_TOKEN_CONTRACT_NAME, weth_dlp);
USDC_LP = contracts.getContractWithAddress(contracts.DODO_LP_TOKEN_CONTRACT_NAME, usdc_dlp);
});
beforeEach(async () => {
snapshotId1 = await ctxV1.EVM.snapshot();
snapshotId2 = await ctxV2.EVM.snapshot();
});
afterEach(async () => {
await ctxV1.EVM.reset(snapshotId1);
await ctxV2.EVM.reset(snapshotId2);
});
describe("AddLiquidity", () => {
it("AddLiquidity", async () => {
var b_DODO = await ctxV1.DODO.methods.balanceOf(trader).call()
var b_USDT = await ctxV1.USDT.methods.balanceOf(trader).call()
var dodo_lp = await DODO_LP.methods.balanceOf(trader).call()
var usdt_lp = await USDT_LP.methods.balanceOf(trader).call()
console.log("Before DODO:" + fromWei(b_DODO, 'ether') + "; USDT:" + fromWei(b_USDT, 'mwei'));
console.log("dodo_lp:" + dodo_lp + " usdt_lp:" + usdt_lp);
await ctxV1.DODO.methods.approve(ctxV2.DODOApprove.options.address, MAX_UINT256).send(ctxV2.sendParam(trader));
await ctxV1.USDT.methods.approve(ctxV2.DODOApprove.options.address, MAX_UINT256).send(ctxV2.sendParam(trader));
await logGas(await ctxV2.DODOProxyV2.methods.addLiquidityToV1(
ctxV1.DODO_USDT.options.address,
decimalStr("100"),
mweiStr("100"),
0,
0,
0,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctxV2.sendParam(trader), "addLiquidity");
var dodo_lp = await DODO_LP.methods.balanceOf(trader).call()
var usdt_lp = await USDT_LP.methods.balanceOf(trader).call()
var a_DODO = await ctxV1.DODO.methods.balanceOf(trader).call()
var a_USDT = await ctxV1.USDT.methods.balanceOf(trader).call()
console.log("After DODO:" + fromWei(a_DODO, 'ether') + "; USDT:" + fromWei(a_USDT, 'mwei'));
assert.equal(dodo_lp,decimalStr("100"));
assert.equal(usdt_lp,mweiStr("100"));
assert.equal(a_DODO,decimalStr("900"));
assert.equal(a_USDT,mweiStr("900"));
});
it("AddLiquidity - ETH", async () => {
var b_WETH = await ctxV1.WETH.methods.balanceOf(trader).call()
var b_USDC = await ctxV1.USDC.methods.balanceOf(trader).call()
var b_ETH = await ctxV2.Web3.eth.getBalance(trader);
var weth_lp = await WETH_LP.methods.balanceOf(trader).call()
var usdc_lp = await USDC_LP.methods.balanceOf(trader).call()
console.log("Before WETH:" + fromWei(b_WETH, 'ether') + "; USDC:" + fromWei(b_USDC, 'mwei') + "; ETH:" + fromWei(b_ETH, 'ether'));
console.log("weth_lp:" + weth_lp + " usdc_lp:" + usdc_lp);
await ctxV1.USDC.methods.approve(ctxV2.DODOApprove.options.address, MAX_UINT256).send(ctxV2.sendParam(trader));
await logGas(await ctxV2.DODOProxyV2.methods.addLiquidityToV1(
ctxV1.WETH_USDC.options.address,
decimalStr("1"),
mweiStr("100"),
0,
0,
1,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctxV2.sendParam(trader,"1"), "addLiquidity - eth");
var weth_lp = await WETH_LP.methods.balanceOf(trader).call()
var usdc_lp = await USDC_LP.methods.balanceOf(trader).call()
var a_WETH = await ctxV1.WETH.methods.balanceOf(trader).call()
var a_USDC = await ctxV1.USDC.methods.balanceOf(trader).call()
var a_ETH = await ctxV2.Web3.eth.getBalance(trader);
console.log("After WETH:" + fromWei(a_WETH, 'ether') + "; USDC:" + fromWei(a_USDC, 'mwei') + "; ETH:" + fromWei(a_ETH, 'ether'));
assert.equal(weth_lp,decimalStr("1"));
assert.equal(usdc_lp,mweiStr("100"));
});
it("DODO to USDT directly swap", async () => {
var b_DODO = await ctxV1.DODO.methods.balanceOf(trader).call()
var b_USDT = await ctxV1.USDT.methods.balanceOf(trader).call()
console.log("Before DODO:" + fromWei(b_DODO, 'ether') + "; USDT:" + fromWei(b_USDT, 'mwei'));
//approve DODO entry
await ctxV1.DODO.methods.approve(ctxV2.DODOApprove.options.address, MAX_UINT256).send(ctxV2.sendParam(trader))
//set route path
var routes = [{
address: ctxV1.DODO.options.address,
decimals: 18
},
{
address: ctxV1.USDT.options.address,
decimals: 6
}];
var pairs = [{
pair: ctxV1.DODO_USDT.options.address,
base: ctxV1.DODO.options.address,
pairContract: ctxV1.DODO_USDT
}];
await logGas(await calcRoute(ctxV2, decimalStr('10'), 0.1, routes, pairs), ctxV2.sendParam(trader), "directly swap first")
await logGas(await calcRoute(ctxV2, decimalStr('10'), 0.1, routes, pairs), ctxV2.sendParam(trader), "directly swap second")
// console.log(tx.events['OrderHistory']);
var a_DODO = await ctxV1.DODO.methods.balanceOf(trader).call()
var a_USDT = await ctxV1.USDT.methods.balanceOf(trader).call()
console.log("After DODO:" + fromWei(a_DODO, 'ether') + "; USDT:" + fromWei(a_USDT, 'mwei'));
console.log("===============================================")
var c_DODO = await ctxV1.DODO.methods.balanceOf(ctxV2.DODOProxyV2.options.address).call()
var c_USDT = await ctxV1.USDT.methods.balanceOf(ctxV2.DODOProxyV2.options.address).call()
console.log("Contract DODO:" + fromWei(c_DODO, 'ether') + "; USDT:" + fromWei(c_USDT, 'mwei'));
assert(a_USDT, "1994000");
});
it("DODO to USDC two hops swap", async () => {
var b_DODO = await ctxV1.DODO.methods.balanceOf(trader).call()
var b_USDC = await ctxV1.USDC.methods.balanceOf(trader).call()
console.log("Before DODO:" + fromWei(b_DODO, 'ether') + "; USDC:" + fromWei(b_USDC, 'mwei'));
//approve DODO entry
await ctxV1.DODO.methods.approve(ctxV2.DODOApprove.options.address, MAX_UINT256).send(ctxV2.sendParam(trader))
//set route path
var routes = [{
address: ctxV1.DODO.options.address,
decimals: 18
}, {
address: ctxV1.USDT.options.address,
decimals: 6
}, {
address: ctxV1.USDC.options.address,
decimals: 6
}];
var pairs = [{
pair: ctxV1.DODO_USDT.options.address,
base: ctxV1.DODO.options.address,
pairContract: ctxV1.DODO_USDT
}, {
pair: ctxV1.USDT_USDC.options.address,
base: ctxV1.USDT.options.address,
pairContract: ctxV1.USDT_USDC
}];
await logGas(await calcRoute(ctxV2, decimalStr('10'), 0.1, routes, pairs), ctxV2.sendParam(trader), "two hops swap first")
await logGas(await calcRoute(ctxV2, decimalStr('10'), 0.1, routes, pairs), ctxV2.sendParam(trader), "two hops swap second")
// console.log(tx.events['Swapped']);
var a_DODO = await ctxV1.DODO.methods.balanceOf(trader).call()
var a_USDC = await ctxV1.USDC.methods.balanceOf(trader).call()
console.log("After DODO:" + fromWei(a_DODO, 'ether') + "; USDC:" + fromWei(a_USDC, 'mwei'));
console.log("===============================================")
var c_DODO = await ctxV1.DODO.methods.balanceOf(ctxV2.DODOProxyV2.options.address).call()
var c_USDT = await ctxV1.USDT.methods.balanceOf(ctxV2.DODOProxyV2.options.address).call()
var c_USDC = await ctxV1.USDC.methods.balanceOf(ctxV2.DODOProxyV2.options.address).call()
console.log("Contract DODO:" + fromWei(c_DODO, 'ether') + "; USDT:" + fromWei(c_USDT, 'mwei') + "; USDC:" + fromWei(c_USDC, 'mwei'));
assert(a_USDC, "1988019");
});
it("DODO to WETH three hops swap", async () => {
var b_DODO = await ctxV1.DODO.methods.balanceOf(trader).call()
var b_WETH = await ctxV1.WETH.methods.balanceOf(trader).call()
console.log("Before DODO:" + fromWei(b_DODO, 'ether') + "; WETH:" + fromWei(b_WETH, 'ether'));
//approve DODO entry
await ctxV1.DODO.methods.approve(ctxV2.DODOApprove.options.address, MAX_UINT256).send(ctxV2.sendParam(trader))
//set route path
var routes = [{
address: ctxV1.DODO.options.address,
decimals: 18
}, {
address: ctxV1.USDT.options.address,
decimals: 6
}, {
address: ctxV1.USDC.options.address,
decimals: 6
}, {
address: ctxV1.WETH.options.address,
decimals: 18
}];
var pairs = [{
pair: ctxV1.DODO_USDT.options.address,
base: ctxV1.DODO.options.address,
pairContract: ctxV1.DODO_USDT
}, {
pair: ctxV1.USDT_USDC.options.address,
base: ctxV1.USDT.options.address,
pairContract: ctxV1.USDT_USDC
}, {
pair: ctxV1.WETH_USDC.options.address,
base: ctxV1.WETH.options.address,
pairContract: ctxV1.WETH_USDC
}];
var tx = await logGas(await calcRoute(ctxV2, decimalStr('10'), 0.1, routes, pairs), ctxV2.sendParam(trader), "three hops swap first")
var tx = await logGas(await calcRoute(ctxV2, decimalStr('10'), 0.1, routes, pairs), ctxV2.sendParam(trader), "three hops swap second")
console.log(tx.events['TestAmount']);
var a_DODO = await ctxV1.DODO.methods.balanceOf(trader).call()
var a_WETH = await ctxV1.WETH.methods.balanceOf(trader).call()
console.log("After DODO:" + fromWei(a_DODO, 'ether') + "; WETH:" + fromWei(a_WETH, 'ether'));
console.log("===============================================")
var c_DODO = await ctxV1.DODO.methods.balanceOf(ctxV2.DODOProxyV2.options.address).call()
var c_USDT = await ctxV1.USDT.methods.balanceOf(ctxV2.DODOProxyV2.options.address).call()
var c_USDC = await ctxV1.USDC.methods.balanceOf(ctxV2.DODOProxyV2.options.address).call()
var c_WETH = await ctxV1.WETH.methods.balanceOf(ctxV2.DODOProxyV2.options.address).call()
console.log("Contract DODO:" + fromWei(c_DODO, 'ether') + "; USDT:" + fromWei(c_USDT, 'mwei') + "; USDC:" + fromWei(c_USDC, 'mwei') + "; WETH:" + fromWei(c_WETH, 'ether'));
assert(a_WETH, "4404365055045800");
});
it("ETH to USDT wrap eth and directly swap", async () => {
var b_ETH = await ctxV1.Web3.eth.getBalance(trader)
var b_WETH = await ctxV1.WETH.methods.balanceOf(trader).call()
var b_USDC = await ctxV1.USDC.methods.balanceOf(trader).call()
console.log("Before ETH:" + fromWei(b_ETH, 'ether') + "; WETH:" + fromWei(b_WETH, 'ether') + "; USDC:" + fromWei(b_USDC, 'mwei'));
var b_w_eth = await ctxV1.Web3.eth.getBalance(ctxV1.WETH.options.address)
console.log("weth contract Before:" + fromWei(b_w_eth, 'ether'))
//set route path
var routes = [{
address: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
decimals: 18
}, {
address: ctxV1.USDC.options.address,
decimals: 6
}];
var pairs = [{
pair: ctxV1.WETH_USDC.options.address,
base: ctxV1.WETH.options.address,
pairContract: ctxV1.WETH_USDC
}];
await logGas(await calcRoute(ctxV2, decimalStr('1'), 0.1, routes, pairs), ctxV2.sendParam(trader, '1'), "wrap eth and directly swap first")
await logGas(await calcRoute(ctxV2, decimalStr('1'), 0.1, routes, pairs), ctxV2.sendParam(trader, '1'), "wrap eth and directly swap second")
var a_ETH = await ctxV1.Web3.eth.getBalance(trader)
var a_WETH = await ctxV1.WETH.methods.balanceOf(trader).call()
var a_USDC = await ctxV1.USDC.methods.balanceOf(trader).call()
console.log("After ETH:" + fromWei(a_ETH, 'ether') + "; WETH:" + fromWei(a_WETH, 'ether') + "; USDC:" + fromWei(a_USDC, 'mwei'));
console.log("===============================================")
var c_ETH = await ctxV1.Web3.eth.getBalance(ctxV2.DODOProxyV2.options.address)
var c_WETH = await ctxV1.WETH.methods.balanceOf(ctxV2.DODOProxyV2.options.address).call()
var c_USDT = await ctxV1.USDT.methods.balanceOf(ctxV2.DODOProxyV2.options.address).call()
var c_USDC = await ctxV1.USDC.methods.balanceOf(ctxV2.DODOProxyV2.options.address).call()
console.log("Contract ETH:" + fromWei(c_ETH, 'ether') + "; WETH:" + fromWei(c_WETH, 'ether') + "; USDT:" + fromWei(c_USDT, 'mwei') + "; USDC:" + fromWei(c_USDC, 'mwei'));
var a_w_eth = await ctxV1.Web3.eth.getBalance(ctxV1.WETH.options.address)
console.log("weth contract After:" + fromWei(a_w_eth, 'ether'))
assert(a_USDC, "869508322");
});
it("ETH to USDT wrap eth and two hops swap", async () => {
var b_ETH = await ctxV1.Web3.eth.getBalance(trader)
var b_WETH = await ctxV1.WETH.methods.balanceOf(trader).call()
var b_USDT = await ctxV1.USDT.methods.balanceOf(trader).call()
console.log("Before ETH:" + fromWei(b_ETH, 'ether') + "; WETH:" + fromWei(b_WETH, 'ether') + "; USDT:" + fromWei(b_USDT, 'mwei'));
var b_w_eth = await ctxV1.Web3.eth.getBalance(ctxV1.WETH.options.address)
console.log("weth contract Before:" + fromWei(b_w_eth, 'ether'))
//set route path
var routes = [{
address: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
decimals: 18
}, {
address: ctxV1.USDC.options.address,
decimals: 6
}, {
address: ctxV1.USDT.options.address,
decimals: 6
}];
var pairs = [{
pair: ctxV1.WETH_USDC.options.address,
base: ctxV1.WETH.options.address,
pairContract: ctxV1.WETH_USDC
}, {
pair: ctxV1.USDT_USDC.options.address,
base: ctxV1.USDT.options.address,
pairContract: ctxV1.USDT_USDC
}];
await logGas(await calcRoute(ctxV2, decimalStr('1'), 0.1, routes, pairs), ctxV2.sendParam(trader, '1'), "wrap eth and two hops swap first")
await logGas(await calcRoute(ctxV2, decimalStr('1'), 0.1, routes, pairs), ctxV2.sendParam(trader, '1'), "wrap eth and two hops swap second")
var a_ETH = await ctxV1.Web3.eth.getBalance(trader)
var a_WETH = await ctxV1.WETH.methods.balanceOf(trader).call()
var a_USDT = await ctxV1.USDT.methods.balanceOf(trader).call()
console.log("After ETH:" + fromWei(a_ETH, 'ether') + "; WETH:" + fromWei(a_WETH, 'ether') + "; USDT:" + fromWei(a_USDT, 'mwei'));
console.log("===============================================")
var c_ETH = await ctxV1.Web3.eth.getBalance(ctxV2.DODOProxyV2.options.address)
var c_WETH = await ctxV1.WETH.methods.balanceOf(ctxV2.DODOProxyV2.options.address).call()
var c_USDT = await ctxV1.USDT.methods.balanceOf(ctxV2.DODOProxyV2.options.address).call()
var c_USDC = await ctxV1.USDC.methods.balanceOf(ctxV2.DODOProxyV2.options.address).call()
console.log("Contract ETH:" + fromWei(c_ETH, 'ether') + "; WETH:" + fromWei(c_WETH, 'ether') + "; USDT:" + fromWei(c_USDT, 'mwei') + "; USDC:" + fromWei(c_USDC, 'mwei'));
var a_w_eth = await ctxV1.Web3.eth.getBalance(ctxV1.WETH.options.address)
console.log("weth contract After:" + fromWei(a_w_eth, 'ether'))
assert(a_USDT, "866832169");
});
it("DODO to ETH unwrap eth and three hops swap", async () => {
var b_DODO = await ctxV1.DODO.methods.balanceOf(trader).call()
var b_ETH = await ctxV1.Web3.eth.getBalance(trader)
var b_WETH = await ctxV1.WETH.methods.balanceOf(trader).call()
console.log("User Before ETH:" + fromWei(b_ETH, 'ether') + "; WETH:" + fromWei(b_WETH, 'ether') + "; DODO:" + fromWei(b_DODO, 'ether'));
var b_w_eth = await ctxV1.Web3.eth.getBalance(ctxV1.WETH.options.address)
console.log("weth contract Before:" + fromWei(b_w_eth, 'ether'))
//approve DODO entry
await ctxV1.DODO.methods.approve(ctxV2.DODOApprove.options.address, MAX_UINT256).send(ctxV2.sendParam(trader))
//set route path
var routes = [{
address: ctxV1.DODO.options.address,
decimals: 18
}, {
address: ctxV1.USDT.options.address,
decimals: 6
}, {
address: ctxV1.USDC.options.address,
decimals: 6
}, {
address: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
decimals: 18
}];
var pairs = [{
pair: ctxV1.DODO_USDT.options.address,
base: ctxV1.DODO.options.address,
pairContract: ctxV1.DODO_USDT
}, {
pair: ctxV1.USDT_USDC.options.address,
base: ctxV1.USDT.options.address,
pairContract: ctxV1.USDT_USDC
}, {
pair: ctxV1.WETH_USDC.options.address,
base: ctxV1.WETH.options.address,
pairContract: ctxV1.WETH_USDC
}];
var tx = await logGas(await calcRoute(ctxV2, decimalStr('100'), 0.1, routes, pairs), ctxV2.sendParam(trader), "unwrap eth and three hops swap first")
var tx = await logGas(await calcRoute(ctxV2, decimalStr('100'), 0.1, routes, pairs), ctxV2.sendParam(trader), "unwrap eth and three hops swap second")
var a_ETH = await ctxV1.Web3.eth.getBalance(trader)
var a_WETH = await ctxV1.WETH.methods.balanceOf(trader).call()
var a_DODO = await ctxV1.DODO.methods.balanceOf(trader).call()
console.log("After ETH:" + fromWei(a_ETH, 'ether') + "; WETH:" + fromWei(a_WETH, 'ether') + "; DODO:" + fromWei(a_DODO, 'ether'));
console.log("===============================================")
var c_ETH = await ctxV1.Web3.eth.getBalance(ctxV2.DODOProxyV2.options.address)
var c_WETH = await ctxV1.WETH.methods.balanceOf(ctxV2.DODOProxyV2.options.address).call()
var c_USDT = await ctxV1.USDT.methods.balanceOf(ctxV2.DODOProxyV2.options.address).call()
var c_USDC = await ctxV1.USDC.methods.balanceOf(ctxV2.DODOProxyV2.options.address).call()
var c_DODO = await ctxV1.DODO.methods.balanceOf(ctxV2.DODOProxyV2.options.address).call()
console.log("Contract ETH:" + fromWei(c_ETH, 'ether') + "; WETH:" + fromWei(c_WETH, 'ether') + "; USDT:" + fromWei(c_USDT, 'mwei') + "; USDC:" + fromWei(c_USDC, 'mwei') + "; DODO:" + fromWei(c_DODO, "ether"));
var w_eth = await ctxV1.Web3.eth.getBalance(ctxV1.WETH.options.address)
console.log("weth contract After:" + fromWei(w_eth, 'ether'))
assert(tx.events['OrderHistory'].returnValues['returnAmount'], "22004556829826281");
});
});
}); | the_stack |
import { assign, defaults, differenceBy, each, flatMap, groupBy, map, reverse, uniqBy } from 'lodash';
// import * as _ from 'lodash';
import { Observable, Subject } from 'rxjs';
import {
createConnection,
CodeLens,
CompletionItem,
CompletionList,
Diagnostic,
DiagnosticSeverity,
DidChangeTextDocumentParams,
Files,
Hover,
InitializeParams,
IConnection,
Location,
ParameterInformation,
Position,
Range,
ServerCapabilities,
SignatureHelp,
SignatureInformation,
StreamMessageReader,
StreamMessageWriter,
SymbolInformation,
TextDocumentEdit,
TextDocumentPositionParams,
TextDocumentSyncKind,
TextEdit,
VersionedTextDocumentIdentifier,
WorkspaceEdit,
} from 'vscode-languageserver';
import { ReactiveClient } from '../lib/reactive/ReactiveClient';
import { DriverState, Models } from '../lib/omnisharp-client';
import { createObservable } from '../lib/operators/create';
import {
ClientCapabilities,
ExtendedServerCapabilities,
GetCodeActionsRequest,
Highlight,
HighlightNotification,
ImplementationRequest,
NavigateRequest,
RunCodeActionRequest,
} from './server-extended';
enum CompletionItemKind {
Text = 1,
Method = 2,
Function = 3,
Constructor = 4,
Field = 5,
Variable = 6,
Class = 7,
Interface = 8,
Module = 9,
Property = 10,
Unit = 11,
Value = 12,
Enum = 13,
Keyword = 14,
Snippet = 15,
Color = 16,
File = 17,
Reference = 18,
}
enum SymbolKind {
File = 1,
Module = 2,
Namespace = 3,
Package = 4,
Class = 5,
Method = 6,
Property = 7,
Field = 8,
Constructor = 9,
Enum = 10,
Interface = 11,
Function = 12,
Variable = 13,
Constant = 14,
String = 15,
Number = 16,
Boolean = 17,
Array = 18,
}
const connection: IConnection = createConnection(new StreamMessageReader(process.stdin), new StreamMessageWriter(process.stdout));
let client: ReactiveClient;
class OpenEditorManager {
private openEditors = new Set<string>();
private _subject = new Subject<{ type: 'add', path: string } | { type: 'delete', path: string }>();
public add(path: string) {
this.openEditors.add(path);
this._subject.next({
type: 'add',
path,
});
}
public delete(path: string) {
this.openEditors.delete(path);
this._subject.next({
type: 'delete',
path,
});
}
public has(path: string) {
return this.openEditors.has(path);
}
public get changes() { return this._subject.asObservable(); }
}
const openEditors = new OpenEditorManager();
// tslint:disable-next-line:variable-name
const ExcludeClassifications = [
Models.HighlightClassification.Number,
Models.HighlightClassification.ExcludedCode,
Models.HighlightClassification.Comment,
Models.HighlightClassification.String,
Models.HighlightClassification.Punctuation,
Models.HighlightClassification.Operator,
Models.HighlightClassification.Keyword,
];
// After the server has started the client sends an initilize request. The server receives
// in the passed params the rootPath of the workspace plus the client capabilites.
// tslint:disable-next-line:max-func-body-length
connection.onInitialize((params: InitializeParams & { capabilities: ClientCapabilities }) => {
const capabilities = params.capabilities;
const enablePackageRestore = capabilities.enablePackageRestore === undefined || capabilities.enablePackageRestore;
client = new ReactiveClient({
projectPath: params.rootPath!,
logger: {
log: message => { connection.telemetry.logEvent({ type: 'log', message }); },
error: message => { connection.telemetry.logEvent({ type: 'error', message }); },
},
serverOptions: {
dotnet: { enablePackageRestore },
},
});
client.observe.diagnostic.subscribe(({ Results }) => {
each(Results, result => {
connection.sendDiagnostics({
uri: toUri(result),
diagnostics: map(result.QuickFixes, getDiagnostic),
});
});
});
if ((<ClientCapabilities>params.capabilities).highlightProvider) {
const highlightsContext = new Map<string, Highlight[]>();
client.observe.updatebuffer.subscribe(context => {
if (openEditors.has(context.request.FileName!)) {
client.highlight({
FileName: context.request.FileName,
ExcludeClassifications,
});
}
});
client.observe.close.subscribe(context => {
if (highlightsContext.has(context.request.FileName!)) {
highlightsContext.delete(context.request.FileName!);
}
});
client.observe.highlight
.bufferToggle(client.observe.highlight.throttleTime(100), () => Observable.timer(100))
.concatMap(items => {
const highlights = map(uniqBy(reverse(items), x => x.request.FileName!), context => {
if (!highlightsContext.has(context.request.FileName!)) {
highlightsContext.set(context.request.FileName!, []);
}
const newHighlights = getHighlights(context.response.Highlights);
const currentHighlights = highlightsContext.get(context.request.FileName!)!;
const added = differenceBy(newHighlights, currentHighlights, x => x.id);
const removeHighlights = differenceBy(currentHighlights, newHighlights, x => x.id);
highlightsContext.set(context.request.FileName!, newHighlights);
return {
uri: toUri({ FileName: context.request.FileName! }),
added,
removed: map(removeHighlights, x => x.id),
};
});
return Observable.from(highlights).concatMap(x => Observable.of(x).delay(10));
})
.subscribe(item => connection.sendNotification(HighlightNotification.type, item));
}
client.observe.events.subscribe(event => {
connection.console.info(JSON.stringify(event));
});
client.observe.requests.subscribe(event => {
connection.console.info(JSON.stringify(event));
});
client.observe.responses.subscribe(event => {
connection.console.info(JSON.stringify(event));
});
/*
* Little big of magic here
* This will wait for the server to update all the buffers after a rename operation
* And then update the diagnostics for all of the buffers.
*/
client.observe.rename
.mergeMap(rename => {
return client.observe.updatebuffer
.debounceTime(1000)
.take(1)
.mergeMap(() => {
// TODO: Add a nicer way to queue many files here to omnisharp...
return Observable.merge(...map(rename.response.Changes, item => client.diagnostics({ FileName: item.FileName })));
});
})
.subscribe();
client.connect();
process.on('uncaughtException', (error: any) => {
connection.telemetry.logEvent({ type: 'error', message: error });
});
return client.state
.filter(x => x === DriverState.Connected)
.take(1)
.do(() => {
// Kick code checking on.
client.diagnostics({});
})
.map(() => ({
capabilities: <ExtendedServerCapabilities & ServerCapabilities>{
//textDocumentSync: TextDocumentSyncKind.Full,
// Not currently supported
textDocumentSync: TextDocumentSyncKind.Incremental,
completionProvider: {
//resolveProvider: true
},
codeLensProvider: {
resolveProvider: true,
},
definitionProvider: true,
documentFormattingProvider: true,
documentOnTypeFormattingProvider: {
firstTriggerCharacter: '}',
moreTriggerCharacter: [';'],
},
documentHighlightProvider: true,
documentRangeFormattingProvider: true,
//documentSymbolProvider: true,
hoverProvider: true,
referencesProvider: true,
renameProvider: true,
signatureHelpProvider: {
triggerCharacters: ['('],
},
workspaceSymbolProvider: true,
extended: {
getCodeActionsProvider: true,
runCodeActionProvider: true,
implementationProvider: true,
navigateProvider: true,
highlightProvider: true,
},
},
}))
.toPromise();
});
connection.onExit(() => {
client.disconnect();
});
// not yet doing this...
// connection.onDidChangeConfiguration((change) => {
// });
connection.onDidChangeWatchedFiles(change => {
each(change.changes, cng => {
client.updatebuffer({
FileName: fromUri(cng),
FromDisk: true,
});
});
});
// ** Do we need this yet? **
// connection.onCompletionResolve((item: CompletionItem) => {
// });
const seq = 0;
const textDocumentChanges = createObservable<DidChangeTextDocumentParams>(observer => {
connection.onDidChangeTextDocument(change => {
observer.next(change);
});
})
.share();
const openBuffer = textDocumentChanges
.filter(x => !openEditors.has(fromUri(x.textDocument)))
.groupBy(x => fromUri(x.textDocument))
.mergeMap(group => {
return group
.windowWhen(() => openEditors.changes
.filter(x => x.type === 'add')
.filter(x => x.path === group.key)
.take(1),
)
.concatAll();
});
Observable.merge(
textDocumentChanges
.filter(x => openEditors.has(fromUri(x.textDocument))),
openBuffer,
)
.concatMap(({ textDocument, contentChanges }) => {
// The editor itself might not support TextDocumentSyncKind.Incremental
// So we check to see if we're getting ranges or not.
if (contentChanges.length === 1 && !contentChanges[0].range) {
// TextDocumentSyncKind.Full
return client.updatebuffer({
FileName: fromUri(textDocument),
Buffer: contentChanges[0].text,
});
} else if (contentChanges.length > 0) {
// TextDocumentSyncKind.Incremental
const changes = map(contentChanges, change =>
(<Models.LinePositionSpanTextChange>{
NewText: change.text,
FileName: fromUri(textDocument),
StartColumn: change.range!.start.character,
StartLine: change.range!.start.line,
EndColumn: change.range!.end.character,
EndLine: change.range!.end.line,
}));
return client.updatebuffer({
FileName: fromUri(textDocument),
Changes: changes,
});
}
return Observable.empty<any>();
})
// .do({
// next() {
// connection.console.info(`sequence ${seq++}`);
// }
// })
.subscribe();
connection.onDidOpenTextDocument(({ textDocument }) => {
client.open({
FileName: fromUri(textDocument),
}).concatMap(() => {
return client.updatebuffer({
FileName: fromUri(textDocument),
Buffer: textDocument.text,
});
})
.subscribe(() => {
openEditors.add(fromUri(textDocument));
});
});
connection.onDidCloseTextDocument(({ textDocument }) => {
client.close({
FileName: fromUri(textDocument),
});
openEditors.delete(fromUri(textDocument));
});
connection.onDidSaveTextDocument(({ textDocument }) => {
client.updatebuffer({
FileName: fromUri(textDocument),
FromDisk: true,
});
});
connection.onDefinition(({ textDocument, position }) => {
return client.gotodefinition({
FileName: fromUri(textDocument),
Column: position.character,
Line: position.line,
})
.map(getLocationPoint)
.toPromise();
});
connection.onCompletion(({ textDocument, position }: TextDocumentPositionParams) => {
return client
.autocomplete({
FileName: fromUri(textDocument),
Column: position.character,
Line: position.line,
WantDocumentationForEveryCompletionResult: true,
WantKind: true,
WantImportableTypes: true,
// WantMethodHeader: true,
WantReturnType: true,
WantSnippet: false,
WordToComplete: '',
})
.map(x => map(x, value => {
return <CompletionItem>{
label: value.DisplayText,
detail: value.Description,
documentation: value.MethodHeader,
filterText: value.CompletionText,
kind: <any>CompletionItemKind[<any>value.Kind],
sortText: value.DisplayText,
};
}))
.map(items => (<CompletionList>{
isIncomplete: false, items,
}))
.toPromise();
});
//connection.onCompletionResolve((x) => {});
connection.onHover(({ textDocument, position }) => {
return client.typelookup({
FileName: fromUri(textDocument),
Column: position.character,
Line: position.line,
})
.map(result => (<Hover>{
contents: `${result.Type || ''} ${result.Documentation || ''}`,
}))
.toPromise();
});
connection.onSignatureHelp(({ textDocument, position }) => {
return client.signatureHelp({
FileName: fromUri(textDocument),
Column: position.character,
Line: position.line,
})
.map(result => (<SignatureHelp>{
activeParameter: result.ActiveParameter,
activeSignature: result.ActiveSignature,
signatures: map(result.Signatures, z => (<SignatureInformation>{
documentation: z.Documentation,
label: z.Label,
parameters: map(z.Parameters, param => (<ParameterInformation>{
documentation: param.Documentation,
label: param.Label,
})),
})),
}))
.toPromise();
});
connection.onReferences(({ context, textDocument, position }) => {
return client.findusages({
FileName: fromUri(textDocument),
Column: position.character,
Line: position.line,
ExcludeDefinition: !context.includeDeclaration,
})
.map(result => map(<Models.DiagnosticLocation[]>result.QuickFixes, getLocation))
.toPromise();
});
connection.onDocumentHighlight(x => {
return client.findusages({
OnlyThisFile: true,
Line: x.position.line,
Column: x.position.character,
FileName: fromUri(x.textDocument)
})
.map(result => map(<Models.DiagnosticLocation[]>result.QuickFixes, getLocation))
.toPromise();
});
//connection.onDocumentSymbol((x) => {});
connection.onWorkspaceSymbol(({ query }) => {
return client.findsymbols({ Filter: query })
.map(results => map(<Models.SymbolLocation[]>results.QuickFixes, fix => (<SymbolInformation>{
kind: <any>SymbolKind[<any>fix.Kind] || SymbolKind.Variable,
name: fix.Text,
location: getLocation(fix),
})))
.toPromise();
});
connection.onCodeLens(({ textDocument }) => {
return client.currentfilemembersasflat({
FileName: fromUri(textDocument),
})
.map(results => {
return map(results, location => {
return <CodeLens>{
data: defaults({ FileName: fromUri(textDocument) }, location),
range: getRange(location),
};
});
})
.toPromise();
});
connection.onCodeLensResolve(codeLens => {
return client.findusages(codeLens.data)
.map(x => {
codeLens.command = {
// TODO: ...?
title: `References (${x.QuickFixes.length})`,
command: `references`,
};
codeLens.data = {
location: getLocation(codeLens.data),
};
return codeLens;
})
.toPromise();
});
// Requires new endpoint
connection.onDocumentFormatting(({ textDocument, options }) => {
return client.codeformat({
WantsTextChanges: true,
FileName: fromUri(textDocument),
})
.map(getTextEdits)
.toPromise();
});
connection.onDocumentRangeFormatting(({ textDocument, options, range }) => {
return client.formatRange({
FileName: fromUri(textDocument),
Column: range.start.character,
Line: range.start.line,
EndColumn: range.end.character,
EndLine: range.end.line,
})
.map(getTextEdits)
.toPromise();
});
connection.onDocumentOnTypeFormatting(({ textDocument, options, position, ch }) => {
return client.formatAfterKeystroke({
FileName: fromUri(textDocument),
Character: ch,
Line: position.line,
Column: position.character,
})
.map(getTextEdits)
.toPromise();
});
connection.onRenameRequest(context => {
return client.rename({
FileName: fromUri(context.textDocument),
Line: context.position.line,
Column: context.position.character,
RenameTo: context.newName,
ApplyTextChanges: false,
WantsTextChanges: true,
})
.map(toWorkspaceEdit)
.toPromise();
});
/* EXTENDED ENDPOINTS */
connection.onRequest(GetCodeActionsRequest.type, ({ textDocument, range, context }) => {
return client.getcodeactions({
FileName: fromUri(textDocument),
Selection: fromRange(range),
})
.map(item => {
const codeActions = map(item.CodeActions, codeAction => {
return {
name: codeAction.Name,
identifier: codeAction.Identifier,
};
});
return { codeActions };
})
.toPromise();
});
connection.onRequest(RunCodeActionRequest.type, ({ textDocument, range, context, identifier }) => {
return client.runcodeaction({
FileName: fromUri(textDocument),
Selection: fromRange(range),
Identifier: identifier,
WantsTextChanges: true,
ApplyTextChanges: false,
})
.map(toWorkspaceEdit)
.toPromise();
});
connection.onRequest(ImplementationRequest.type, ({ textDocument, position }) => {
return client.findimplementations({
FileName: fromUri(textDocument),
Column: position.character,
Line: position.line,
})
.map(z => z.QuickFixes)
.map(getLocationPoints)
.toPromise();
});
connection.onRequest(NavigateRequest.type, params => {
const request = (params.direction === 'up' ?
client.navigateup({
FileName: fromUri(params.textDocument),
Column: params.position.character,
Line: params.position.line,
})
:
client.navigatedown({
FileName: fromUri(params.textDocument),
Column: params.position.character,
Line: params.position.line,
}));
return request
.map(getPosition)
.toPromise();
});
// Listen on the connection
connection.listen();
function getRange(item: { StartColumn: number; StartLine: number; EndColumn: number; EndLine: number; }): Range;
function getRange(item: { Column: number; Line: number; EndColumn: number; EndLine: number; }): Range;
function getRange(item: { Column?: number; Line?: number; StartColumn?: number; StartLine?: number; EndColumn: number; EndLine: number; }) {
return <Range>{
start: {
character: item.Column || item.StartColumn || 0,
line: item.Line || item.StartLine || 0,
},
end: {
character: item.EndColumn,
line: item.EndLine,
},
};
}
function getHighlights(highlights: Models.HighlightSpan[]) {
return map(highlights, getHighlight);
}
function getHighlight(highlight: Models.HighlightSpan) {
const range = getRange(highlight);
return <Highlight>{
id: `${range.start.line}:${range.start.character}|${range.end.line}:${range.end.character}|${highlight.Kind}`,
range,
kind: highlight.Kind,
};
}
function getLocationPoints(fix: { Column: number; Line: number; FileName: string; }[]) {
return map(fix, getLocationPoint);
}
function getLocationPoint(fix: { Column: number; Line: number; FileName: string; }) {
return getLocation(assign(fix, { EndColumn: fix.Column, EndLine: fix.Line }));
}
function getLocation(fix: { Column: number; Line: number; EndColumn: number; EndLine: number; FileName: string; }) {
return <Location>{
uri: toUri(fix),
range: getRange(fix),
};
}
function getPosition(model: Models.NavigateResponse) {
return Position.create(model.Line, model.Column);
}
function getTextEdit(change: Models.LinePositionSpanTextChange) {
return <TextEdit>{
range: getRange(change),
newText: change.NewText,
};
}
function getTextEdits(response: { Changes: Models.LinePositionSpanTextChange[] }) {
return map(response.Changes, getTextEdit);
}
function getDiagnostic(item: Models.DiagnosticLocation) {
let sev: DiagnosticSeverity = DiagnosticSeverity.Error;
if (item.LogLevel === 'Warning') {
sev = DiagnosticSeverity.Warning;
}
if (item.LogLevel === 'Hidden') {
sev = DiagnosticSeverity.Hint;
}
if (item.LogLevel === 'Information') {
sev = DiagnosticSeverity.Information;
}
return <Diagnostic>{
severity: sev,
message: item.Text,
range: getRange(item),
};
}
function fromUri(document: { uri: string; }) {
return Files.uriToFilePath(document.uri)!;
}
function fromRange(range: Range): Models.V2.Range {
return {
Start: {
Column: range.start.character,
Line: range.start.line,
},
End: {
Column: range.end.character,
Line: range.end.line,
},
};
}
function toUri(result: { FileName: string; }) {
return toUriString(result.FileName);
}
function toWorkspaceEdit(item: { Changes: Models.ModifiedFileResponse[] }): WorkspaceEdit {
const changes: { [uri: string]: TextEdit[]; } = {};
each(groupBy(item.Changes, x => x.FileName), (result, key) => {
changes[toUriString(key)] = flatMap(
result,
i => {
return map(i.Changes, getTextEdit);
});
});
const documentChanges = map(groupBy(item.Changes, x => x.FileName), (result, key) => {
return TextDocumentEdit.create(
// TODO: Version?
VersionedTextDocumentIdentifier.create(toUriString(key), 0),
flatMap(
result,
i => map(i.Changes, getTextEdit)
)
);
});
return { documentChanges, changes };
}
// TODO: this code isn't perfect
function toUriString(path: string) {
return `file://${process.platform === 'win32' ? '/' : ''}${path.replace(':', encodeURIComponent(':'))}`;
// tslint:disable-next-line:max-file-line-count
} | the_stack |
module android.view.animation {
import RectF = android.graphics.RectF;
import ArrayList = java.util.ArrayList;
import List = java.util.List;
import Long = java.lang.Long;
import Animation = android.view.animation.Animation;
import Interpolator = android.view.animation.Interpolator;
import Transformation = android.view.animation.Transformation;
/**
* Represents a group of Animations that should be played together.
* The transformation of each individual animation are composed
* together into a single transform.
* If AnimationSet sets any properties that its children also set
* (for example, duration or fillBefore), the values of AnimationSet
* override the child values.
*
* <p>The way that AnimationSet inherits behavior from Animation is important to
* understand. Some of the Animation attributes applied to AnimationSet affect the
* AnimationSet itself, some are pushed down to the children, and some are ignored,
* as follows:
* <ul>
* <li>duration, repeatMode, fillBefore, fillAfter: These properties, when set
* on an AnimationSet object, will be pushed down to all child animations.</li>
* <li>repeatCount, fillEnabled: These properties are ignored for AnimationSet.</li>
* <li>startOffset, shareInterpolator: These properties apply to the AnimationSet itself.</li>
* </ul>
* Starting with {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH},
* the behavior of these properties is the same in XML resources and at runtime (prior to that
* release, the values set in XML were ignored for AnimationSet). That is, calling
* <code>setDuration(500)</code> on an AnimationSet has the same effect as declaring
* <code>android:duration="500"</code> in an XML resource for an AnimationSet object.</p>
*/
export class AnimationSet extends Animation {
private static PROPERTY_FILL_AFTER_MASK:number = 0x1;
private static PROPERTY_FILL_BEFORE_MASK:number = 0x2;
private static PROPERTY_REPEAT_MODE_MASK:number = 0x4;
private static PROPERTY_START_OFFSET_MASK:number = 0x8;
private static PROPERTY_SHARE_INTERPOLATOR_MASK:number = 0x10;
private static PROPERTY_DURATION_MASK:number = 0x20;
private static PROPERTY_MORPH_MATRIX_MASK:number = 0x40;
private static PROPERTY_CHANGE_BOUNDS_MASK:number = 0x80;
private mFlags:number = 0;
private mDirty:boolean;
private mHasAlpha:boolean;
private mAnimations:ArrayList<Animation> = new ArrayList<Animation>();
private mTempTransformation:Transformation = new Transformation();
private mLastEnd:number = 0;
private mStoredOffsets:number[];
///**
// * Constructor used when an AnimationSet is loaded from a resource.
// *
// * @param context Application context to use
// * @param attrs Attribute set from which to read values
// */
//constructor( context:Context, attrs:AttributeSet) {
// super(context, attrs);
// let a:TypedArray = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.AnimationSet);
// this.setFlag(AnimationSet.PROPERTY_SHARE_INTERPOLATOR_MASK, a.getBoolean(com.android.internal.R.styleable.AnimationSet_shareInterpolator, true));
// this.init();
// if (context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
// if (a.hasValue(com.android.internal.R.styleable.AnimationSet_duration)) {
// this.mFlags |= AnimationSet.PROPERTY_DURATION_MASK;
// }
// if (a.hasValue(com.android.internal.R.styleable.AnimationSet_fillBefore)) {
// this.mFlags |= AnimationSet.PROPERTY_FILL_BEFORE_MASK;
// }
// if (a.hasValue(com.android.internal.R.styleable.AnimationSet_fillAfter)) {
// this.mFlags |= AnimationSet.PROPERTY_FILL_AFTER_MASK;
// }
// if (a.hasValue(com.android.internal.R.styleable.AnimationSet_repeatMode)) {
// this.mFlags |= AnimationSet.PROPERTY_REPEAT_MODE_MASK;
// }
// if (a.hasValue(com.android.internal.R.styleable.AnimationSet_startOffset)) {
// this.mFlags |= AnimationSet.PROPERTY_START_OFFSET_MASK;
// }
// }
// a.recycle();
//}
/**
* Constructor to use when building an AnimationSet from code
*
* @param shareInterpolator Pass true if all of the animations in this set
* should use the interpolator associated with this AnimationSet.
* Pass false if each animation should use its own interpolator.
*/
constructor(shareInterpolator=false) {
super();
this.setFlag(AnimationSet.PROPERTY_SHARE_INTERPOLATOR_MASK, shareInterpolator);
this.init();
}
//protected clone():AnimationSet {
// const animation:AnimationSet = <AnimationSet> super.clone();
// animation.mTempTransformation = new Transformation();
// animation.mAnimations = new ArrayList<Animation>();
// const count:number = this.mAnimations.size();
// const animations:ArrayList<Animation> = this.mAnimations;
// for (let i:number = 0; i < count; i++) {
// animation.mAnimations.add(animations.get(i).clone());
// }
// return animation;
//}
private setFlag(mask:number, value:boolean):void {
if (value) {
this.mFlags |= mask;
} else {
this.mFlags &= ~mask;
}
}
private init():void {
this.mStartTime = 0;
}
setFillAfter(fillAfter:boolean):void {
this.mFlags |= AnimationSet.PROPERTY_FILL_AFTER_MASK;
super.setFillAfter(fillAfter);
}
setFillBefore(fillBefore:boolean):void {
this.mFlags |= AnimationSet.PROPERTY_FILL_BEFORE_MASK;
super.setFillBefore(fillBefore);
}
setRepeatMode(repeatMode:number):void {
this.mFlags |= AnimationSet.PROPERTY_REPEAT_MODE_MASK;
super.setRepeatMode(repeatMode);
}
setStartOffset(startOffset:number):void {
this.mFlags |= AnimationSet.PROPERTY_START_OFFSET_MASK;
super.setStartOffset(startOffset);
}
/**
* @hide
*/
hasAlpha():boolean {
if (this.mDirty) {
this.mDirty = this.mHasAlpha = false;
const count:number = this.mAnimations.size();
const animations:ArrayList<Animation> = this.mAnimations;
for (let i:number = 0; i < count; i++) {
if (animations.get(i).hasAlpha()) {
this.mHasAlpha = true;
break;
}
}
}
return this.mHasAlpha;
}
/**
* <p>Sets the duration of every child animation.</p>
*
* @param durationMillis the duration of the animation, in milliseconds, for
* every child in this set
*/
setDuration(durationMillis:number):void {
this.mFlags |= AnimationSet.PROPERTY_DURATION_MASK;
super.setDuration(durationMillis);
this.mLastEnd = this.mStartOffset + this.mDuration;
}
/**
* Add a child animation to this animation set.
* The transforms of the child animations are applied in the order
* that they were added
* @param a Animation to add.
*/
addAnimation(a:Animation):void {
this.mAnimations.add(a);
let noMatrix:boolean = (this.mFlags & AnimationSet.PROPERTY_MORPH_MATRIX_MASK) == 0;
if (noMatrix && a.willChangeTransformationMatrix()) {
this.mFlags |= AnimationSet.PROPERTY_MORPH_MATRIX_MASK;
}
let changeBounds:boolean = (this.mFlags & AnimationSet.PROPERTY_CHANGE_BOUNDS_MASK) == 0;
if (changeBounds && a.willChangeBounds()) {
this.mFlags |= AnimationSet.PROPERTY_CHANGE_BOUNDS_MASK;
}
if ((this.mFlags & AnimationSet.PROPERTY_DURATION_MASK) == AnimationSet.PROPERTY_DURATION_MASK) {
this.mLastEnd = this.mStartOffset + this.mDuration;
} else {
if (this.mAnimations.size() == 1) {
this.mDuration = a.getStartOffset() + a.getDuration();
this.mLastEnd = this.mStartOffset + this.mDuration;
} else {
this.mLastEnd = Math.max(this.mLastEnd, a.getStartOffset() + a.getDuration());
this.mDuration = this.mLastEnd - this.mStartOffset;
}
}
this.mDirty = true;
}
/**
* Sets the start time of this animation and all child animations
*
* @see android.view.animation.Animation#setStartTime(long)
*/
setStartTime(startTimeMillis:number):void {
super.setStartTime(startTimeMillis);
const count:number = this.mAnimations.size();
const animations:ArrayList<Animation> = this.mAnimations;
for (let i:number = 0; i < count; i++) {
let a:Animation = animations.get(i);
a.setStartTime(startTimeMillis);
}
}
getStartTime():number {
let startTime:number = Long.MAX_VALUE;
const count:number = this.mAnimations.size();
const animations:ArrayList<Animation> = this.mAnimations;
for (let i:number = 0; i < count; i++) {
let a:Animation = animations.get(i);
startTime = Math.min(startTime, a.getStartTime());
}
return startTime;
}
restrictDuration(durationMillis:number):void {
super.restrictDuration(durationMillis);
const animations:ArrayList<Animation> = this.mAnimations;
let count:number = animations.size();
for (let i:number = 0; i < count; i++) {
animations.get(i).restrictDuration(durationMillis);
}
}
/**
* The duration of an AnimationSet is defined to be the
* duration of the longest child animation.
*
* @see android.view.animation.Animation#getDuration()
*/
getDuration():number {
const animations:ArrayList<Animation> = this.mAnimations;
const count:number = animations.size();
let duration:number = 0;
let durationSet:boolean = (this.mFlags & AnimationSet.PROPERTY_DURATION_MASK) == AnimationSet.PROPERTY_DURATION_MASK;
if (durationSet) {
duration = this.mDuration;
} else {
for (let i:number = 0; i < count; i++) {
duration = Math.max(duration, animations.get(i).getDuration());
}
}
return duration;
}
/**
* The duration hint of an animation set is the maximum of the duration
* hints of all of its component animations.
*
* @see android.view.animation.Animation#computeDurationHint
*/
computeDurationHint():number {
let duration:number = 0;
const count:number = this.mAnimations.size();
const animations:ArrayList<Animation> = this.mAnimations;
for (let i:number = count - 1; i >= 0; --i) {
const d:number = animations.get(i).computeDurationHint();
if (d > duration)
duration = d;
}
return duration;
}
/**
* @hide
*/
initializeInvalidateRegion(left:number, top:number, right:number, bottom:number):void {
const region:RectF = this.mPreviousRegion;
region.set(left, top, right, bottom);
region.inset(-1.0, -1.0);
if (this.mFillBefore) {
const count:number = this.mAnimations.size();
const animations:ArrayList<Animation> = this.mAnimations;
const temp:Transformation = this.mTempTransformation;
const previousTransformation:Transformation = this.mPreviousTransformation;
for (let i:number = count - 1; i >= 0; --i) {
const a:Animation = animations.get(i);
if (!a.isFillEnabled() || a.getFillBefore() || a.getStartOffset() == 0) {
temp.clear();
const interpolator:Interpolator = a.mInterpolator;
a.applyTransformation(interpolator != null ? interpolator.getInterpolation(0.0) : 0.0, temp);
previousTransformation.compose(temp);
}
}
}
}
/**
* The transformation of an animation set is the concatenation of all of its
* component animations.
*
* @see android.view.animation.Animation#getTransformation
*/
getTransformation(currentTime:number, t:Transformation):boolean {
const count:number = this.mAnimations.size();
const animations:ArrayList<Animation> = this.mAnimations;
const temp:Transformation = this.mTempTransformation;
let more:boolean = false;
let started:boolean = false;
let ended:boolean = true;
t.clear();
for (let i:number = count - 1; i >= 0; --i) {
const a:Animation = animations.get(i);
temp.clear();
more = a.getTransformation(currentTime, temp, this.getScaleFactor()) || more;
t.compose(temp);
started = started || a.hasStarted();
ended = a.hasEnded() && ended;
}
if (started && !this.mStarted) {
if (this.mListener != null) {
this.mListener.onAnimationStart(this);
}
this.mStarted = true;
}
if (ended != this.mEnded) {
if (this.mListener != null) {
this.mListener.onAnimationEnd(this);
}
this.mEnded = ended;
}
return more;
}
/**
* @see android.view.animation.Animation#scaleCurrentDuration(float)
*/
scaleCurrentDuration(scale:number):void {
const animations:ArrayList<Animation> = this.mAnimations;
let count:number = animations.size();
for (let i:number = 0; i < count; i++) {
animations.get(i).scaleCurrentDuration(scale);
}
}
/**
* @see android.view.animation.Animation#initialize(int, int, int, int)
*/
initialize(width:number, height:number, parentWidth:number, parentHeight:number):void {
super.initialize(width, height, parentWidth, parentHeight);
let durationSet:boolean = (this.mFlags & AnimationSet.PROPERTY_DURATION_MASK) == AnimationSet.PROPERTY_DURATION_MASK;
let fillAfterSet:boolean = (this.mFlags & AnimationSet.PROPERTY_FILL_AFTER_MASK) == AnimationSet.PROPERTY_FILL_AFTER_MASK;
let fillBeforeSet:boolean = (this.mFlags & AnimationSet.PROPERTY_FILL_BEFORE_MASK) == AnimationSet.PROPERTY_FILL_BEFORE_MASK;
let repeatModeSet:boolean = (this.mFlags & AnimationSet.PROPERTY_REPEAT_MODE_MASK) == AnimationSet.PROPERTY_REPEAT_MODE_MASK;
let shareInterpolator:boolean = (this.mFlags & AnimationSet.PROPERTY_SHARE_INTERPOLATOR_MASK) == AnimationSet.PROPERTY_SHARE_INTERPOLATOR_MASK;
let startOffsetSet:boolean = (this.mFlags & AnimationSet.PROPERTY_START_OFFSET_MASK) == AnimationSet.PROPERTY_START_OFFSET_MASK;
if (shareInterpolator) {
this.ensureInterpolator();
}
const children:ArrayList<Animation> = this.mAnimations;
const count:number = children.size();
const duration:number = this.mDuration;
const fillAfter:boolean = this.mFillAfter;
const fillBefore:boolean = this.mFillBefore;
const repeatMode:number = this.mRepeatMode;
const interpolator:Interpolator = this.mInterpolator;
const startOffset:number = this.mStartOffset;
let storedOffsets:number[] = this.mStoredOffsets;
if (startOffsetSet) {
if (storedOffsets == null || storedOffsets.length != count) {
storedOffsets = this.mStoredOffsets = androidui.util.ArrayCreator.newNumberArray(count);
}
} else if (storedOffsets != null) {
storedOffsets = this.mStoredOffsets = null;
}
for (let i:number = 0; i < count; i++) {
let a:Animation = children.get(i);
if (durationSet) {
a.setDuration(duration);
}
if (fillAfterSet) {
a.setFillAfter(fillAfter);
}
if (fillBeforeSet) {
a.setFillBefore(fillBefore);
}
if (repeatModeSet) {
a.setRepeatMode(repeatMode);
}
if (shareInterpolator) {
a.setInterpolator(interpolator);
}
if (startOffsetSet) {
let offset:number = a.getStartOffset();
a.setStartOffset(offset + startOffset);
storedOffsets[i] = offset;
}
a.initialize(width, height, parentWidth, parentHeight);
}
}
reset():void {
super.reset();
this.restoreChildrenStartOffset();
}
/**
* @hide
*/
restoreChildrenStartOffset():void {
const offsets:number[] = this.mStoredOffsets;
if (offsets == null)
return;
const children:ArrayList<Animation> = this.mAnimations;
const count:number = children.size();
for (let i:number = 0; i < count; i++) {
children.get(i).setStartOffset(offsets[i]);
}
}
/**
* @return All the child animations in this AnimationSet. Note that
* this may include other AnimationSets, which are not expanded.
*/
getAnimations():List<Animation> {
return this.mAnimations;
}
willChangeTransformationMatrix():boolean {
return (this.mFlags & AnimationSet.PROPERTY_MORPH_MATRIX_MASK) == AnimationSet.PROPERTY_MORPH_MATRIX_MASK;
}
willChangeBounds():boolean {
return (this.mFlags & AnimationSet.PROPERTY_CHANGE_BOUNDS_MASK) == AnimationSet.PROPERTY_CHANGE_BOUNDS_MASK;
}
}
} | the_stack |
import * as THREE from 'three';
const container = document.createElement('div');
const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 1000);
const scene = new THREE.Scene();
const renderer = new THREE.WebGLRenderer({ antialias: true });
const group = new THREE.Group();
let targetRotation = 0;
let targetRotationOnPointerDown = 0;
let pointerX = 0;
let pointerXOnPointerDown = 0;
let windowHalfX = window.innerWidth / 2;
init();
animate();
interface ExtrudeSettings {
depth: number;
bevelEnabled: boolean;
bevelSegments: number;
steps: number;
bevelSize: number;
bevelThickness: number;
}
function init() {
document.body.appendChild(container);
scene.background = new THREE.Color(0xf0f0f0);
camera.position.set(0, 150, 500);
scene.add(camera);
const light = new THREE.PointLight(0xffffff, 0.8);
camera.add(light);
group.position.y = 50;
scene.add(group);
const loader = new THREE.TextureLoader();
const texture = loader.load('textures/uv_grid_opengl.jpg');
// it's necessary to apply these settings in order to correctly display the texture on a shape geometry
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(0.008, 0.008);
function addShape(
shape: THREE.Shape,
extrudeSettings: ExtrudeSettings,
color: number,
x: number,
y: number,
z: number,
rx: number,
ry: number,
rz: number,
s: number,
) {
// flat shape with texture
// note: default UVs generated by THREE.ShapeGeometry are simply the x- and y-coordinates of the vertices
let geometry = new THREE.ShapeGeometry(shape);
let mesh = new THREE.Mesh(geometry, new THREE.MeshPhongMaterial({ side: THREE.DoubleSide, map: texture }));
mesh.position.set(x, y, z - 175);
mesh.rotation.set(rx, ry, rz);
mesh.scale.set(s, s, s);
group.add(mesh);
// flat shape
geometry = new THREE.ShapeGeometry(shape);
mesh = new THREE.Mesh(geometry, new THREE.MeshPhongMaterial({ color, side: THREE.DoubleSide }));
mesh.position.set(x, y, z - 125);
mesh.rotation.set(rx, ry, rz);
mesh.scale.set(s, s, s);
group.add(mesh);
// extruded shape
geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings);
mesh = new THREE.Mesh(geometry, new THREE.MeshPhongMaterial({ color }));
mesh.position.set(x, y, z - 75);
mesh.rotation.set(rx, ry, rz);
mesh.scale.set(s, s, s);
group.add(mesh);
addLineShape(shape, color, x, y, z, rx, ry, rz, s);
}
function addLineShape(
shape: THREE.Path,
color: number,
x: number,
y: number,
z: number,
rx: number,
ry: number,
rz: number,
s: number,
) {
// lines
shape.autoClose = true;
const points = shape.getPoints();
const spacedPoints = shape.getSpacedPoints(50);
const geometryPoints = new THREE.BufferGeometry().setFromPoints(points);
const geometrySpacedPoints = new THREE.BufferGeometry().setFromPoints(spacedPoints);
// solid line
let line = new THREE.Line(geometryPoints, new THREE.LineBasicMaterial({ color }));
line.position.set(x, y, z - 25);
line.rotation.set(rx, ry, rz);
line.scale.set(s, s, s);
group.add(line);
// line from equidistance sampled points
line = new THREE.Line(geometrySpacedPoints, new THREE.LineBasicMaterial({ color }));
line.position.set(x, y, z + 25);
line.rotation.set(rx, ry, rz);
line.scale.set(s, s, s);
group.add(line);
// vertices from real points
let particles = new THREE.Points(geometryPoints, new THREE.PointsMaterial({ color, size: 4 }));
particles.position.set(x, y, z + 75);
particles.rotation.set(rx, ry, rz);
particles.scale.set(s, s, s);
group.add(particles);
// equidistance sampled points
particles = new THREE.Points(geometrySpacedPoints, new THREE.PointsMaterial({ color, size: 4 }));
particles.position.set(x, y, z + 125);
particles.rotation.set(rx, ry, rz);
particles.scale.set(s, s, s);
group.add(particles);
}
// California
const californiaPts: THREE.Vector2[] = [];
californiaPts.push(new THREE.Vector2(610, 320));
californiaPts.push(new THREE.Vector2(450, 300));
californiaPts.push(new THREE.Vector2(392, 392));
californiaPts.push(new THREE.Vector2(266, 438));
californiaPts.push(new THREE.Vector2(190, 570));
californiaPts.push(new THREE.Vector2(190, 600));
californiaPts.push(new THREE.Vector2(160, 620));
californiaPts.push(new THREE.Vector2(160, 650));
californiaPts.push(new THREE.Vector2(180, 640));
californiaPts.push(new THREE.Vector2(165, 680));
californiaPts.push(new THREE.Vector2(150, 670));
californiaPts.push(new THREE.Vector2(90, 737));
californiaPts.push(new THREE.Vector2(80, 795));
californiaPts.push(new THREE.Vector2(50, 835));
californiaPts.push(new THREE.Vector2(64, 870));
californiaPts.push(new THREE.Vector2(60, 945));
californiaPts.push(new THREE.Vector2(300, 945));
californiaPts.push(new THREE.Vector2(300, 743));
californiaPts.push(new THREE.Vector2(600, 473));
californiaPts.push(new THREE.Vector2(626, 425));
californiaPts.push(new THREE.Vector2(600, 370));
californiaPts.push(new THREE.Vector2(610, 320));
californiaPts.map(vec => vec.multiplyScalar(0.25));
const californiaShape = new THREE.Shape(californiaPts);
// Triangle
const triangleShape = new THREE.Shape().moveTo(80, 20).lineTo(40, 80).lineTo(120, 80).lineTo(80, 20); // close path
// Heart
const x = 0;
const y = 0;
const heartShape = new THREE.Shape() // From http://blog.burlock.org/html5/130-paths
.moveTo(x + 25, y + 25)
.bezierCurveTo(x + 25, y + 25, x + 20, y, x, y)
.bezierCurveTo(x - 30, y, x - 30, y + 35, x - 30, y + 35)
.bezierCurveTo(x - 30, y + 55, x - 10, y + 77, x + 25, y + 95)
.bezierCurveTo(x + 60, y + 77, x + 80, y + 55, x + 80, y + 35)
.bezierCurveTo(x + 80, y + 35, x + 80, y, x + 50, y)
.bezierCurveTo(x + 35, y, x + 25, y + 25, x + 25, y + 25);
// Square
const sqLength = 80;
const squareShape = new THREE.Shape()
.moveTo(0, 0)
.lineTo(0, sqLength)
.lineTo(sqLength, sqLength)
.lineTo(sqLength, 0)
.lineTo(0, 0);
// Rounded rectangle
const roundedRectShape = new THREE.Shape();
(function roundedRect(ctx, x, y, width, height, radius) {
ctx.moveTo(x, y + radius);
ctx.lineTo(x, y + height - radius);
ctx.quadraticCurveTo(x, y + height, x + radius, y + height);
ctx.lineTo(x + width - radius, y + height);
ctx.quadraticCurveTo(x + width, y + height, x + width, y + height - radius);
ctx.lineTo(x + width, y + radius);
ctx.quadraticCurveTo(x + width, y, x + width - radius, y);
ctx.lineTo(x + radius, y);
ctx.quadraticCurveTo(x, y, x, y + radius);
})(roundedRectShape, 0, 0, 50, 50, 20);
// Track
const trackShape = new THREE.Shape()
.moveTo(40, 40)
.lineTo(40, 160)
.absarc(60, 160, 20, Math.PI, 0, true)
.lineTo(80, 40)
.absarc(60, 40, 20, 2 * Math.PI, Math.PI, true);
// Circle
const circleRadius = 40;
const circleShape = new THREE.Shape()
.moveTo(0, circleRadius)
.quadraticCurveTo(circleRadius, circleRadius, circleRadius, 0)
.quadraticCurveTo(circleRadius, -circleRadius, 0, -circleRadius)
.quadraticCurveTo(-circleRadius, -circleRadius, -circleRadius, 0)
.quadraticCurveTo(-circleRadius, circleRadius, 0, circleRadius);
// Fish
const fishShape = new THREE.Shape()
.moveTo(x, y)
.quadraticCurveTo(x + 50, y - 80, x + 90, y - 10)
.quadraticCurveTo(x + 100, y - 10, x + 115, y - 40)
.quadraticCurveTo(x + 115, y, x + 115, y + 40)
.quadraticCurveTo(x + 100, y + 10, x + 90, y + 10)
.quadraticCurveTo(x + 50, y + 80, x, y);
// Arc circle
const arcShape = new THREE.Shape().moveTo(50, 10).absarc(10, 10, 40, 0, Math.PI * 2, false);
const holePath = new THREE.Path().moveTo(20, 10).absarc(10, 10, 10, 0, Math.PI * 2, true);
arcShape.holes.push(holePath);
// Smiley
const smileyShape = new THREE.Shape().moveTo(80, 40).absarc(40, 40, 40, 0, Math.PI * 2, false);
const smileyEye1Path = new THREE.Path().moveTo(35, 20).absellipse(25, 20, 10, 10, 0, Math.PI * 2, true, 0);
const smileyEye2Path = new THREE.Path().moveTo(65, 20).absarc(55, 20, 10, 0, Math.PI * 2, true);
const smileyMouthPath = new THREE.Path()
.moveTo(20, 40)
.quadraticCurveTo(40, 60, 60, 40)
.bezierCurveTo(70, 45, 70, 50, 60, 60)
.quadraticCurveTo(40, 80, 20, 60)
.quadraticCurveTo(5, 50, 20, 40);
smileyShape.holes.push(smileyEye1Path);
smileyShape.holes.push(smileyEye2Path);
smileyShape.holes.push(smileyMouthPath);
// Spline shape
const splinepts = [];
splinepts.push(new THREE.Vector2(70, 20));
splinepts.push(new THREE.Vector2(80, 90));
splinepts.push(new THREE.Vector2(-30, 70));
splinepts.push(new THREE.Vector2(0, 0));
const splineShape = new THREE.Shape().moveTo(0, 0).splineThru(splinepts);
const extrudeSettings: ExtrudeSettings = {
depth: 8,
bevelEnabled: true,
bevelSegments: 2,
steps: 2,
bevelSize: 1,
bevelThickness: 1,
};
// addShape( shape, color, x, y, z, rx, ry,rz, s );
addShape(californiaShape, extrudeSettings, 0xf08000, -300, -100, 0, 0, 0, 0, 1);
addShape(triangleShape, extrudeSettings, 0x8080f0, -180, 0, 0, 0, 0, 0, 1);
addShape(roundedRectShape, extrudeSettings, 0x008000, -150, 150, 0, 0, 0, 0, 1);
addShape(trackShape, extrudeSettings, 0x008080, 200, -100, 0, 0, 0, 0, 1);
addShape(squareShape, extrudeSettings, 0x0040f0, 150, 100, 0, 0, 0, 0, 1);
addShape(heartShape, extrudeSettings, 0xf00000, 60, 100, 0, 0, 0, Math.PI, 1);
addShape(circleShape, extrudeSettings, 0x00f000, 120, 250, 0, 0, 0, 0, 1);
addShape(fishShape, extrudeSettings, 0x404040, -60, 200, 0, 0, 0, 0, 1);
addShape(smileyShape, extrudeSettings, 0xf000f0, -200, 250, 0, 0, 0, Math.PI, 1);
addShape(arcShape, extrudeSettings, 0x804000, 150, 0, 0, 0, 0, 0, 1);
addShape(splineShape, extrudeSettings, 0x808080, -50, -100, 0, 0, 0, 0, 1);
addLineShape(arcShape.holes[0], 0x804000, 150, 0, 0, 0, 0, 0, 1);
smileyShape.holes.forEach(path => {
addLineShape(path, 0xf000f0, -200, 250, 0, 0, 0, Math.PI, 1);
});
//
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
container.style.touchAction = 'none';
container.addEventListener('pointerdown', onPointerDown);
//
window.addEventListener('resize', onWindowResize);
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
//
function onPointerDown(event: PointerEvent) {
if (event.isPrimary) return;
pointerXOnPointerDown = event.clientX - windowHalfX;
targetRotationOnPointerDown = targetRotation;
document.addEventListener('pointermove', onPointerMove);
document.addEventListener('pointerup', onPointerUp);
}
function onPointerMove(event: PointerEvent) {
if (event.isPrimary) return;
pointerX = event.clientX - windowHalfX;
targetRotation = targetRotationOnPointerDown + (pointerX - pointerXOnPointerDown) * 0.02;
}
function onPointerUp() {
document.removeEventListener('pointermove', onPointerMove);
document.removeEventListener('pointerup', onPointerUp);
}
//
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
group.rotation.y += (targetRotation - group.rotation.y) * 0.05;
renderer.render(scene, camera);
} | the_stack |
import options from '../options';
import type {
HookType,
Ref as ReactRef,
ContextInternal as ReactContext,
} from '../types';
import type {
Inputs,
Ref,
PropRef,
Reducer,
HookState,
EffectHookState,
Component,
HookTypeMap,
StateUpdater,
EffectCallback,
} from './types';
let currentHook = 0;
let currentIndex: number;
let currentComponent: Component | undefined;
let afterPaintEffects: Component[] = [];
const oldBeforeRender = options._render;
const oldAfterDiff = options.diffed;
const oldCommit = options._commit;
const oldBeforeUnmount = options.unmount;
const RAF_TIMEOUT = 100;
let prevRaf: typeof options['requestAnimationFrame'];
options._render = (vnode) => {
if (oldBeforeRender) oldBeforeRender(vnode);
currentComponent = vnode._component;
currentIndex = 0;
const hooks = currentComponent!.__hooks;
if (hooks) {
hooks._pendingEffects.forEach(invokeCleanup);
hooks._pendingEffects.forEach(invokeEffect);
hooks._pendingEffects = [];
}
};
options.diffed = (vnode) => {
oldAfterDiff?.(vnode);
const component = vnode._component as Component;
if (component?.__hooks?._pendingEffects.length) {
afterPaint(afterPaintEffects.push(component));
}
};
options._commit = (vnode, commitQueue) => {
let newCommitQueue = commitQueue;
commitQueue.some((component: Component) => {
try {
component._renderCallbacks.forEach(invokeCleanup);
component._renderCallbacks = component._renderCallbacks.filter((cb) =>
'_value' in cb ? invokeEffect(cb) : true,
);
} catch (error) {
for (const component of commitQueue) {
if (component._renderCallbacks) component._renderCallbacks = [];
}
newCommitQueue = [];
options._catchError(error, component._vnode!);
}
});
oldCommit?.(vnode, newCommitQueue);
};
options.unmount = (vnode) => {
oldBeforeUnmount?.(vnode);
const component = vnode._component as Component;
if (component?.__hooks) {
try {
component.__hooks._list.forEach(invokeCleanup);
} catch (error) {
options._catchError(error, component._vnode!);
}
}
};
/**
* Get a hook's state from the currentComponent
*/
function getHookState<T extends HookType>(
index: number,
type: T,
): T extends keyof HookTypeMap ? HookTypeMap[T] : never {
options._hook?.(currentComponent!, index, currentHook || type);
currentHook = 0;
// Largely inspired by:
// * https://github.com/michael-klein/funcy.js/blob/f6be73468e6ec46b0ff5aa3cc4c9baf72a29025a/src/hooks/core_hooks.mjs
// * https://github.com/michael-klein/funcy.js/blob/650beaa58c43c33a74820a3c98b3c7079cf2e333/src/renderer.mjs
// Other implementations to look at:
// * https://codesandbox.io/s/mnox05qp8
if (currentComponent!.__hooks == null) {
currentComponent!.__hooks = {
_list: [],
_pendingEffects: [],
};
}
const hooks = currentComponent!.__hooks;
if (index >= hooks._list.length) {
hooks._list.push({});
}
return hooks._list[index] as any;
}
/**
* Returns a stateful value, and a function to update it.
* @param initialState The initial value (or a function that returns the initial value)
*/
export function useState<S>(initialState: S | (() => S)): [S, StateUpdater<S>] {
currentHook = 1;
return useReducer(invokeOrReturn as any, initialState) as any;
}
/**
* An alternative to `useState`.
*
* `useReducer` is usually preferable to `useState` when you have complex state logic that involves
* multiple sub-values. It also lets you optimize performance for components that trigger deep
* updates because you can pass `dispatch` down instead of callbacks.
* @param reducer Given the current state and an action, returns the new state
* @param initialState The initial value to store as state
*/
export function useReducer<S, A>(
reducer: Reducer<S, A>,
initialState: S,
): [S, (action: A) => void];
/**
* An alternative to `useState`.
*
* `useReducer` is usually preferable to `useState` when you have complex state logic that involves
* multiple sub-values. It also lets you optimize performance for components that trigger deep
* updates because you can pass `dispatch` down instead of callbacks.
* @param reducer Given the current state and an action, returns the new state
* @param initialArg The initial argument to pass to the `init` function
* @param init A function that, given the `initialArg`, returns the initial value to store as state
*/
export function useReducer<S, A, I>(
reducer: Reducer<S, A>,
initialArg: I,
init: (arg: I) => S,
): [S, (action: A) => void];
export function useReducer<S, A, I>(
reducer: Reducer<S, A>,
initialArg: I,
init?: (arg: I) => S,
): [S, (action: A) => void] {
const hookState = getHookState<HookType.useReducer>(currentIndex++, 2);
hookState._reducer = reducer;
if (!hookState._component) {
hookState._component = currentComponent;
hookState._value = [
init ? init(initialArg) : invokeOrReturn(undefined, initialArg),
(action: A) => {
const nextValue = hookState._reducer!(hookState._value[0], action);
if (hookState._value[0] !== nextValue) {
hookState._value = [nextValue, hookState._value[1]];
hookState._component!.setState({});
}
},
];
}
return hookState._value;
}
/**
* Accepts a function that contains imperative, possibly effectful code.
* The effects run after browser paint, without blocking it.
*
* @param effect Imperative function that can return a cleanup function
* @param inputs If present, effect will only activate if the values in the list change (using ===).
*/
export function useEffect(effect: EffectCallback, inputs?: Inputs): void {
const state = getHookState<HookType.useEffect>(currentIndex++, 3);
if (!options._skipEffects && argsChanged(state._args, inputs ?? [])) {
state._value = effect;
state._args = inputs;
currentComponent!.__hooks!._pendingEffects.push(state);
}
}
/**
* Accepts a function that contains imperative, possibly effectful code.
* Use this to read layout from the DOM and synchronously re-render.
* Updates scheduled inside `useLayoutEffect` will be flushed synchronously, after all DOM mutations but before the browser has a chance to paint.
* Prefer the standard `useEffect` hook when possible to avoid blocking visual updates.
*
* @param effect Imperative function that can return a cleanup function
* @param inputs If present, effect will only activate if the values in the list change (using ===).
*/
export function useLayoutEffect(effect: EffectCallback, inputs?: Inputs): void {
const state = getHookState<HookType.useLayoutEffect>(currentIndex++, 4);
if (!options._skipEffects && argsChanged(state._args, inputs ?? [])) {
state._value = effect;
state._args = inputs;
currentComponent!._renderCallbacks.push(state);
}
}
/**
* `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument
* (`initialValue`). The returned object will persist for the full lifetime of the component.
*
* Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable
* value around similar to how you’d use instance fields in classes.
*/
export function useRef<T>(initialValue?: T | null): Ref<T>;
/**
* `useRef` without an initial value is the special case handling `ref` props.
* If you want a non prop-based, mutable ref, you can explicitly give it an initial value of undefined/null/etc.
* You should explicitly set the type parameter for the expected ref value to either a DOM Element like `HTMLInputElement` or a `Component`
*/
export function useRef<T = unknown>(): PropRef<T>;
export function useRef(initialValue?: any): any {
currentHook = 5;
// eslint-disable-next-line react-hooks/exhaustive-deps
return useMemo(() => ({current: initialValue}), []);
}
/**
* @param ref The ref that will be mutated
* @param create The function that will be executed to get the value that will be attached to
* ref.current
* @param inputs If present, effect will only activate if the values in the list change (using ===).
*/
export function useImperativeHandle<T, R extends T>(
ref: ReactRef<T>,
create: () => R,
inputs?: Inputs,
): void {
currentHook = 6;
useLayoutEffect(
() => {
if (typeof ref === 'function') {
ref(create());
} else if (ref) {
ref.current = create();
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
inputs == null ? inputs : [...inputs, ref],
);
}
/**
* Pass a factory function and an array of inputs.
* useMemo will only recompute the memoized value when one of the inputs has changed.
* This optimization helps to avoid expensive calculations on every render.
* If no array is provided, a new value will be computed whenever a new function instance is passed as the first argument.
*/
// for `inputs`, allow undefined, but don't make it optional as that is very likely a mistake
export function useMemo<T>(factory: () => T, inputs: Inputs | undefined): T {
const state = getHookState<HookType.useMemo>(currentIndex++, 7);
if (argsChanged(state._args, inputs ?? [])) {
state._args = inputs;
state._factory = factory;
return (state._value = factory());
}
return state._value;
}
export function useCallback<T extends Function>(
callback: T,
inputs: Inputs,
): T {
currentHook = 8;
// eslint-disable-next-line react-hooks/exhaustive-deps
return useMemo(() => callback, inputs);
}
/**
* Returns the current context value, as given by the nearest context provider for the given context.
* When the provider updates, this Hook will trigger a rerender with the latest context value.
*
* @param context The context you want to use
*/
export function useContext<T>(context: ReactContext<T>): T {
const provider = currentComponent!.context[context._id];
const state = getHookState<HookType.useContext>(currentIndex++, 9);
// The devtools needs access to the context object to
// be able to pull of the default value when no provider
// is present in the tree.
// state._context = context;
if (!provider) return context._defaultValue;
// This is probably not safe to convert to "!"
if (state._value == null) {
state._value = true;
provider.sub(currentComponent);
}
return provider.props.value;
}
/**
* Customize the displayed value in the devtools panel.
*
* @param value Custom hook name or object that is passed to formatter
* @param formatter Formatter to modify value before sending it to the devtools
*/
export function useDebugValue<T>(
value: T,
formatter?: (value: T) => any,
): void {
options.useDebugValue?.(formatter ? formatter(value) : value);
}
/**
* After paint effects consumer.
*/
function flushAfterPaintEffects() {
for (const component of afterPaintEffects) {
if (component._parentRemoteNode) {
try {
component.__hooks!._pendingEffects.forEach(invokeCleanup);
component.__hooks!._pendingEffects.forEach(invokeEffect);
component.__hooks!._pendingEffects = [];
} catch (error) {
component.__hooks!._pendingEffects = [];
options._catchError(error, component._vnode!);
return true;
}
}
}
afterPaintEffects = [];
}
const HAS_RAF = typeof requestAnimationFrame === 'function';
/**
* Schedule a callback to be invoked after the browser has a chance to paint a new frame.
* Do this by combining requestAnimationFrame (rAF) + setTimeout to invoke a callback after
* the next browser frame.
*
* Also, schedule a timeout in parallel to the the rAF to ensure the callback is invoked
* even if RAF doesn't fire (for example if the browser tab is not visible)
*/
function afterNextFrame(callback: () => void) {
const done = () => {
clearTimeout(timeout);
if (HAS_RAF) cancelAnimationFrame(raf);
setTimeout(callback);
};
const timeout = setTimeout(done, RAF_TIMEOUT);
let raf: ReturnType<typeof requestAnimationFrame>;
if (HAS_RAF) {
raf = requestAnimationFrame(done);
}
}
// Note: if someone used options.debounceRendering = requestAnimationFrame,
// then effects will ALWAYS run on the NEXT frame instead of the current one, incurring a ~16ms delay.
// Perhaps this is not such a big deal.
/**
* Schedule afterPaintEffects flush after the browser paints
*/
function afterPaint(newQueueLength: number) {
if (newQueueLength === 1 || prevRaf !== options.requestAnimationFrame) {
prevRaf = options.requestAnimationFrame;
(prevRaf || afterNextFrame)(flushAfterPaintEffects);
}
}
function invokeCleanup(hook: HookState | (() => void)) {
if ('_cleanup' in hook && typeof hook._cleanup === 'function')
hook._cleanup();
}
function invokeEffect(hook: EffectHookState) {
hook._cleanup = hook._value!() as any;
}
function argsChanged(
oldArgs: any[] | ReadonlyArray<any> | undefined,
newArgs: any[] | ReadonlyArray<any>,
) {
return (
!oldArgs ||
oldArgs.length !== newArgs.length ||
newArgs.some((arg, index) => arg !== oldArgs[index])
);
}
function invokeOrReturn<T>(
arg: any,
maybeFunction: T,
): T extends (...args: any) => any ? ReturnType<T> : T {
return typeof maybeFunction === 'function'
? maybeFunction(arg)
: maybeFunction;
} | the_stack |
import { ITextIntentSequenceLabelObjectByPosition} from "./ITextIntentSequenceLabelObjectByPosition";
import { Data } from "./Data";
import { Utility } from "../utility/Utility";
export class ColumnarData extends Data {
public static createColumnarDataFromSamplingExistingColumnarDataUtterances(
existingColumnarData: ColumnarData,
labelColumnIndex: number,
textColumnIndex: number,
weightColumnIndex: number,
linesToSkip: number,
samplingIndexArray: number[]): ColumnarData {
// -------------------------------------------------------------------
const columnarData: ColumnarData =
ColumnarData.createColumnarData(
existingColumnarData.getContent(),
labelColumnIndex,
textColumnIndex,
weightColumnIndex,
linesToSkip);
// -------------------------------------------------------------------
const luUtterances: ITextIntentSequenceLabelObjectByPosition[] = columnarData.luUtterances;
const lengthUtterancesArray: number =
luUtterances.length;
columnarData.luUtterances = [];
for (const index of samplingIndexArray) {
if ((index < 0) || (index > lengthUtterancesArray)) {
Utility.debuggingThrow(`(index|${index}|<0)||(index|${index}|>lengthUtterancesArray|${lengthUtterancesArray}|)`);
}
columnarData.luUtterances.push(luUtterances[index]);
}
// -------------------------------------------------------------------
columnarData.intentInstanceIndexMapArray =
columnarData.collectIntents(columnarData.luUtterances);
columnarData.entityTypeInstanceIndexMapArray =
columnarData.collectEntityTypes(columnarData.luUtterances);
columnarData.intentsUtterancesWeights.intents = columnarData.luUtterances.map(
(entry: ITextIntentSequenceLabelObjectByPosition) => entry.intent);
columnarData.intentsUtterancesWeights.utterances = columnarData.luUtterances.map(
(entry: ITextIntentSequenceLabelObjectByPosition) => entry.text);
columnarData.intentsUtterancesWeights.weights = columnarData.luUtterances.map(
(entry: ITextIntentSequenceLabelObjectByPosition) => entry.weight);
// -------------------------------------------------------------------
return columnarData;
}
public static createColumnarDataFromFilteringExistingColumnarDataUtterances(
existingColumnarData: ColumnarData,
labelColumnIndex: number,
textColumnIndex: number,
weightColumnIndex: number,
linesToSkip: number,
filteringIndexSet: Set<number>): ColumnarData {
// -------------------------------------------------------------------
const columnarData: ColumnarData =
ColumnarData.createColumnarData(
existingColumnarData.getContent(),
labelColumnIndex,
textColumnIndex,
weightColumnIndex,
linesToSkip);
// -------------------------------------------------------------------
const luUtterances: ITextIntentSequenceLabelObjectByPosition[] =
columnarData.luUtterances;
columnarData.luUtterances = luUtterances.filter(
(value: ITextIntentSequenceLabelObjectByPosition,
index: number,
array: ITextIntentSequenceLabelObjectByPosition[]) => {
return (filteringIndexSet.has(index));
});
// -------------------------------------------------------------------
columnarData.intentInstanceIndexMapArray =
columnarData.collectIntents(columnarData.luUtterances);
columnarData.entityTypeInstanceIndexMapArray =
columnarData.collectEntityTypes(columnarData.luUtterances);
columnarData.intentsUtterancesWeights.intents = columnarData.luUtterances.map(
(entry: ITextIntentSequenceLabelObjectByPosition) => entry.intent);
columnarData.intentsUtterancesWeights.utterances = columnarData.luUtterances.map(
(entry: ITextIntentSequenceLabelObjectByPosition) => entry.text);
columnarData.intentsUtterancesWeights.weights = columnarData.luUtterances.map(
(entry: ITextIntentSequenceLabelObjectByPosition) => entry.weight);
// -------------------------------------------------------------------
return columnarData;
}
public static createColumnarData(
content: string,
labelColumnIndex: number,
textColumnIndex: number,
weightColumnIndex: number,
linesToSkip: number): ColumnarData {
// -------------------------------------------------------------------
const columnarData: ColumnarData =
new ColumnarData(
labelColumnIndex,
textColumnIndex,
weightColumnIndex,
linesToSkip);
columnarData.content =
content;
// -------------------------------------------------------------------
columnarData.luUtterances =
columnarData.retrieveColumnarUtterances(content);
// -------------------------------------------------------------------
columnarData.intentInstanceIndexMapArray =
columnarData.collectIntents(columnarData.luUtterances);
columnarData.entityTypeInstanceIndexMapArray =
columnarData.collectEntityTypes(columnarData.luUtterances);
columnarData.intentsUtterancesWeights.intents = columnarData.luUtterances.map(
(entry: ITextIntentSequenceLabelObjectByPosition) => entry.intent);
columnarData.intentsUtterancesWeights.utterances = columnarData.luUtterances.map(
(entry: ITextIntentSequenceLabelObjectByPosition) => entry.text);
columnarData.intentsUtterancesWeights.weights = columnarData.luUtterances.map(
(entry: ITextIntentSequenceLabelObjectByPosition) => entry.weight);
// -------------------------------------------------------------------
return columnarData;
}
protected labelColumnIndex: number = 0;
protected textColumnIndex: number = 1;
protected weightColumnIndex: number = -1;
protected linesToSkip: number = 0;
protected constructor(
labelColumnIndex: number = 0,
textColumnIndex: number = 1,
weightColumnIndex: number = -1,
linesToSkip: number = 0) {
super();
this.labelColumnIndex = labelColumnIndex;
this.textColumnIndex = textColumnIndex;
this.weightColumnIndex = weightColumnIndex;
this.linesToSkip = linesToSkip;
}
public async createDataFromSamplingExistingDataUtterances(
existingData: Data,
labelColumnIndex: number,
textColumnIndex: number,
weightColumnIndex: number,
linesToSkip: number,
samplingIndexArray: number[]): Promise<Data> {
if (!(existingData instanceof ColumnarData)) {
Utility.debuggingThrow("logic error: the input Data object should be a ColumnarData object.");
}
return ColumnarData.createColumnarDataFromSamplingExistingColumnarDataUtterances(
existingData as ColumnarData,
labelColumnIndex,
textColumnIndex,
weightColumnIndex,
linesToSkip,
samplingIndexArray);
}
public async createDataFromFilteringExistingDataUtterances(
existingData: Data,
labelColumnIndex: number,
textColumnIndex: number,
weightColumnIndex: number,
linesToSkip: number,
filteringIndexSet: Set<number>): Promise<Data> {
if (!(existingData instanceof ColumnarData)) {
Utility.debuggingThrow("logic error: the input Data object should be a ColumnarData object.");
}
return ColumnarData.createColumnarDataFromFilteringExistingColumnarDataUtterances(
existingData as ColumnarData,
labelColumnIndex,
textColumnIndex,
weightColumnIndex,
linesToSkip,
filteringIndexSet);
}
public retrieveColumnarUtterances(content: string): ITextIntentSequenceLabelObjectByPosition[] {
// ---- NOTE ---- the return is newly allocated, unlike the one in LuData
const intentsUtterancesWeights: { "intents": string[], "utterances": string[], "weights": number[] } =
Utility.loadLabelUtteranceColumnarContent(
content, // ---- filename: string,
this.getLabelColumnIndex(), // ---- labelColumnIndex: number = 0,
this.getTextColumnIndex(), // ---- textColumnIndex: number = 1,
this.getWeightColumnIndex(), // ---- weightColumnIndex: number = -1,
this.getLinesToSkip(), // ---- lineIndexToStart: number = 0,
"\t", // ---- columnDelimiter: string = "\t",
"\n", // ---- rowDelimiter: string = "\n",
"utf8", // ---- encoding: string = "utf8",
-1, // ---- lineIndexToEnd: number = -1
);
const luUtterances: ITextIntentSequenceLabelObjectByPosition[] = [];
const intents: string[] = intentsUtterancesWeights.intents;
const utterances: string[] = intentsUtterancesWeights.utterances;
const weights: number[] = intentsUtterancesWeights.weights;
for (let i = 0; i < intents.length; i++) {
const intent: string = intents[i];
const text: string = utterances[i];
const weight: number = weights[i];
const luUtterance: ITextIntentSequenceLabelObjectByPosition = {
entities: [],
partOfSpeechTags: [],
intent,
text,
weight,
};
luUtterances.push(luUtterance);
}
return luUtterances;
}
public getLuObject(): any { // ---- NOTE: can be overriden by a child class.
throw new Error("Logical error as it's not implemented for a " +
"ColumnarData object to generate a LU object.");
}
public getLuLuisJsonStructure(): any { // ---- NOTE: can be overriden by a child class.
throw new Error("Logical error as it's not implemented for a " +
"ColumnarData object to generate a LUIS JSON object.");
}
public getLuQnaJsonStructure(): any { // ---- NOTE: can be overriden by a child class.
throw new Error("Logical error as it's not implemented for a " +
"ColumnarData object to generate a QnA JSON object.");
}
public getLuQnaAlterationsJsonStructure(): any { // ---- NOTE: can be overriden by a child class.
throw new Error("Logical error as it's not implemented for a " +
"ColumnarData to generate a QnA Alterations JSON object.");
}
public getLabelColumnIndex(): number {
return this.labelColumnIndex;
}
public getTextColumnIndex(): number {
return this.textColumnIndex;
}
public getWeightColumnIndex(): number {
return this.weightColumnIndex;
}
public getLinesToSkip(): number {
return this.linesToSkip;
}
} | the_stack |
import ThePlugin from "../main";
import { GenericFuzzySuggester, SuggesterItem } from "./GenericFuzzySuggester";
import { grabCommmunityPluginList, grabCommmunityThemesList } from "../features/githubUtils";
import { themeseCheckAndUpdates, themesInstallFromCommunityList } from "../features/themes";
import AddNewTheme from "./AddNewTheme";
import { ToastMessage } from "../utils/notifications";
export default class PluginCommands {
plugin: ThePlugin;
bratCommands = [
{
id: "BRAT-AddBetaPlugin",
icon: "BratIcon",
name: "Plugins: Add a beta plugin for testing",
showInRibbon: true,
callback: async () => { await this.plugin.betaPlugins.displayAddNewPluginModal(false, false) }
},
{
id: "BRAT-AddBetaPluginWithFrozenVersion",
icon: "BratIcon",
name: "Plugins: Add a beta plugin with frozen version based on a release tag",
showInRibbon: true,
callback: async () => { await this.plugin.betaPlugins.displayAddNewPluginModal(false, true) }
},
{
id: "BRAT-checkForUpdatesAndUpdate",
icon: "BratIcon",
name: "Plugins: Check for updates to all beta plugins and UPDATE",
showInRibbon: true,
callback: async () => { await this.plugin.betaPlugins.checkForUpdatesAndInstallUpdates(true, false) }
},
{
id: "BRAT-checkForUpdatesAndDontUpdate",
icon: "BratIcon",
name: "Plugins: Only check for updates to beta plugins, but don't Update",
showInRibbon: true,
callback: async () => { await this.plugin.betaPlugins.checkForUpdatesAndInstallUpdates(true, true) }
},
{
id: "BRAT-updateOnePlugin",
icon: "BratIcon",
name: "Plugins: Choose a single plugin version to update",
showInRibbon: true,
callback: async () => {
const pluginSubListFrozenVersionNames =
new Set(this.plugin.settings.pluginSubListFrozenVersion.map(f => f.repo));
const pluginList: SuggesterItem[] =
Object
.values(this.plugin.settings.pluginList)
.filter((f) => !pluginSubListFrozenVersionNames.has(f))
.map((m) => { return { display: m, info: m } });
const gfs = new GenericFuzzySuggester(this.plugin);
gfs.setSuggesterData(pluginList);
await gfs.display(async (results) => {
const msg = `Checking for updates for ${results.info}`;
this.plugin.log(msg,true);
ToastMessage(this.plugin, `\n${msg}`, 3);
await this.plugin.betaPlugins.updatePlugin(results.info, false, true);
});
}
},
{
id: "BRAT-restartPlugin",
icon: "BratIcon",
name: "Plugins: Restart a plugin that is already installed",
showInRibbon: true,
callback: async () => {
// @ts-ignore
const pluginList: SuggesterItem[] = Object.values(this.plugin.app.plugins.manifests).map((m) => { return { display: m.id, info: m.id } });
const gfs = new GenericFuzzySuggester(this.plugin);
gfs.setSuggesterData(pluginList);
await gfs.display(async (results) => {
ToastMessage(this.plugin, `${results.info}\nPlugin reloading .....`, 5);
await this.plugin.betaPlugins.reloadPlugin(results.info);
});
}
},
{
id: "BRAT-disablePlugin",
icon: "BratIcon",
name: "Plugins: Disable a plugin - toggle it off",
showInRibbon: true,
callback: async () => {
const pluginList = this.plugin.betaPlugins.getEnabledDisabledPlugins(true).map(manifest => { return { display: `${manifest.name} (${manifest.id})`, info: manifest.id } });
const gfs = new GenericFuzzySuggester(this.plugin);
gfs.setSuggesterData(pluginList);
await gfs.display(async (results) => {
this.plugin.log(`${results.display} plugin disabled`, false);
// @ts-ignore
await this.plugin.app.plugins.disablePlugin(results.info);
});
}
},
{
id: "BRAT-enablePlugin",
icon: "BratIcon",
name: "Plugins: Enable a plugin - toggle it on",
showInRibbon: true,
callback: async () => {
const pluginList = this.plugin.betaPlugins.getEnabledDisabledPlugins(false).map(manifest => { return { display: `${manifest.name} (${manifest.id})`, info: manifest.id } });
const gfs = new GenericFuzzySuggester(this.plugin);
gfs.setSuggesterData(pluginList);
await gfs.display(async (results) => {
this.plugin.log(`${results.display} plugin enabled`, false);
// @ts-ignore
await this.plugin.app.plugins.enablePlugin(results.info);
});
}
},
{
id: "BRAT-openGitHubZRepository",
icon: "BratIcon",
name: "Plugins: Open the GitHub repository for a plugin",
showInRibbon: true,
callback: async () => {
const communityPlugins = await grabCommmunityPluginList();
const communityPluginList: SuggesterItem[] = Object.values(communityPlugins).map((p) => { return { display: `Plugin: ${p.name} (${p.repo})`, info: p.repo } });
const bratList: SuggesterItem[] = Object.values(this.plugin.settings.pluginList).map((p) => { return { display: "BRAT: " + p, info: p } });
communityPluginList.forEach(si => bratList.push(si));
const gfs = new GenericFuzzySuggester(this.plugin);
gfs.setSuggesterData(bratList);
await gfs.display(async (results) => {
if (results.info) window.open(`https://github.com/${results.info}`)
});
}
},
{
id: "BRAT-openGitHubRepoTheme",
icon: "BratIcon",
name: "Themes: Open the GitHub repository for a theme (appearance)",
showInRibbon: true,
callback: async () => {
const communityTheme = await grabCommmunityThemesList();
const communityThemeList: SuggesterItem[] = Object.values(communityTheme).map((p) => { return { display: `Theme: ${p.name} (${p.repo})`, info: p.repo } });
const gfs = new GenericFuzzySuggester(this.plugin);
gfs.setSuggesterData(communityThemeList);
await gfs.display(async (results) => {
if (results.info) window.open(`https://github.com/${results.info}`)
});
}
},
{
id: "BRAT-opentPluginSettings",
icon: "BratIcon",
name: "Plugins: Open Plugin Settings Tab",
showInRibbon: true,
callback: async () => {
// @ts-ignore
const settings = this.plugin.app.setting;
// @ts-ignore
const listOfPluginSettingsTabs: SuggesterItem[] = Object.values(settings.pluginTabs).map((t) => { return { display: "Plugin: " + t.name, info: t.id } });
const gfs = new GenericFuzzySuggester(this.plugin);
// @ts-ignore
const listOfCoreSettingsTabs: SuggesterItem[] = Object.values(settings.settingTabs).map((t) => { return { display: "Core: " + t.name, info: t.id } });
listOfPluginSettingsTabs.forEach(si => listOfCoreSettingsTabs.push(si));
gfs.setSuggesterData(listOfCoreSettingsTabs);
await gfs.display(async (results) => {
settings.open();
settings.openTabById(results.info);
});
}
},
{
id: "BRAT-GrabCommunityTheme",
icon: "BratIcon",
name: "Themes: Grab a community theme",
showInRibbon: true,
callback: async () => await themesInstallFromCommunityList(this.plugin)
},
{
id: "BRAT-GrabBetaTheme",
icon: "BratIcon",
name: "Themes: Grab a beta theme for testing from a Github repository",
showInRibbon: true,
callback: async () => { (new AddNewTheme(this.plugin)).open() }
},
{
id: "BRAT-updateBetaThemes",
icon: "BratIcon",
name: "Themes: Update beta themes",
showInRibbon: true,
callback: async () => await themeseCheckAndUpdates(this.plugin, true)
},
{
id: "BRAT-switchTheme",
icon: "BratIcon",
name: "Themes: Switch Active Theme ",
showInRibbon: true,
callback: async () => {
// @ts-ignore
const communityThemeList: SuggesterItem[] = Object.values(this.plugin.app.customCss.themes).map((t) => { return { display: t, info: t } });
communityThemeList.unshift({ display: "Obsidian Default Theme", info: "" });
const gfs = new GenericFuzzySuggester(this.plugin);
gfs.setSuggesterData(communityThemeList);
await gfs.display(async (results) => {
this.plugin.log(`Switched to theme ${results.display}`, false);
// @ts-ignore
this.plugin.app.customCss.setTheme(results.info);
});
}
},
{
id: "BRAT-allCommands",
icon: "BratIcon",
name: "All Commands list",
showInRibbon: false,
callback: async () => this.ribbonDisplayCommands()
},
]
async ribbonDisplayCommands(): Promise<void> {
const bratCommandList: SuggesterItem[] = [];
this.bratCommands.forEach(cmd => { if (cmd.showInRibbon) bratCommandList.push({ display: cmd.name, info: cmd.callback }) });
const gfs = new GenericFuzzySuggester(this.plugin);
// @ts-ignore
const settings = this.plugin.app.setting;
// @ts-ignore
const listOfCoreSettingsTabs: SuggesterItem[] = Object.values(settings.settingTabs).map((t: any) => {
return {
display: "Core: " + t.name,
info: async () => {
settings.open();
settings.openTabById(t.id);
}
}
});
// @ts-ignore
const listOfPluginSettingsTabs: SuggesterItem[] = Object.values(settings.pluginTabs).map((t: any) => {
return {
display: "Plugin: " + t.name,
info: async () => {
settings.open();
settings.openTabById(t.id);
}
}
});
bratCommandList.push({ display: "---- Core Plugin Settings ----", info: async () => { await this.ribbonDisplayCommands() } })
listOfCoreSettingsTabs.forEach(si => bratCommandList.push(si));
bratCommandList.push({ display: "---- Plugin Settings ----", info: async () => { await this.ribbonDisplayCommands() } })
listOfPluginSettingsTabs.forEach(si => bratCommandList.push(si));
gfs.setSuggesterData(bratCommandList);
await gfs.display(async (results) => await results.info());
}
constructor(plugin: ThePlugin) {
this.plugin = plugin;
this.bratCommands.forEach(async (item) => {
this.plugin.addCommand({
id: item.id,
name: item.name,
icon: item.icon,
callback: async () => { await item.callback() }
})
});
}
} | the_stack |
import * as _ from 'lodash';
import * as setProtocolUtils from 'set-protocol-utils';
import { Address } from 'set-protocol-utils';
import {
CoreContract,
CoreMockContract,
LiquidatorMockContract,
SetTokenContract,
RebalanceAuctionModuleContract,
RebalancingSetTokenContract,
RebalancingSetTokenV2Contract,
RebalancingSetTokenV3Contract,
VaultContract,
WhiteListContract,
} from '../contracts';
import { BigNumber } from 'bignumber.js';
import {
DEFAULT_GAS,
DEFAULT_REBALANCING_NATURAL_UNIT,
DEFAULT_UNIT_SHARES,
EMPTY_BYTESTRING,
ONE_DAY_IN_SECONDS,
SCALE_FACTOR,
UNLIMITED_ALLOWANCE_IN_BASE_UNITS,
ZERO,
} from '../constants';
import { extractNewSetTokenAddressFromLogs } from '../contract_logs/core';
import { ether } from '../units';
import { getWeb3, getContractInstance, importArtifactsFromSource, txnFrom } from '../web3Helper';
import { RebalancingHelper } from './rebalancingHelper';
const web3 = getWeb3();
const RebalancingSetTokenV2 = importArtifactsFromSource('RebalancingSetTokenV2');
declare type CoreLikeContract = CoreMockContract | CoreContract;
declare type RebalancingV2LikeContract = RebalancingSetTokenV2Contract | RebalancingSetTokenV3Contract;
const { SetProtocolTestUtils: SetTestUtils, SetProtocolUtils: SetUtils } = setProtocolUtils;
const setTestUtils = new SetTestUtils(web3);
export class RebalancingSetV2Helper extends RebalancingHelper {
/* ============ Deployment ============ */
/**
* addressConfig [factory, manager, liquidator, initialSet, componentWhiteList,
* liquidatorWhiteList, feeRecipient]
* [0]factory Factory used to create the Rebalancing Set
* [1]manager Address that is able to propose the next Set
* [2]liquidator Address of the liquidator contract
* [3]initialSet Initial set that collateralizes the Rebalancing set
* [4]componentWhiteList Whitelist that nextSet components are checked against during propose
* [5]liquidatorWhiteList Whitelist of valid liquidators
* [6]feeRecipient Address that receives any incentive fees
*
* uintConfig [unitShares, naturalUnit, rebalanceInterval, rebalanceFailPeriod, lastRebalanceTimestamp,
* entryFee, rebalanceFee]
* [0]initialUnitShares Units of currentSet that equals one share
* [1]naturalUnit The minimum multiple of Sets that can be issued or redeemed
* [2]rebalanceInterval: Minimum amount of time between rebalances
* [3]rebalanceFailPeriod: Time after auctionStart where something in the rebalance has gone wrong
* [4]lastRebalanceTimestamp: Time of the last rebalance; Allows customized deployments
* [5]entryFee: Mint fee represented in a scaled percentage value
* [6]rebalanceFee: Rebalance fee represented in a scaled percentage value
*
*/
public async deployRebalancingSetTokenV2Async(
addressConfig: Address[],
bigNumberConfig: BigNumber[],
name: string = 'Rebalancing Set',
symbol: string = 'RBSET',
from: Address = this._tokenOwnerAddress
): Promise<RebalancingSetTokenV2Contract> {
const truffleRebalancingToken = await RebalancingSetTokenV2.new(
addressConfig,
bigNumberConfig,
name,
symbol,
{ from, gas: DEFAULT_GAS },
);
const rebalancingToken = new RebalancingSetTokenV2Contract(
getContractInstance(truffleRebalancingToken),
{ from, gas: DEFAULT_GAS },
);
return rebalancingToken;
}
public async createRebalancingTokenV2Async(
core: CoreLikeContract,
factory: Address,
componentAddresses: Address[],
units: BigNumber[],
naturalUnit: BigNumber,
callData: string = '',
name: string = 'Rebalancing Set Token',
symbol: string = 'RBSET',
from: Address = this._tokenOwnerAddress,
): Promise<RebalancingSetTokenV2Contract> {
const encodedName = SetUtils.stringToBytes(name);
const encodedSymbol = SetUtils.stringToBytes(symbol);
const txHash = await core.createSet.sendTransactionAsync(
factory,
componentAddresses,
units,
naturalUnit,
encodedName,
encodedSymbol,
callData,
{ from },
);
const logs = await setTestUtils.getLogsFromTxHash(txHash);
const setAddress = extractNewSetTokenAddressFromLogs(logs);
return await RebalancingSetTokenV2Contract.at(
setAddress,
web3,
{ from }
);
}
public async createDefaultRebalancingSetTokenV2Async(
core: CoreLikeContract,
factory: Address,
manager: Address,
liquidator: Address,
feeRecipient: Address,
rebalanceFeeCalculator: Address,
initialSet: Address,
failRebalancePeriod: BigNumber,
lastRebalanceTimestamp: BigNumber,
entryFee: BigNumber = ZERO,
rebalanceFee: BigNumber = ZERO,
initialUnitShares: BigNumber = DEFAULT_UNIT_SHARES,
): Promise<RebalancingSetTokenV2Contract> {
// Generate defualt rebalancingSetToken params
const rebalanceInterval = ONE_DAY_IN_SECONDS;
const rebalanceFeeCallData = SetUtils.generateFixedFeeCalculatorCalldata(rebalanceFee);
const callData = SetUtils.generateRebalancingSetTokenV2CallData(
manager,
liquidator,
feeRecipient,
rebalanceFeeCalculator,
rebalanceInterval,
failRebalancePeriod,
lastRebalanceTimestamp,
entryFee,
rebalanceFeeCallData,
);
// Create rebalancingSetToken
return await this.createRebalancingTokenV2Async(
core,
factory,
[initialSet],
[initialUnitShares],
DEFAULT_REBALANCING_NATURAL_UNIT,
callData,
);
}
public async transitionToRebalanceV2Async(
core: CoreLikeContract,
rebalancingComponentWhiteList: WhiteListContract,
rebalancingSetToken: RebalancingV2LikeContract,
nextSetToken: SetTokenContract,
caller: Address,
liquidatorData: string = EMPTY_BYTESTRING,
): Promise<void> {
const currentSupply = await rebalancingSetToken.totalSupply.callAsync();
if (currentSupply.eq(new BigNumber(0))) {
const currentSetMintQuantity = ether(8);
const currentSetToken = await rebalancingSetToken.currentSet.callAsync();
// Issue currentSetToken
await core.issue.sendTransactionAsync(
currentSetToken,
currentSetMintQuantity,
txnFrom(caller)
);
// Use issued currentSetToken to issue rebalancingSetToken
const rebalancingSetQuantityToIssue = ether(7);
await core.issue.sendTransactionAsync(
rebalancingSetToken.address,
rebalancingSetQuantityToIssue,
txnFrom(caller)
);
}
const nextSetTokenComponentAddresses = await nextSetToken.getComponents.callAsync();
await this._coreHelper.addTokensToWhiteList(
nextSetTokenComponentAddresses,
rebalancingComponentWhiteList
);
// Transition to rebalance
await this._blockchain.increaseTimeAsync(ONE_DAY_IN_SECONDS.add(1));
await rebalancingSetToken.startRebalance.sendTransactionAsync(
nextSetToken.address,
liquidatorData,
{ from: caller, gas: DEFAULT_GAS }
);
}
public async transitionToDrawdownV2Async(
core: CoreLikeContract,
rebalancingComponentWhiteList: WhiteListContract,
rebalancingSetToken: RebalancingV2LikeContract,
rebalanceAuctionModule: RebalanceAuctionModuleContract,
liquidatorMock: LiquidatorMockContract,
nextSetToken: SetTokenContract,
manager: Address,
liquidatorData: string = EMPTY_BYTESTRING,
caller: Address = this._tokenOwnerAddress,
): Promise<void> {
await this.transitionToRebalanceV2Async(
core,
rebalancingComponentWhiteList,
rebalancingSetToken,
nextSetToken,
manager,
liquidatorData,
);
const minimumBid = await liquidatorMock.minimumBid.callAsync(rebalancingSetToken.address);
await this.placeBidAsync(
rebalanceAuctionModule,
rebalancingSetToken.address,
minimumBid,
);
// Transition to rebalance
await this._blockchain.increaseTimeAsync(ONE_DAY_IN_SECONDS.add(1));
await rebalancingSetToken.endFailedRebalance.sendTransactionAsync(
{ from: caller, gas: DEFAULT_GAS }
);
}
public async failRebalanceToDrawdownAsync(
rebalancingSetToken: RebalancingV2LikeContract,
liquidatorMock: LiquidatorMockContract,
rebalanceAuctionModule: RebalanceAuctionModuleContract,
caller: Address = this._tokenOwnerAddress,
): Promise<void> {
const minimumBid = await liquidatorMock.minimumBid.callAsync(rebalancingSetToken.address);
await this.placeBidAsync(
rebalanceAuctionModule,
rebalancingSetToken.address,
minimumBid,
);
// Transition to rebalance
await this._blockchain.increaseTimeAsync(ONE_DAY_IN_SECONDS.add(1));
await rebalancingSetToken.endFailedRebalance.sendTransactionAsync(
{ from: caller, gas: DEFAULT_GAS }
);
}
public async placeBidAsync(
rebalanceAuctionModule: RebalanceAuctionModuleContract,
rebalancingSetTokenAddress: Address,
bidQuantity: BigNumber,
allowPartialFill: boolean = false,
caller: Address = this._tokenOwnerAddress,
): Promise<void> {
await rebalanceAuctionModule.bid.sendTransactionAsync(
rebalancingSetTokenAddress,
bidQuantity,
allowPartialFill,
{ from: caller, gas: DEFAULT_GAS }
);
}
public async endFailedRebalanceAsync(
rebalancingSetToken: RebalancingSetTokenContract,
caller: Address = this._tokenOwnerAddress,
): Promise<void> {
await rebalancingSetToken.endFailedAuction.sendTransactionAsync(
{ gas: DEFAULT_GAS },
);
}
public async getFailedWithdrawComponentsAsync(
nextSetToken: SetTokenContract,
currentSetToken: SetTokenContract,
): Promise<Address[]> {
const nextSetComponents: Address[] = await nextSetToken.getComponents.callAsync();
const currentSetComponents: Address[] = await currentSetToken.getComponents.callAsync();
return _.union(currentSetComponents, nextSetComponents);
}
public async getSetIssueQuantity(
setToken: SetTokenContract,
rebalancingSetToken: RebalancingV2LikeContract,
vault: VaultContract,
): Promise<BigNumber> {
// Calculate max Set issue amount
const maxIssueAmount = await this.calculateMaxIssueAmount(
setToken,
rebalancingSetToken,
vault,
);
const setTokenNaturalUnit = await setToken.naturalUnit.callAsync();
return maxIssueAmount.div(setTokenNaturalUnit).round(0, 3).mul(setTokenNaturalUnit);
}
public async calculateMaxIssueAmount(
nextSetToken: SetTokenContract,
rebalancingSetToken: RebalancingV2LikeContract,
vault: VaultContract,
): Promise<BigNumber> {
// Start with a big number
let maxIssueAmount = UNLIMITED_ALLOWANCE_IN_BASE_UNITS;
const naturalUnit = await nextSetToken.naturalUnit.callAsync();
const components = await nextSetToken.getComponents.callAsync();
const units = await nextSetToken.getUnits.callAsync();
for (let i = 0; i < components.length; i++) {
const componentVaultBalance = await vault.getOwnerBalance.callAsync(
components[i],
rebalancingSetToken.address,
);
const impliedIssueAmount = componentVaultBalance.div(units[i]).mul(naturalUnit);
if (impliedIssueAmount.lt(maxIssueAmount)) {
maxIssueAmount = impliedIssueAmount;
}
}
return maxIssueAmount;
}
// Simplified: quantity * fee / 10e18
public async calculateEntryFee(
rebalancingSetToken: RebalancingV2LikeContract,
quantity: BigNumber
): Promise<BigNumber> {
const entryFee = await rebalancingSetToken.entryFee.callAsync();
return entryFee.mul(quantity).div(SCALE_FACTOR).round(0, 3);
}
// Fee is paid via inflation and ownership of the Set.
// Math: newShares / (newShares + oldShares) = percentFee
// Simplified: fee * oldShare / (scaleFactor - fee)
public async calculateRebalanceFeeInflation(
feePercentage: BigNumber,
totalSupply: BigNumber
): Promise<BigNumber> {
return feePercentage.mul(totalSupply).div(SCALE_FACTOR.sub(feePercentage)).round(0, 3);
}
public async getExpectedUnitSharesV2(
core: CoreMockContract,
rebalancingSetToken: RebalancingV2LikeContract,
newSet: SetTokenContract,
vault: VaultContract
): Promise<BigNumber> {
// Gather data needed for calculations
const totalSupply = await rebalancingSetToken.totalSupply.callAsync();
const rebalancingNaturalUnit = await rebalancingSetToken.naturalUnit.callAsync();
const newSetNaturalUnit = await newSet.naturalUnit.callAsync();
const components = await newSet.getComponents.callAsync();
const units = await newSet.getUnits.callAsync();
const rebalanceFee = await rebalancingSetToken.rebalanceFee.callAsync();
// Figure out how many new Sets can be issued from balance in Vault, if less than previously calculated
// amount, then set that to maxIssueAmount
let maxIssueAmount: BigNumber = UNLIMITED_ALLOWANCE_IN_BASE_UNITS;
for (let i = 0; i < components.length; i++) {
const componentAmount = await vault.getOwnerBalance.callAsync(components[i], rebalancingSetToken.address);
const componentIssueAmount = componentAmount.div(units[i]).round(0, 3).mul(newSetNaturalUnit);
if (componentIssueAmount.lessThan(maxIssueAmount)) {
maxIssueAmount = componentIssueAmount;
}
}
// Calculate unitShares by finding how many natural units worth of the rebalancingSetToken have been issued
// Divide maxIssueAmount by this to find unitShares, remultiply unitShares by issued amount of rebalancing-
// SetToken in natural units to get amount of new Sets to issue
const issueAmount = maxIssueAmount.div(newSetNaturalUnit).round(0, 3).mul(newSetNaturalUnit);
const rebalancingInflation = await this.calculateRebalanceFeeInflation(
rebalanceFee,
totalSupply
);
const postFeeTotalySupply = totalSupply.plus(rebalancingInflation);
const naturalUnitsOutstanding = postFeeTotalySupply.div(rebalancingNaturalUnit);
const unitShares = issueAmount.div(naturalUnitsOutstanding).round(0, 3);
return unitShares;
}
} | the_stack |
declare module ManipulationHelpers {
import Color3 = BABYLON.Color3;
import Scene = BABYLON.Scene;
import Vector3 = BABYLON.Vector3;
import Quaternion = BABYLON.Quaternion;
import Vector2 = BABYLON.Vector2;
const enum RadixFeatures {
None = 0,
/**
* Display the Arrow that follows the X Axis
*/
ArrowX = 1,
/**
* Display the Arrow that follows the Y Axis
*/
ArrowY = 2,
/**
* Display the Arrow that follows the Z Axis
*/
ArrowZ = 4,
/**
* Display the Arrow that follows the XYZ Axis
*/
ArrowsXYZ = 7,
/**
* Display the anchor that allow XY plane manipulation
*/
PlaneSelectionXY = 16,
/**
* Display the anchor that allow XZ plane manipulation
*/
PlaneSelectionXZ = 32,
/**
* Display the anchor that allow YZ plane manipulation
*/
PlaneSelectionYZ = 64,
/**
* Display all the anchors that allow plane manipulation
*/
AllPlanesSelection = 112,
/**
* Display the rotation cylinder that allows rotation manipulation along the X Axis
*/
RotationX = 256,
/**
* Display the rotation cylinder that allows rotation manipulation along the Y Axis
*/
RotationY = 512,
/**
* Display the rotation cylinder that allows rotation manipulation along the A Axis
*/
RotationZ = 1024,
/**
* Display all rotation cylinders
*/
Rotations = 1792,
}
/**
* This class create the visual geometry to display a manipulation radix in a viewport.
* It also implements the logic to handler intersection, hover on feature.
*/
class Radix {
private static pc;
private static sc;
/**
* Set/get the Wire Selection Threshold, set a bigger value to improve tolerance while picking a wire mesh
*/
wireSelectionThreshold: number;
/**
* Get/set the colors of the X Arrow
*/
xArrowColor: Color3;
/**
* Get/set the colors of the Y Arrow
*/
yArrowColor: Color3;
/**
* Get/set the colors of the Z Arrow
*/
zArrowColor: Color3;
/**
* Get/set the colors of the XY Plane selection anchor
*/
xyPlaneSelectionColor: Color3;
/**
* Get/set the colors of the XZ Plane selection anchor
*/
xzPlaneSelectionColor: Color3;
/**
* Get/set the colors of the YZ Plane selection anchor
*/
yzPlaneSelectionColor: Color3;
/**
* Get/set the feature of the Radix that are/must be highlighted
* @returns {}
*/
highlighted: RadixFeatures;
/**
* Get the Radix Features that were selected upon creation
*/
features: RadixFeatures;
/**
* Create a new Radix instance. The length/radius members are optionals and the default value should suit most cases
* @param scene the owner Scene
* @param features the feature the radix must display
* @param arrowLength the length of a row of an axis, include the rotation cylinder (if any), but always exclude the arrow cone
* @param coneLength the length of the arrow cone. this is also the length taken for the rotation cylinder (if any)
* @param coneRadius the radius of the arrow cone
* @param planeSelectionLength the length of the selection plane
*/
constructor(scene: Scene, features?: RadixFeatures, arrowLength?: number, coneLength?: number, coneRadius?: number, planeSelectionLength?: number);
/**
* make an intersection test between a point position in the viwport and the Radix, return the feature that is intersected, if any.
* only the closer Radix Feature is picked.
* @param pos the viewport position to create the picking ray from.
*/
intersect(pos: Vector2): RadixFeatures;
/**
* Set the world coordinate of where the Axis should be displayed
* @param position the position
* @param rotation the rotation quaternion
* @param scale the scale (should be uniform)
*/
setWorld(position: Vector3, rotation: Quaternion, scale: Vector3): void;
/**
* Display the Radix on screen
*/
show(): void;
/**
* Hide the Radix from the screen
*/
hide(): void;
private setVisibleState(mesh, state);
private intersectMeshes(pos, startName, currentClosest);
private constructGraphicalObjects();
private constructArrow(feature, name, transform);
private constructPlaneSelection(feature, name, transform);
private constructRotation(feature, name, transform);
private addSymbolicMeshToLit(mesh);
private hasFeature(value);
private hasHighlightedFeature(value);
private updateMaterial(name, color);
private updateMaterialFromHighlighted(feature, highlighted, name);
private getMaterial(name);
private _arrowLength;
private _coneLength;
private _coneRadius;
private _planeSelectionLength;
private _light1;
private _light2;
private _rootMesh;
private _features;
private _scene;
private _materials;
private _wireSelectionThreshold;
private _xArrowColor;
private _yArrowColor;
private _zArrowColor;
private _xyPlaneSelectionColor;
private _xzPlaneSelectionColor;
private _yzPlaneSelectionColor;
private _highlighted;
}
}
import Vector4 = BABYLON.Vector2;
declare module ManipulationHelpers {
import Scene = BABYLON.Scene;
import Node = BABYLON.Node;
/**
* This class is used to manipulated a single node.
* Right now only node of type AbstractMesh is support.
* In the future, manipulation on multiple selection could be possible.
*
* A manipulation start when left clicking and moving the mouse. It can be cancelled if the right mouse button is clicked before releasing the left one (this feature is only possible if noPreventContextMenu is false).
* Per default translation is peformed when manipulating the arrow (axis or cone) or the plane anchor. If you press the shift key it will switch to rotation manipulation. The Shift key can be toggle while manipulating, the current manipulation is accept and a new one starts.
*
* You can set the rotation/translationStep (in radian) to enable snapping.
*
* The current implementation of this class creates a radix with all the features selected.
*/
class ManipulatorInteractionHelper {
/**
* Rotation Step in Radian to perform rotation with the given step instead of a smooth one.
* Set back to null/undefined to disable
*/
rotationStep: number;
/**
* Translation Step in World unit to perform translation at the given step instread of a smooth one.
* Set back to null/undefined to disable
*/
translationStep: number;
/**
* Set to true if you want the context menu to be displayed while manipulating. The manipulation cancel feature (which is triggered by a right click) won't work in this case. Default value is false (context menu is not showed when right clicking during manipulation) and this should fit most of the cases.
*/
noPreventContextMenu: boolean;
/**
* Attach a node to manipulate. Right now, only manipulation on a single node is supported, but this api will allow manipulation on a multiple selection in the future.
* @param node
*/
attachManipulatedNode(node: Node): void;
/**
* Detach the node to manipulate. Right now, only manipulation on a single node is supported, but this api will allow manipulation on a multiple selection in the future.
*/
detachManipulatedNode(node: Node): void;
constructor(scene: Scene);
private onBeforeRender(scene, state);
private onPointer(e, state);
private beginDrag(rayPos, event);
private endDragMode();
private doRot(rayPos);
private doPos(rayPos);
private hasManipulatedMode(value);
private hasManFlags(value);
private clearManFlags(values);
private setManFlags(values);
private static ComputeRayHit(ray, distance);
private setManipulatedNodeWorldMatrix(mtx);
private getManipulatedNodeWorldMatrix();
private setupIntersectionPlane(mode, plane2);
private setupIntersectionPlanes(mode);
private getRayPosition(event);
private renderManipulator();
private fromScreenToWorld(l, z);
private static evalPosition(ray, u);
private _flags;
private _firstMousePos;
private _prevMousePos;
private _shiftKeyState;
private _pos;
private _right;
private _up;
private _view;
private _oldPos;
private _prevHit;
private _firstTransform;
private _scene;
private _manipulatedMode;
private _rotationFactor;
private _manipulatedNode;
private _radix;
}
}
declare module ManipulationHelpers {
import Scene = BABYLON.Scene;
const enum SIHCurrentAction {
None = 0,
Selector = 1,
Camerator = 2,
}
/**
* The purpose of this class is to allow the camera manipulation, single node selection and manipulation.
* You can use it as an example to create your more complexe/different interaction helper
*/
class SimpleInteractionHelper {
constructor(scene: Scene);
currentAction: SIHCurrentAction;
manipulator: ManipulatorInteractionHelper;
private pointerCallback(p, s);
private doSelectorInteraction(p, s);
private detectActionChanged(p, s);
private static CameratorSwitchThreshold;
private _pickedNode;
private _actionStack;
private _scene;
private _pointerObserver;
private _manipulator;
}
}
declare module ManipulationHelpers {
class SymbolicVisualHelper {
render(): void;
renderLight: boolean;
renderManipulator: boolean;
}
} | the_stack |
import {
implementsIAcmImportCertProps,
implementsINewSecretProps,
implementsISecretCertificate,
implementsIX509CertificateEncodePkcs12,
implementsIX509CertificateGenerate,
implementsIX509ResourceProperties,
implementsTag,
} from '../types';
test.each([
// Valid
[
[{ Key: 'key', Value: 'val' }],
true,
],
// Valid Multiple
[
[
{ Key: 'key1', Value: 'val1' },
{ Key: 'key2', Value: 'val2' },
],
true,
],
// Valid Empty
[
[],
true,
],
// Not array
[
'notArray',
false,
],
// Array doesn't contain objects
[
['notTag'],
false,
],
// Tag array object missing Key
[
[{ Value: 'val' }],
false,
],
// Tag array object missing value
[
[{ Key: 'key' }],
false,
],
])('implementsTag: %p returns %p', (value: any, doesImplement: boolean) => {
expect(implementsTag(value)).toEqual(doesImplement);
});
test.each([
// Valid no CertChain
[
{
Cert: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Cert',
Key: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Key',
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
},
true,
],
// Valid with CertChain
[
{
Cert: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Cert',
Key: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Key',
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
CertChain: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/CertChain',
},
true,
],
// Valid, extra field
[
{
Cert: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Cert',
Key: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Key',
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
Extra: 'test',
},
true,
],
// Value undefined
[undefined, false],
// Value not object
['test', false],
// No Cert
[
{
Key: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Key',
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
},
false,
],
// Cert not arn
[
{
Cert: 'test',
Key: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Key',
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
},
false,
],
// Cert not string
[
{
Cert: false,
Key: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Key',
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
},
false,
],
// No Key
[
{
Cert: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Cert',
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
},
false,
],
// Key not arn
[
{
Cert: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Cert',
Key: 'test',
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
},
false,
],
// Key not string
[
{
Cert: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Cert',
Key: false,
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
},
false,
],
// No Passphrase
[
{
Cert: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Cert',
Key: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Key',
},
false,
],
// Passphrase not arn
[
{
Cert: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Cert',
Key: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Key',
Passphrase: 'test',
},
false,
],
// Passphrase not string
[
{
Cert: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Cert',
Key: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Key',
Passphrase: false,
},
false,
],
// CertChain not arn
[
{
Cert: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Cert',
Key: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Key',
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
CertChain: 'test',
},
false,
],
// CertChain not string
[
{
Cert: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Cert',
Key: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Key',
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
CertChain: true,
},
false,
],
])('implementsISecretCertificate: %p returns %p', (value: any, doesImplement: boolean) => {
expect(implementsISecretCertificate(value)).toEqual(doesImplement);
});
test.each([
// Valid
[
{
Description: 'Test Desc',
NamePrefix: 'prefix',
Tags: [{ Key: 'key', Value: 'val' }],
},
true,
],
// Valid with encryption key
[
{
Description: 'Test Desc',
NamePrefix: 'prefix',
Tags: [{ Key: 'key', Value: 'val' }],
EncryptionKey: 'arn:aws:kms:abc123:1234:key/12ab',
},
true,
],
// Value not defined
[undefined, false],
// Value not an object
['test', false],
// No description
[
{
NamePrefix: 'prefix',
Tags: [{ Key: 'key', Value: 'val' }],
},
false,
],
// Description not string
[
{
Description: false,
NamePrefix: 'prefix',
Tags: [{ Key: 'key', Value: 'val' }],
},
false,
],
// No NamePrefix
[
{
Description: 'Test Desc',
Tags: [{ Key: 'key', Value: 'val' }],
},
false,
],
// NamePrefix not string
[
{
Description: 'Test Desc',
NamePrefix: false,
Tags: [{ Key: 'key', Value: 'val' }],
},
false,
],
// No Tags
[
{
Description: 'Test Desc',
NamePrefix: 'prefix',
},
false,
],
// Tags not array
[
{
Description: 'Test Desc',
NamePrefix: 'prefix',
Tags: 'notArray',
},
false,
],
// EncrpytionKey not ARN
[
{
Description: 'Test Desc',
NamePrefix: 'prefix',
Tags: [{ Key: 'key', Value: 'val' }],
EncryptionKey: 'test',
},
false,
],
// EncryptionKey not string
[
{
Description: 'Test Desc',
NamePrefix: 'prefix',
Tags: [{ Key: 'key', Value: 'val' }],
EncryptionKey: {},
},
false,
],
])('implementsINewSecretProps: %p returns %p', (value: any, doesImplement: boolean) => {
expect(implementsINewSecretProps(value)).toEqual(doesImplement);
});
test.each([
// Valid
[
{
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
Secret: {
Description: 'Test Desc',
NamePrefix: 'prefix',
Tags: [{ Key: 'key', Value: 'val' }],
},
},
true,
],
// Value not defined
[undefined, false],
// Value not object
['test', false],
// No Passphrase
[
{
Secret: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Secret',
},
false,
],
// Non ARN Passphrase
[
{
Passphrase: 'badArn',
Secret: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Secret',
},
false,
],
// Non string Passphrase
[
{
Passphrase: {},
Secret: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Secret',
},
false,
],
// No Secret
[
{
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
},
false,
],
// Non ARN Secret
[
{
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
Secret: 'badArn',
},
false,
],
// Non string Secret
[
{
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
Secret: {},
},
false,
],
// Extra field
[
{
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
Secret: {
Description: 'Test Desc',
NamePrefix: 'prefix',
Tags: [{ Key: 'key', Value: 'val' }],
},
Extra: 'test',
},
true,
],
])('implementsIX509ResourceProperties: %p returns %p', (value: any, doesImplement: boolean) => {
expect(implementsIX509ResourceProperties(value)).toEqual(doesImplement);
});
test.each([
// Valid
[
{
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
Secret: {
Description: 'Test Desc',
NamePrefix: 'prefix',
Tags: [{ Key: 'key', Value: 'val' }],
},
DistinguishedName: { CN: 'test' },
SigningCertificate: {
Cert: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Cert',
Key: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Key',
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
},
},
true,
],
// Valid, no SigningCertificate
[
{
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
Secret: {
Description: 'Test Desc',
NamePrefix: 'prefix',
Tags: [{ Key: 'key', Value: 'val' }],
},
DistinguishedName: { CN: 'test' },
},
true,
],
// Value not defined
[undefined, false],
// Value not object
['test', false],
// Bad IX509ResourceProperties
[
{
Passphrase: '',
Secret: {},
DistinguishedName: { CN: 'test' },
SigningCertificate: {
Cert: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Cert',
Key: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Key',
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
},
},
false,
],
// Bad DistinguishedName
[
{
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
Secret: {
Description: 'Test Desc',
NamePrefix: 'prefix',
Tags: [{ Key: 'key', Value: 'val' }],
},
DistinguishedName: {},
SigningCertificate: {
Cert: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Cert',
Key: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Key',
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
},
},
false,
],
// Bad SigningCertificate
[
{
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
Secret: {
Description: 'Test Desc',
NamePrefix: 'prefix',
Tags: [{ Key: 'key', Value: 'val' }],
},
DistinguishedName: { CN: 'test' },
SigningCertificate: {
Cert: '',
Key: '',
Passphrase: '',
},
},
false,
],
])('implementsIX509CertificateGenerate: %p returns %p', (value: any, doesImplement: boolean) => {
expect(implementsIX509CertificateGenerate(value)).toEqual(doesImplement);
});
test.each([
// Valid
[
{
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
Secret: {
Description: 'Test Desc',
NamePrefix: 'prefix',
Tags: [{ Key: 'key', Value: 'val' }],
},
Certificate: {
Cert: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Cert',
Key: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Key',
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
},
},
true,
],
// Value not defined
[undefined, false],
// Value not object
['test', false],
// Bad IX509ResourceProperties
[
{
Passphrase: '',
Secret: {},
Certificate: {
Cert: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Cert',
Key: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Key',
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
},
},
false,
],
// Bad Certificate
[
{
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
Secret: {
Description: 'Test Desc',
NamePrefix: 'prefix',
Tags: [{ Key: 'key', Value: 'val' }],
},
Certificate: {
Cert: '',
Key: '',
Passphrase: '',
},
},
false,
],
])('implementsIX509CertificateEncodePkcs12: %p returns %p', (value: any, doesImplement: boolean) => {
expect(implementsIX509CertificateEncodePkcs12(value)).toEqual(doesImplement);
});
test.each([
// Valid
[
{
Tags: [{ Key: 'key', Value: 'val' }],
X509CertificatePem: {
Cert: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Cert',
Key: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Key',
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
},
},
true,
],
// Value not defined
[undefined, false],
// Value not object
['test', false],
// Bad X509CertificatePem
[
{
Tags: [{ Key: 'key', Value: 'val' }],
X509CertificatePem: {
Key: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Key',
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
},
},
false,
],
// Bad Tags
[
{
Tags: [{ Key: 'key' }],
X509CertificatePem: {
Cert: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Cert',
Key: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Key',
Passphrase: 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Passphrase',
},
},
false,
],
])('implementsIAcmImportCertProps: %p returns %p', (value: any, doesImplement: boolean) => {
expect(implementsIAcmImportCertProps(value)).toEqual(doesImplement);
}); | the_stack |
import {
AdjacentBoundaryBehaviour,
Annotation,
AnnotationCollection,
AnnotationConstructor,
AnnotationJSON,
compareAnnotations,
Deletion,
EdgeBehaviour,
Insertion,
ParseAnnotation,
UnknownAnnotation,
} from "./internals";
/**
* Get the function that converts between two documents. Use this to grab a converter
* for testing, or for nesting conversions.
*
* the converter returned from this will in general mutate its argument;
* you should probably use convertTo unless you're in the middle of defining a converter
*/
export function getConverterFor(
from: typeof Document | string,
to: typeof Document | string
): never | ((doc: Document) => Document) {
let exports = (typeof window !== "undefined" ? window : global) as any;
let fromType = typeof from === "string" ? from : from.contentType;
let toType = typeof to === "string" ? to : to.contentType;
let converters = exports.__atjson_converters__;
let converter = converters
? converters[fromType]
? converters[fromType][toType]
: null
: null;
if (converter == null) {
let fromName = typeof from === "string" ? from : from.name;
let toName = typeof to === "string" ? to : to.name;
throw new Error(
`🚨 There is no converter registered between ${fromName} and ${toName}.\n\nDid you forget to \`import\` or \`require\` your converter?\n\nIf you haven't written a converter yet, register a converter for this:\n\n${fromName}.defineConverterTo(${toName}, doc => {\n // ❤️ Write your converter here!\n return doc;\n});`
);
}
return converter;
}
/**
* This function merges and sorts the provided ranges
*
* @param ranges list of { start, end } structs to sort and merge
* @returns a list of non-overlapping { start, end } structs, sorted by start position
*/
export function mergeRanges(_ranges: Array<{ start: number; end: number }>) {
if (_ranges.length === 0) return [];
/**
* shallowly clone the argument so we don't change the ordering
*/
let ranges = [..._ranges];
/**
* sort the ranges in ascending order by start position
* this allows us to efficiently merge them, which will allow us to efficiently delete text
*/
let sortedRanges = ranges.sort(function compareRangeStarts(
{ start: startL },
{ start: startR }
) {
return startL - startR;
});
/**
* merge overlapping ranges so we don't need to worry about them when we're deleting text and adjusting annotations
*
* do this by passing over the sorted ranges (taking the first as a starting accumulator)
* for each new range we see, if it overlaps *and* overhangs the current accumulator we extend the accumulator
* if it doesn't overlap the current accumulator, we know it must come *after* the accumulator since the ranges are sorted
* so we add the accumulator to the merged ranges and make the next range the new accumulator
*/
let [{ start, end }, ...unmergedRanges] = sortedRanges;
// copy the start and end positions into a new object we can modify freely
let currentMergingRange = { start, end };
let mergedRanges = [];
for (let { start, end } of unmergedRanges) {
// copy the start and end positions into a new object we can modify freely
let range = { start, end };
// if the new range overlaps and overhangs the current range, extend the current range
if (range.start <= currentMergingRange.end) {
if (range.end > currentMergingRange.end) {
currentMergingRange.end = range.end;
}
} else {
mergedRanges.push(currentMergingRange);
currentMergingRange = range;
}
}
mergedRanges.push(currentMergingRange);
return mergedRanges;
}
export class Document {
static contentType: string;
static schema: Array<AnnotationConstructor<any, any>> = [];
static defineConverterTo(
to: typeof Document,
converter: (doc: Document) => Document
) {
// We may have multiple / conflicting versions of
// @atjson/document. To allow this, we need to
// register converters on the global to ensure
// that they can be shared across versions of the library.
let exports = (typeof window !== "undefined" ? window : global) as any;
let converters = exports.__atjson_converters__;
if (converters == null) {
converters = exports.__atjson_converters__ = {};
}
if (converters[this.contentType] == null) {
converters[this.contentType] = {};
}
if (!(to.prototype instanceof Document)) {
throw new Error(
`📦 We've detected that you have multiple versions of \`@atjson/document\` installed— ${to.name} doesn't extend the same Document class as ${this.name}.\nThis may be because @atjson/document is being installed as a sub-dependency of an npm package and as a top-level package, and their versions don't match. It could also be that your build includes two versions of @atjson/document.`
);
}
converters[this.contentType][to.contentType] = converter;
}
content: string;
readonly contentType: string;
annotations: Array<Annotation<any>>;
changeListeners: Array<() => void>;
private pendingChangeEvent: any;
constructor(options: {
content: string;
annotations: Array<AnnotationJSON | Annotation<any>>;
}) {
let DocumentClass = this.constructor as typeof Document;
this.contentType = DocumentClass.contentType;
this.changeListeners = [];
this.content = options.content;
let createAnnotation = (annotation: AnnotationJSON | Annotation<any>) =>
this.createAnnotation(annotation);
this.annotations = options.annotations.map(createAnnotation);
}
/**
* I'm on a plane; I'm not sure the best approach to cross-platform event
* listeners and don't have internet access at the moment, so I'm just going
* to quickly roll my own here. To be updated.
*/
addEventListener(eventName: string, func: () => void): void {
if (eventName !== "change")
throw new Error("Unsupported event. `change` is the only constant.");
this.changeListeners.push(func);
}
/*
removeEventListener(eventName: string, func: Function): void {
throw new Error('Unimplemented.');
}
*/
/**
* Annotations must be explicitly allowed unless they
* are added to the annotations array directly- this is
* acceptable, but side-affects created by queries will
* not be called.
*/
addAnnotations(
...annotations: Array<Annotation<any> | AnnotationJSON>
): void {
let createAnnotation = (annotation: AnnotationJSON | Annotation<any>) =>
this.createAnnotation(annotation);
this.annotations.push(...annotations.map(createAnnotation));
this.triggerChange();
}
/**
*
* A simple example of this is transforming a document parsed from
* an HTML document into a common format:
*
* html.where({ type: 'h1' }).set({ type: 'heading', attributes: { level: 1 }});
*
* When the attribute for `h1` is added to the document, it will
* be swapped out for a `heading` with a level of 1.
*
* Other options available are renaming variables:
*
* html.where({ type: 'img' }).set({ 'attributes.src': 'attributes.url' });
*
* tk: join documentation
*/
where(
filter: { [key: string]: any } | ((annotation: Annotation<any>) => boolean)
) {
return this.all().where(filter);
}
all() {
return new AnnotationCollection(this, this.annotations);
}
removeAnnotation(annotation: Annotation<any>): Annotation<any> | void {
let index = this.annotations.indexOf(annotation);
if (index > -1) {
this.triggerChange();
return this.annotations.splice(index, 1)[0];
}
}
removeAnnotations(_annotations: Array<Annotation<any>>) {
if (_annotations.length < 10) {
for (let annotation of _annotations) {
this.removeAnnotation(annotation);
}
return;
}
/**
* shallowly clone the argument so we don't change the order or remove elements
*/
let annotations = [..._annotations];
let sortedAnnotationsToRemove = annotations.sort(compareAnnotations);
let docAnnotations = this.annotations.sort(compareAnnotations);
let keptAnnotations = [];
for (let annotation of docAnnotations) {
if (annotation === sortedAnnotationsToRemove[0]) {
sortedAnnotationsToRemove.shift();
} else {
keptAnnotations.push(annotation);
}
}
this.annotations = keptAnnotations;
this.triggerChange();
}
replaceAnnotation(
annotation: Annotation<any>,
...newAnnotations: Array<AnnotationJSON | Annotation<any>>
): Array<Annotation<any>> {
let index = this.annotations.indexOf(annotation);
let createAnnotation = (annotation: AnnotationJSON | Annotation<any>) =>
this.createAnnotation(annotation);
if (index > -1) {
let annotations = newAnnotations.map(createAnnotation);
this.annotations.splice(index, 1, ...annotations);
return annotations;
}
this.triggerChange();
return [];
}
insertText(
start: number,
text: string,
behaviour: AdjacentBoundaryBehaviour = AdjacentBoundaryBehaviour.default
) {
if (start < 0 || start > this.content.length)
throw new Error("Invalid position.");
let behaviourLeading;
let behaviourTrailing;
// "preserve" and "modify" are targeted for deprecation as valid options in
// favor of preserveLeading, preserveTrailing, or preserveBoth
switch (behaviour) {
case AdjacentBoundaryBehaviour.preserveBoth:
behaviourLeading = EdgeBehaviour.preserve;
behaviourTrailing = EdgeBehaviour.preserve;
break;
case AdjacentBoundaryBehaviour.preserve:
case AdjacentBoundaryBehaviour.preserveTrailing:
behaviourLeading = EdgeBehaviour.modify;
behaviourTrailing = EdgeBehaviour.preserve;
break;
default:
case AdjacentBoundaryBehaviour.modify:
case AdjacentBoundaryBehaviour.preserveLeading:
behaviourLeading = EdgeBehaviour.preserve;
behaviourTrailing = EdgeBehaviour.modify;
break;
}
let insertion = new Insertion(
start,
text,
behaviourLeading,
behaviourTrailing
);
try {
for (let i = this.annotations.length - 1; i >= 0; i--) {
let annotation = this.annotations[i];
annotation.handleChange(insertion);
}
this.content =
this.content.slice(0, start) + text + this.content.slice(start);
} catch (e) {
// eslint-disable-next-line no-console
console.error("Failed to insert text", e);
}
/*
if (text.indexOf('\n') > -1) {
let prevEnd: number;
for (let j = this.annotations.length - 1; j >= 0; j--) {
a = this.annotations[j];
// This doesn't affect us.
if (a.type !== 'block') continue;
if (a.end < position) continue;
if (position < a.start) continue;
// First adjust the end of the current paragraph.
prevEnd = a.end;
a.end = position + 1;
// And now add a new paragraph.
this.addAnnotations({
type: 'paragraph',
display: 'block',
start: position + 1,
end: prevEnd
});
}
}
*/
this.triggerChange();
}
deleteText(start: number, end: number) {
// This should really not just truncate annotations, but rather tombstone
// the modified annotations as an atjson sub-document inside the annotation
// that's being used to delete stuff.
let deletion = new Deletion(start, end);
try {
for (let i = this.annotations.length - 1; i >= 0; i--) {
let annotation = this.annotations[i];
annotation.handleChange(deletion);
}
this.content = this.content.slice(0, start) + this.content.slice(end);
} catch (e) {
// eslint-disable-next-line no-console
console.error("Failed to delete text", e);
}
/* to be moved to block annotation
let potentialMergeAnnotations = { type: annotations[] }
for (const type in potentialMergeAnnotations) {
let annotations = potentialMergeAnnotations[type];
annotations = annotations.sort((j, k) => j.start - k.start);
for (let l = annotations.length - 1; l > 0; l--) {
if (annotations[l - 1].end === annotations[l].start) { // && annotations[i-1].attributes.toJSON() === annotations[i].attributes.toJSON()) {
annotations[l - 1].end = annotations[l].end;
this.removeAnnotation(annotations[l]);
}
}
*/
this.triggerChange();
}
/**
* Slices return part of a document from the parent document.
* By default, the slice contains a truncated copy of any annotation
* overlapping the range. This can be overriden by specifying a filter
*/
slice(
start: number,
end: number,
filter?: (annotation: Annotation<any>) => boolean
): Document {
let DocumentClass = this.constructor as typeof Document;
let slicedAnnotations = filter
? this.where(filter)
: this.where(function sliceContainsAnnotation(a) {
if (start < a.start) {
return end > a.start;
} else {
return a.end > start;
}
});
let doc = new DocumentClass({
content: this.content,
annotations: slicedAnnotations.map(function cloneAnnotation(annotation) {
return annotation.clone();
}),
});
doc.deleteText(end, doc.content.length);
doc.deleteText(0, start);
return doc;
}
/**
* Cuts out part of the document, modifying `this` and returning the removed portion.
* By default, the cut contains a truncated copy of any annotation
* overlapping the range. This can be overriden by specifying a filter.
* Annotations included wholly in the cut that are matched by the filter
* will be removed from the original document
*/
cut(
start: number,
end: number,
filter?: (annotation: Annotation<any>) => boolean
): Document {
let slice = this.slice(start, end, filter);
this.where(function annotationWasCut(annotation) {
return (
annotation.start >= start &&
annotation.end <= end &&
(!filter || filter(annotation))
);
}).remove();
this.deleteText(start, end);
return slice;
}
convertTo<To extends typeof Document>(to: To): InstanceType<To> | never {
let DocumentClass = this.constructor as typeof Document;
let converter = getConverterFor(DocumentClass, to);
class ConversionDocument extends DocumentClass {
static schema = DocumentClass.schema.concat(to.schema);
/**
* overrides Document.slice to return the result in the original source
*/
slice(
start: number,
end: number,
filter?: (annotation: Annotation<any>) => boolean
): Document {
let sliceDoc = super.slice(start, end, filter);
return new DocumentClass({
content: sliceDoc.content,
annotations: sliceDoc.annotations,
});
}
convertTo<Other extends typeof Document>(other: Other): never {
throw new Error(
`🚨 Don't nest converters! Instead, import \`getConverterFor\` and get the converter that way!\n\nimport { getConverterFor } from '@atjson/document';\n\n${
DocumentClass.name
}.defineConverterTo(${
to.name
}, doc => {\n let convert${other.name.replace(
"Source",
""
)} = getConverterFor(${other.name}, ${
to.name
});\n return convert${other.name.replace("Source", "")}(doc);\n});`
);
}
}
let convertedDoc = new ConversionDocument({
content: this.content,
annotations: this.where({})
.sort()
.map(function cloneAnnotation(a) {
return a.clone();
}),
});
let result = converter(convertedDoc);
return new to({
content: result.content,
annotations: result.where({}).sort().annotations,
}) as InstanceType<To>;
}
toJSON() {
let DocumentClass = this.constructor as typeof Document;
let schema = DocumentClass.schema;
return {
content: this.content,
contentType: this.contentType,
annotations: this.where({}).sort().toJSON(),
schema: schema.map(function prefixAnnotationType(AnnotationClass) {
return `-${AnnotationClass.vendorPrefix}-${AnnotationClass.type}`;
}),
};
}
clone(): Document {
let DocumentClass = this.constructor as typeof Document;
return new DocumentClass({
content: this.content,
annotations: this.annotations.map(function cloneAnnotation(annotation) {
return annotation.clone();
}),
});
}
match(
regex: RegExp,
start?: number,
end?: number
): Array<{ start: number; end: number; matches: string[] }> {
let content = this.content.slice(start, end);
let offset = start || 0;
let matches = [];
let match;
do {
match = regex.exec(content);
if (match) {
matches.push({
start: offset + match.index,
end: offset + match.index + match[0].length,
matches: match.slice(),
});
}
} while (regex.global && match);
return matches;
}
deleteTextRanges(ranges: Array<{ start: number; end: number }>) {
if (ranges.length === 0) {
return;
}
/**
* sorts and merges ranges so that they are non-overlapping and in ascending order by start value
*/
let mergedRanges = mergeRanges(ranges);
if (mergedRanges.length === 1) {
let [{ start, end }] = mergedRanges;
return this.deleteText(start, end);
}
/**
* because the ranges are now *sorted* and *non-overlapping* we can straightforwardly extract the text *between* the ranges,
* join the extracted text, and make that our new content.
*/
let newContent = this.content.slice(0, mergedRanges[0].start);
let lastEnd;
for (let i = 0; i < mergedRanges.length - 1; i++) {
newContent += this.content.slice(
mergedRanges[i].end,
mergedRanges[i + 1].start
);
lastEnd = mergedRanges[i + 1].end;
}
this.content = newContent + this.content.slice(lastEnd);
/**
* for adjusting annotations, we need to handle the ranges backwards.
* Conveniently they are already sorted and non-overlapping, so we can simply walk the list backwards
*/
for (let i = mergedRanges.length - 1; i >= 0; i--) {
let change = mergedRanges[i];
for (let annotation of this.annotations) {
let length = change.end - change.start;
// We're deleting after the annotation, nothing needed to be done.
// [ ]
// -----------*---*---
if (annotation.end < change.start) {
continue;
}
// If the annotation is wholly *after* the deleted text, just move
// everything.
// [ ]
// --*---*-------------
if (change.end < annotation.start) {
annotation.start -= length;
annotation.end -= length;
} else {
if (change.end < annotation.end) {
// Annotation spans the whole deleted text, so just truncate the end of
// the annotation (shrink from the right).
// [ ]
// ------*------*---------
if (change.start > annotation.start) {
annotation.end -= length;
// Annotation occurs within the deleted text, affecting both start and
// end of the annotation, but by only part of the deleted text length.
// [ ]
// ---*---------*------------
} else if (change.start <= annotation.start) {
annotation.start -= annotation.start - change.start;
annotation.end -= length;
}
} else if (change.end >= annotation.end) {
// [ ]
// [ ]
// [ ]
// [ ]
// ------*---------*--------
if (change.start <= annotation.start) {
annotation.start = change.start;
annotation.end = change.start;
// [ ]
// ------*---------*--------
} else if (change.start > annotation.start) {
annotation.end = change.start;
}
}
}
}
}
this.triggerChange();
}
canonical() {
let canonicalDoc = this.clone();
let parseTokensToDelete = [];
// preserve order in the original document before
// modifying it, as deleting text ranges may collapse
// annotations onto each other
canonicalDoc.annotations.sort(compareAnnotations);
for (let annotation of canonicalDoc.annotations) {
if (
annotation.vendorPrefix === "atjson" &&
annotation.type === "parse-token"
) {
parseTokensToDelete.push(annotation);
}
}
canonicalDoc.removeAnnotations(parseTokensToDelete);
canonicalDoc.deleteTextRanges(parseTokensToDelete);
return canonicalDoc;
}
equals(docToCompare: Document): boolean {
let canonicalLeftHandSideDoc = this.canonical();
let canonicalRightHandSideDoc = docToCompare.canonical();
let isContentEqual =
canonicalLeftHandSideDoc.content === canonicalRightHandSideDoc.content;
if (!isContentEqual) {
return false;
}
let isAnnotationLengthEqual =
canonicalLeftHandSideDoc.annotations.length ===
canonicalRightHandSideDoc.annotations.length;
if (!isAnnotationLengthEqual) {
return false;
}
return canonicalLeftHandSideDoc.annotations.every(
function matchesRightHandDocAnnotationAtIndex(lhsAnnotation, index) {
return lhsAnnotation.equals(
canonicalRightHandSideDoc.annotations[index]
);
}
);
}
private createAnnotation(
annotation: Annotation<any> | AnnotationJSON
): Annotation<any> {
let DocumentClass = this.constructor as typeof Document;
let schema = [...DocumentClass.schema, ParseAnnotation];
if (annotation instanceof UnknownAnnotation) {
let KnownAnnotation = schema.find(function annotationMatchesClass(
AnnotationClass
) {
return (
annotation.attributes.type ===
`-${AnnotationClass.vendorPrefix}-${AnnotationClass.type}`
);
});
if (KnownAnnotation) {
return KnownAnnotation.hydrate(annotation.toJSON());
}
return annotation;
} else if (annotation instanceof Annotation) {
let AnnotationClass = annotation.getAnnotationConstructor();
if (schema.indexOf(AnnotationClass) === -1) {
let json = annotation.toJSON();
return new UnknownAnnotation({
id: json.id,
start: json.start,
end: json.end,
attributes: {
type: json.type,
attributes: json.attributes,
},
});
}
return annotation;
} else {
let ConcreteAnnotation = schema.find(function annotationMatchesClass(
AnnotationClass
) {
return (
annotation.type ===
`-${AnnotationClass.vendorPrefix}-${AnnotationClass.type}`
);
});
if (ConcreteAnnotation) {
return ConcreteAnnotation.hydrate(annotation);
} else {
return new UnknownAnnotation({
id: annotation.id,
start: annotation.start,
end: annotation.end,
attributes: {
type: annotation.type,
attributes: annotation.attributes,
},
});
}
}
}
/**
* This is really coarse, just enough to allow different code in the editor to detect
* changes in the document without handling that change management separately.
*
* Eventually it should be possible to handle this transactionally, but for
* now we batch all changes enacted within one cycle of the event loop and
* fire the change event only once. n.b that we don't send any information
* about the changes here yet, but that's not to say we couldn't, but rather
* it's not clear right now what the best approach would be so it's left
* undefined.
*/
private triggerChange() {
if (this.pendingChangeEvent) return;
let notifyListeners = () => {
for (let listener of this.changeListeners) {
listener();
}
delete this.pendingChangeEvent;
};
this.pendingChangeEvent = setTimeout(notifyListeners, 0);
}
} | the_stack |
import {
assertCardRule,
assertAssignmentRule,
assertFlagRule,
assertOnlyRule,
assertBindingRule,
assertContainsRule,
assertCaretValueRule,
assertObeysRule,
assertInsertRule,
assertAddElementRule
} from '../testhelpers/asserts';
import {
FshCanonical,
FshCode,
FshQuantity,
FshRatio,
FshReference,
ParamRuleSet
} from '../../src/fshtypes';
import { loggerSpy } from '../testhelpers/loggerSpy';
import { stats } from '../../src/utils/FSHLogger';
import { importSingleText } from '../testhelpers/importSingleText';
import { FSHImporter, RawFSH } from '../../src/import';
import { EOL } from 'os';
import { leftAlign } from '../utils/leftAlign';
describe('FSHImporter', () => {
beforeEach(() => loggerSpy.reset());
describe('SD Rules', () => {
// These rules are shared across all StructureDefinition entities:
// Profile, Extension, Resource, Logical
// The intent is that the comprehensive testing of these common rules occurs here
// while in each StructureDefinition entity test suite, these rules will have simple
// smoke tests.
describe('#cardRule', () => {
it('should parse simple card rules', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category 1..5
* value[x] 1..1
* component 2..*
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(3);
assertCardRule(profile.rules[0], 'category', 1, 5);
assertCardRule(profile.rules[1], 'value[x]', 1, 1);
assertCardRule(profile.rules[2], 'component', 2, '*');
});
it('should parse card rule with only min', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category 1..
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertCardRule(profile.rules[0], 'category', 1, ''); // Unspecified max
});
it('should parse card rule with only max', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category ..5
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertCardRule(profile.rules[0], 'category', NaN, '5'); // Unspecified min
});
it('should log an error if neither side is specified', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category ..
`);
const result = importSingleText(input, 'BadCard.fsh');
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1); // Rule is still set and element's current cardinalities will be used at export
expect(loggerSpy.getLastMessage('error')).toMatch(
/Neither side of the cardinality was specified on path \"category\". A min, max, or both need to be specified.\D*/s
);
expect(loggerSpy.getLastMessage('error')).toMatch(/File: BadCard\.fsh.*Line: 4\D*/s);
});
it('should parse card rules w/ flags', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category 1..5 MS
* value[x] 1..1 ?!
* component 2..* SU
* interpretation 1..* TU
* note 0..11 N
* bodySite 1..1 D
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(12);
assertCardRule(profile.rules[0], 'category', 1, 5);
assertFlagRule(
profile.rules[1],
'category',
true,
undefined,
undefined,
undefined,
undefined,
undefined
);
assertCardRule(profile.rules[2], 'value[x]', 1, 1);
assertFlagRule(
profile.rules[3],
'value[x]',
undefined,
undefined,
true,
undefined,
undefined,
undefined
);
assertCardRule(profile.rules[4], 'component', 2, '*');
assertFlagRule(
profile.rules[5],
'component',
undefined,
true,
undefined,
undefined,
undefined,
undefined
);
assertCardRule(profile.rules[6], 'interpretation', 1, '*');
assertFlagRule(
profile.rules[7],
'interpretation',
undefined,
undefined,
undefined,
true,
undefined,
undefined
);
assertCardRule(profile.rules[8], 'note', 0, '11');
assertFlagRule(
profile.rules[9],
'note',
undefined,
undefined,
undefined,
undefined,
true,
undefined
);
assertCardRule(profile.rules[10], 'bodySite', 1, '1');
assertFlagRule(
profile.rules[11],
'bodySite',
undefined,
undefined,
undefined,
undefined,
undefined,
true
);
});
it('should parse card rules w/ multiple flags', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category 1..5 MS ?! TU
* value[x] 1..1 ?! SU N
* component 2..* SU MS D
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(6);
assertCardRule(profile.rules[0], 'category', 1, 5);
assertFlagRule(
profile.rules[1],
'category',
true,
undefined,
true,
true,
undefined,
undefined
);
assertCardRule(profile.rules[2], 'value[x]', 1, 1);
assertFlagRule(
profile.rules[3],
'value[x]',
undefined,
true,
true,
undefined,
true,
undefined
);
assertCardRule(profile.rules[4], 'component', 2, '*');
assertFlagRule(
profile.rules[5],
'component',
true,
true,
undefined,
undefined,
undefined,
true
);
});
});
describe('#flagRule', () => {
it('should parse single-path single-value flag rules', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category MS
* value[x] ?!
* component SU
* interpretation TU
* note N
* bodySite D
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(6);
assertFlagRule(
profile.rules[0],
'category',
true,
undefined,
undefined,
undefined,
undefined,
undefined
);
assertFlagRule(
profile.rules[1],
'value[x]',
undefined,
undefined,
true,
undefined,
undefined,
undefined
);
assertFlagRule(
profile.rules[2],
'component',
undefined,
true,
undefined,
undefined,
undefined,
undefined
);
assertFlagRule(
profile.rules[3],
'interpretation',
undefined,
undefined,
undefined,
true,
undefined,
undefined
);
assertFlagRule(
profile.rules[4],
'note',
undefined,
undefined,
undefined,
undefined,
true,
undefined
);
assertFlagRule(
profile.rules[5],
'bodySite',
undefined,
undefined,
undefined,
undefined,
undefined,
true
);
});
it('should parse single-path multi-value flag rules', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category MS ?! N
* value[x] ?! SU D
* component MS SU ?! TU
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(3);
assertFlagRule(
profile.rules[0],
'category',
true,
undefined,
true,
undefined,
true,
undefined
);
assertFlagRule(
profile.rules[1],
'value[x]',
undefined,
true,
true,
undefined,
undefined,
true
);
assertFlagRule(profile.rules[2], 'component', true, true, true, true, undefined, undefined);
});
it('should parse multi-path single-value flag rules', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category and value[x] and component MS
* subject and focus ?!
* interpretation and note N
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(7);
assertFlagRule(
profile.rules[0],
'category',
true,
undefined,
undefined,
undefined,
undefined,
undefined
);
assertFlagRule(
profile.rules[1],
'value[x]',
true,
undefined,
undefined,
undefined,
undefined,
undefined
);
assertFlagRule(
profile.rules[2],
'component',
true,
undefined,
undefined,
undefined,
undefined,
undefined
);
assertFlagRule(
profile.rules[3],
'subject',
undefined,
undefined,
true,
undefined,
undefined,
undefined
);
assertFlagRule(
profile.rules[4],
'focus',
undefined,
undefined,
true,
undefined,
undefined,
undefined
);
assertFlagRule(
profile.rules[5],
'interpretation',
undefined,
undefined,
undefined,
undefined,
true,
undefined
);
assertFlagRule(
profile.rules[6],
'note',
undefined,
undefined,
undefined,
undefined,
true,
undefined
);
});
it('should parse multi-path multi-value flag rules', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category and value[x] and component MS SU N
* subject and focus ?! SU TU
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(5);
assertFlagRule(
profile.rules[0],
'category',
true,
true,
undefined,
undefined,
true,
undefined
);
assertFlagRule(
profile.rules[1],
'value[x]',
true,
true,
undefined,
undefined,
true,
undefined
);
assertFlagRule(
profile.rules[2],
'component',
true,
true,
undefined,
undefined,
true,
undefined
);
assertFlagRule(
profile.rules[3],
'subject',
undefined,
true,
true,
true,
undefined,
undefined
);
assertFlagRule(
profile.rules[4],
'focus',
undefined,
true,
true,
true,
undefined,
undefined
);
});
it('should log an error when paths are listed with commas', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category, value[x] , component MS SU N
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(0);
expect(loggerSpy.getLastMessage('error')).toMatch(
/Using ',' to list items is no longer supported/s
);
});
});
describe('#BindingRule', () => {
it('should parse value set rules w/ names and strengths', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category from CategoryValueSet (required)
* code from CodeValueSet (extensible)
* valueCodeableConcept from ValueValueSet (preferred)
* component.code from ComponentCodeValueSet (example)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(4);
assertBindingRule(profile.rules[0], 'category', 'CategoryValueSet', 'required');
assertBindingRule(profile.rules[1], 'code', 'CodeValueSet', 'extensible');
assertBindingRule(profile.rules[2], 'valueCodeableConcept', 'ValueValueSet', 'preferred');
assertBindingRule(profile.rules[3], 'component.code', 'ComponentCodeValueSet', 'example');
});
it('should parse value set rules w/ urls and strengths', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category from http://example.org/fhir/ValueSet/CategoryValueSet (required)
* code from http://example.org/fhir/ValueSet/CodeValueSet (extensible)
* valueCodeableConcept from http://example.org/fhir/ValueSet/ValueValueSet (preferred)
* component.code from http://example.org/fhir/ValueSet/ComponentCodeValueSet (example)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(4);
assertBindingRule(
profile.rules[0],
'category',
'http://example.org/fhir/ValueSet/CategoryValueSet',
'required'
);
assertBindingRule(
profile.rules[1],
'code',
'http://example.org/fhir/ValueSet/CodeValueSet',
'extensible'
);
assertBindingRule(
profile.rules[2],
'valueCodeableConcept',
'http://example.org/fhir/ValueSet/ValueValueSet',
'preferred'
);
assertBindingRule(
profile.rules[3],
'component.code',
'http://example.org/fhir/ValueSet/ComponentCodeValueSet',
'example'
);
});
it('should accept and translate aliases for value set URLs', () => {
const input = leftAlign(`
Alias: CAT = http://example.org/fhir/ValueSet/CategoryValueSet
Alias: CODE = http://example.org/fhir/ValueSet/CodeValueSet
Alias: VALUE = http://example.org/fhir/ValueSet/ValueValueSet
Alias: COMP = http://example.org/fhir/ValueSet/ComponentCodeValueSet
Profile: ObservationProfile
Parent: Observation
* category from CAT (required)
* code from CODE (extensible)
* valueCodeableConcept from VALUE (preferred)
* component.code from COMP (example)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(4);
assertBindingRule(
profile.rules[0],
'category',
'http://example.org/fhir/ValueSet/CategoryValueSet',
'required'
);
assertBindingRule(
profile.rules[1],
'code',
'http://example.org/fhir/ValueSet/CodeValueSet',
'extensible'
);
assertBindingRule(
profile.rules[2],
'valueCodeableConcept',
'http://example.org/fhir/ValueSet/ValueValueSet',
'preferred'
);
assertBindingRule(
profile.rules[3],
'component.code',
'http://example.org/fhir/ValueSet/ComponentCodeValueSet',
'example'
);
});
it('should parse value set rules w/ numeric names', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category from 123 (required)
* code from 456 (extensible)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(2);
assertBindingRule(profile.rules[0], 'category', '123', 'required');
assertBindingRule(profile.rules[1], 'code', '456', 'extensible');
});
it('should parse value set rules w/ no strength and default to required', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category from CategoryValueSet
* code from http://example.org/fhir/ValueSet/CodeValueSet
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(2);
assertBindingRule(profile.rules[0], 'category', 'CategoryValueSet', 'required');
assertBindingRule(
profile.rules[1],
'code',
'http://example.org/fhir/ValueSet/CodeValueSet',
'required'
);
});
it('should ignore the units keyword and log an error when parsing value set rules on Quantity', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueQuantity units from http://unitsofmeasure.org
`);
const result = importSingleText(input, 'UselessQuant.fsh');
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(0);
expect(loggerSpy.getLastMessage('error')).toMatch(
/The 'units' keyword is no longer supported.*File: UselessQuant\.fsh.*Line: 4\D*/s
);
});
});
describe('#assignmentRule', () => {
it('should parse assigned value boolean rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueBoolean = true
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertAssignmentRule(profile.rules[0], 'valueBoolean', true);
});
it('should parse assigned value boolean rule with (exactly) modifier', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueBoolean = true (exactly)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertAssignmentRule(profile.rules[0], 'valueBoolean', true, true);
});
it('should parse assigned value number (decimal) rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueDecimal = 1.23
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertAssignmentRule(profile.rules[0], 'valueDecimal', 1.23);
});
it('should parse assigned value number (integer) rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueInteger = 123
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertAssignmentRule(profile.rules[0], 'valueInteger', BigInt(123));
});
it('should parse assigned value string rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueString = "hello world"
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertAssignmentRule(profile.rules[0], 'valueString', 'hello world');
});
it('should parse assigned value multi-line string rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueString = """
hello
world
"""
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertAssignmentRule(profile.rules[0], 'valueString', 'hello\nworld');
});
it('should parse assigned value date rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueDateTime = 2019-11-01T12:30:01.999Z
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
// For now, treating dates like strings
assertAssignmentRule(profile.rules[0], 'valueDateTime', '2019-11-01T12:30:01.999Z');
});
it('should parse assigned value time rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueTime = 12:30:01.999-05:00
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
// For now, treating dates like strings
assertAssignmentRule(profile.rules[0], 'valueTime', '12:30:01.999-05:00');
});
it('should parse assigned value code rule', () => {
const input = leftAlign(`
Alias: LOINC = http://loinc.org
Profile: ObservationProfile
Parent: Observation
* status = #final
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedCode = new FshCode('final').withLocation([6, 12, 6, 17]).withFile('');
assertAssignmentRule(profile.rules[0], 'status', expectedCode);
});
it('should parse assigned value CodeableConcept rule', () => {
const input = leftAlign(`
Alias: LOINC = http://loinc.org
Profile: ObservationProfile
Parent: Observation
* valueCodeableConcept = LOINC#718-7 "Hemoglobin [Mass/volume] in Blood"
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedCode = new FshCode(
'718-7',
'http://loinc.org',
'Hemoglobin [Mass/volume] in Blood'
)
.withLocation([6, 26, 6, 72])
.withFile('');
assertAssignmentRule(profile.rules[0], 'valueCodeableConcept', expectedCode);
});
it('should parse assigned value CodeableConcept rule with (exactly) modifier', () => {
const input = leftAlign(`
Alias: LOINC = http://loinc.org
Profile: ObservationProfile
Parent: Observation
* valueCodeableConcept = LOINC#718-7 "Hemoglobin [Mass/volume] in Blood" (exactly)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedCode = new FshCode(
'718-7',
'http://loinc.org',
'Hemoglobin [Mass/volume] in Blood'
)
.withLocation([6, 26, 6, 72])
.withFile('');
assertAssignmentRule(profile.rules[0], 'valueCodeableConcept', expectedCode, true);
});
it('should ignore the units keyword and log a warning when parsing an assigned value FSHCode rule with units on Quantity', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueQuantity units = http://unitsofmeasure.org#cGy
`);
const result = importSingleText(input, 'UselessUnits.fsh');
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(0);
expect(loggerSpy.getLastMessage('error')).toMatch(
/The 'units' keyword is no longer supported.*File: UselessUnits\.fsh.*Line: 4\D*/s
);
});
it('should parse assigned value Quantity rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueQuantity = 1.5 'mm'
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedQuantity = new FshQuantity(
1.5,
new FshCode('mm', 'http://unitsofmeasure.org').withLocation([5, 23, 5, 26]).withFile('')
)
.withLocation([5, 19, 5, 26])
.withFile('');
assertAssignmentRule(profile.rules[0], 'valueQuantity', expectedQuantity);
});
it('should parse assigned value Quantity rule with unit display', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueQuantity = 155.0 '[lb_av]' "lb"
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedQuantity = new FshQuantity(
155.0,
new FshCode('[lb_av]', 'http://unitsofmeasure.org', 'lb')
.withLocation([5, 25, 5, 33])
.withFile('')
)
.withLocation([5, 19, 5, 38])
.withFile('');
assertAssignmentRule(profile.rules[0], 'valueQuantity', expectedQuantity);
});
it('should parse assigned value Ratio rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueRatio = 130 'mg' : 1 'dL'
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedRatio = new FshRatio(
new FshQuantity(
130,
new FshCode('mg', 'http://unitsofmeasure.org').withLocation([5, 20, 5, 23]).withFile('')
)
.withLocation([5, 16, 5, 23])
.withFile(''),
new FshQuantity(
1,
new FshCode('dL', 'http://unitsofmeasure.org').withLocation([5, 29, 5, 32]).withFile('')
)
.withLocation([5, 27, 5, 32])
.withFile('')
)
.withLocation([5, 16, 5, 32])
.withFile('');
assertAssignmentRule(profile.rules[0], 'valueRatio', expectedRatio);
});
it('should parse assigned value Ratio rule w/ numeric numerator', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueRatio = 130 : 1 'dL'
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedRatio = new FshRatio(
new FshQuantity(130).withLocation([5, 16, 5, 18]).withFile(''),
new FshQuantity(
1,
new FshCode('dL', 'http://unitsofmeasure.org').withLocation([5, 24, 5, 27]).withFile('')
)
.withLocation([5, 22, 5, 27])
.withFile('')
)
.withLocation([5, 16, 5, 27])
.withFile('');
assertAssignmentRule(profile.rules[0], 'valueRatio', expectedRatio);
});
it('should parse assigned value Ratio rule w/ numeric denominator', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueRatio = 130 'mg' : 1
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedRatio = new FshRatio(
new FshQuantity(
130,
new FshCode('mg', 'http://unitsofmeasure.org').withLocation([5, 20, 5, 23]).withFile('')
)
.withLocation([5, 16, 5, 23])
.withFile(''),
new FshQuantity(1).withLocation([5, 27, 5, 27]).withFile('')
)
.withLocation([5, 16, 5, 27])
.withFile('');
assertAssignmentRule(profile.rules[0], 'valueRatio', expectedRatio);
});
it('should parse assigned value Ratio rule w/ numeric numerator and denominator', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueRatio = 130 : 1
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedRatio = new FshRatio(
new FshQuantity(130).withLocation([5, 16, 5, 18]).withFile(''),
new FshQuantity(1).withLocation([5, 22, 5, 22]).withFile('')
)
.withLocation([5, 16, 5, 22])
.withFile('');
assertAssignmentRule(profile.rules[0], 'valueRatio', expectedRatio);
});
it('should parse assigned value Reference rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* basedOn = Reference(fooProfile)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedReference = new FshReference('fooProfile')
.withLocation([5, 13, 5, 33])
.withFile('');
assertAssignmentRule(profile.rules[0], 'basedOn', expectedReference);
});
it('should parse assigned value Reference rules while allowing and translating aliases', () => {
const input = leftAlign(`
Alias: FOO = http://hl7.org/fhir/StructureDefinition/Foo
Profile: ObservationProfile
Parent: Observation
* basedOn = Reference(FOO) "bar"
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedReference = new FshReference(
'http://hl7.org/fhir/StructureDefinition/Foo',
'bar'
)
.withLocation([6, 13, 6, 32])
.withFile('');
assertAssignmentRule(profile.rules[0], 'basedOn', expectedReference);
});
it('should parse assigned value Reference rule with a display string', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* basedOn = Reference(fooProfile) "bar"
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedReference = new FshReference('fooProfile', 'bar')
.withLocation([5, 13, 5, 39])
.withFile('');
assertAssignmentRule(profile.rules[0], 'basedOn', expectedReference);
});
it('should parse assigned value Reference rule with whitespace', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* basedOn = Reference( fooProfile )
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedReference = new FshReference('fooProfile')
.withLocation([5, 13, 5, 39])
.withFile('');
assertAssignmentRule(profile.rules[0], 'basedOn', expectedReference);
});
it('should log an error when an assigned value Reference rule has a choice of references', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* basedOn = Reference(cakeProfile or pieProfile)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedReference = new FshReference('cakeProfile')
.withLocation([5, 13, 5, 48])
.withFile('');
assertAssignmentRule(profile.rules[0], 'basedOn', expectedReference);
expect(loggerSpy.getLastMessage('error')).toMatch(
/Multiple choices of references are not allowed when setting a value.*Line: 5\D*/s
);
});
it('should parse assigned value using Canonical', () => {
const input = leftAlign(`
CodeSystem: Example
* #first
* #second
Profile: ObservationProfile
Parent: Observation
* code.coding.system = Canonical(Example)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedCanonical = new FshCanonical('Example')
.withLocation([8, 24, 8, 41])
.withFile('');
assertAssignmentRule(profile.rules[0], 'code.coding.system', expectedCanonical);
});
it('should parse assigned value using Canonical with spaces around entity name', () => {
const input = leftAlign(`
CodeSystem: SpaceyExample
* #first
* #second
Profile: ObservationProfile
Parent: Observation
* code.coding.system = Canonical( SpaceyExample )
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedCanonical = new FshCanonical('SpaceyExample') // No spaces are included in the entityName
.withLocation([8, 24, 8, 51])
.withFile('');
assertAssignmentRule(profile.rules[0], 'code.coding.system', expectedCanonical);
});
it('should parse assigned value using Canonical with a version', () => {
const input = leftAlign(`
CodeSystem: Example
* #first
* #second
Profile: ObservationProfile
Parent: Observation
* code.coding.system = Canonical(Example|1.2.3)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedCanonical = new FshCanonical('Example')
.withLocation([8, 24, 8, 47])
.withFile('');
expectedCanonical.version = '1.2.3';
assertAssignmentRule(profile.rules[0], 'code.coding.system', expectedCanonical);
});
it('should parse assigned value using Canonical with a version which contains a |', () => {
const input = leftAlign(`
CodeSystem: Example
* #first
* #second
Profile: ObservationProfile
Parent: Observation
* code.coding.system = Canonical( Example|1.2.3|aWeirdVersion )
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedCanonical = new FshCanonical('Example')
.withLocation([8, 24, 8, 65])
.withFile('');
expectedCanonical.version = '1.2.3|aWeirdVersion';
assertAssignmentRule(profile.rules[0], 'code.coding.system', expectedCanonical);
});
it('should parse assigned values that are an alias', () => {
const input = leftAlign(`
Alias: EXAMPLE = http://example.org
Profile: PatientProfile
Parent: Patient
* identifier.system = EXAMPLE
`);
const result = importSingleText(input);
const profile = result.profiles.get('PatientProfile');
expect(profile.rules).toHaveLength(1);
assertAssignmentRule(profile.rules[0], 'identifier.system', 'http://example.org');
});
it('should parse an assigned value Resource rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* contained[0] = SomeInstance
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertAssignmentRule(profile.rules[0], 'contained[0]', 'SomeInstance', false, true);
});
});
describe('#onlyRule', () => {
it('should parse an only rule with one type', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* value[x] only Quantity
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertOnlyRule(profile.rules[0], 'value[x]', { type: 'Quantity' });
});
it('should parse an only rule with multiple types', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* value[x] only Quantity or CodeableConcept or string
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertOnlyRule(
profile.rules[0],
'value[x]',
{ type: 'Quantity' },
{ type: 'CodeableConcept' },
{ type: 'string' }
);
});
it('should parse an only rule with one numeric type name', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* value[x] only 123
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertOnlyRule(profile.rules[0], 'value[x]', { type: '123' });
});
it('should parse an only rule with multiple numeric type names', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* value[x] only 123 or 456 or 789
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertOnlyRule(
profile.rules[0],
'value[x]',
{ type: '123' },
{ type: '456' },
{ type: '789' }
);
});
it('should parse an only rule with a reference to one type', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* performer only Reference(Practitioner)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertOnlyRule(profile.rules[0], 'performer', { type: 'Practitioner', isReference: true });
});
it('should parse an only rule with a reference to multiple types', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* performer only Reference(Organization or CareTeam)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertOnlyRule(
profile.rules[0],
'performer',
{ type: 'Organization', isReference: true },
{ type: 'CareTeam', isReference: true }
);
});
it('should parse an only rule with a reference to multiple types with whitespace', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* performer only Reference( Organization or CareTeam)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertOnlyRule(
profile.rules[0],
'performer',
{ type: 'Organization', isReference: true },
{ type: 'CareTeam', isReference: true }
);
});
it('should allow and translate aliases for only types', () => {
const input = leftAlign(`
Alias: QUANTITY = http://hl7.org/fhir/StructureDefinition/Quantity
Alias: CODING = http://hl7.org/fhir/StructureDefinition/Coding
Profile: ObservationProfile
Parent: Observation
* value[x] only CodeableConcept or CODING or string or QUANTITY
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertOnlyRule(
profile.rules[0],
'value[x]',
{ type: 'CodeableConcept' },
{ type: 'http://hl7.org/fhir/StructureDefinition/Coding' },
{ type: 'string' },
{ type: 'http://hl7.org/fhir/StructureDefinition/Quantity' }
);
});
it('should log an error when references are listed with pipes', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* performer only Reference(Organization | CareTeam)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
// Following is correct expectation. Error prevents the proper resolution of multiple references
assertOnlyRule(profile.rules[0], 'performer', { type: 'Reference(Organization' });
expect(loggerSpy.getLastMessage('error')).toMatch(
/Using '|' to list references is no longer supported\..*Line: 4\D*/s
);
});
it('should log an error when references are listed with pipes with whitespace', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* performer only Reference( Organization | CareTeam)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
// Following is correct expectation. Error prevents the proper resolution of multiple references
assertOnlyRule(profile.rules[0], 'performer', { type: 'Reference(' });
expect(loggerSpy.getLastMessage('error')).toMatch(
/Using '|' to list references is no longer supported\..*Line: 4\D*/s
);
});
});
describe('#containsRule', () => {
it('should parse contains rule with one item', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* component contains SystolicBP 1..1
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(2);
assertContainsRule(profile.rules[0], 'component', 'SystolicBP');
assertCardRule(profile.rules[1], 'component[SystolicBP]', 1, 1);
});
it('should parse contains rule with one item declaring an aliased type', () => {
const input = leftAlign(`
Alias: OffsetExtension = http://hl7.org/fhir/StructureDefinition/observation-timeOffset
Profile: ObservationProfile
Parent: Observation
* component.extension contains OffsetExtension named offset 0..1
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(2);
assertContainsRule(profile.rules[0], 'component.extension', {
name: 'offset',
type: 'http://hl7.org/fhir/StructureDefinition/observation-timeOffset'
});
assertCardRule(profile.rules[1], 'component.extension[offset]', 0, 1);
});
it('should parse contains rule with one item declaring an FSH extension type', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* component.extension contains ComponentExtension named compext 0..1
Extension: ComponentExtension
Id: component-extension
* value[x] only CodeableConcept
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(2);
assertContainsRule(profile.rules[0], 'component.extension', {
name: 'compext',
type: 'ComponentExtension'
});
assertCardRule(profile.rules[1], 'component.extension[compext]', 0, 1);
});
it('should parse contains rules with multiple items', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* component contains SystolicBP 1..1 and DiastolicBP 2..*
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(3);
assertContainsRule(profile.rules[0], 'component', 'SystolicBP', 'DiastolicBP');
assertCardRule(profile.rules[1], 'component[SystolicBP]', 1, 1);
assertCardRule(profile.rules[2], 'component[DiastolicBP]', 2, '*');
});
it('should parse contains rule with mutliple items, some declaring types', () => {
const input = leftAlign(`
Alias: FocusCodeExtension = http://hl7.org/fhir/StructureDefinition/observation-focusCode
Alias: PreconditionExtension = http://hl7.org/fhir/StructureDefinition/observation-precondition
Profile: ObservationProfile
Parent: Observation
* extension contains
foo 0..1 and
FocusCodeExtension named focus 1..1 and
bar 0..* and
PreconditionExtension named pc 1..*
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(5);
assertContainsRule(
profile.rules[0],
'extension',
'foo',
{
name: 'focus',
type: 'http://hl7.org/fhir/StructureDefinition/observation-focusCode'
},
'bar',
{
name: 'pc',
type: 'http://hl7.org/fhir/StructureDefinition/observation-precondition'
}
);
assertCardRule(profile.rules[1], 'extension[foo]', 0, 1);
assertCardRule(profile.rules[2], 'extension[focus]', 1, 1);
assertCardRule(profile.rules[3], 'extension[bar]', 0, '*');
assertCardRule(profile.rules[4], 'extension[pc]', 1, '*');
});
it('should parse contains rules with flags', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* component contains SystolicBP 1..1 MS D and DiastolicBP 2..* MS SU
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(5);
assertContainsRule(profile.rules[0], 'component', 'SystolicBP', 'DiastolicBP');
assertCardRule(profile.rules[1], 'component[SystolicBP]', 1, 1);
assertFlagRule(
profile.rules[2],
'component[SystolicBP]',
true,
undefined,
undefined,
undefined,
undefined,
true
);
assertCardRule(profile.rules[3], 'component[DiastolicBP]', 2, '*');
assertFlagRule(
profile.rules[4],
'component[DiastolicBP]',
true,
true,
undefined,
undefined,
undefined,
undefined
);
});
it('should parse contains rule with item declaring a type and flags', () => {
const input = leftAlign(`
Alias: OffsetExtension = http://hl7.org/fhir/StructureDefinition/observation-timeOffset
Profile: ObservationProfile
Parent: Observation
* component.extension contains OffsetExtension named offset 0..1 MS TU
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(3);
assertContainsRule(profile.rules[0], 'component.extension', {
name: 'offset',
type: 'http://hl7.org/fhir/StructureDefinition/observation-timeOffset'
});
assertCardRule(profile.rules[1], 'component.extension[offset]', 0, 1);
assertFlagRule(
profile.rules[2],
'component.extension[offset]',
true,
undefined,
undefined,
true,
undefined,
undefined
);
});
});
describe('#caretValueRule', () => {
it('should parse caret value rules with no path', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* ^description = "foo"
* ^experimental = false
* ^keyword[0] = foo#bar "baz"
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
assertCaretValueRule(profile.rules[0], '', 'description', 'foo', false);
assertCaretValueRule(profile.rules[1], '', 'experimental', false, false);
assertCaretValueRule(
profile.rules[2],
'',
'keyword[0]',
new FshCode('bar', 'foo', 'baz').withLocation([6, 17, 6, 29]).withFile(''),
false
);
});
it('should parse caret value rules with a path', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* status ^short = "foo"
* status ^sliceIsConstraining = false
* status ^code[0] = foo#bar "baz"
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
assertCaretValueRule(profile.rules[0], 'status', 'short', 'foo', false);
assertCaretValueRule(profile.rules[1], 'status', 'sliceIsConstraining', false, false);
assertCaretValueRule(
profile.rules[2],
'status',
'code[0]',
new FshCode('bar', 'foo', 'baz').withLocation([6, 21, 6, 33]).withFile(''),
false
);
});
it('should not include non-breaking spaces as part of the caret path', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* status ^short\u00A0= "Non-breaking"
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
assertCaretValueRule(profile.rules[0], 'status', 'short', 'Non-breaking', false);
});
it('should add resources to the contained array using a CaretValueRule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* ^contained = myResource
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
assertCaretValueRule(profile.rules[0], '', 'contained', 'myResource', true);
});
});
describe('#obeysRule', () => {
it('should parse an obeys rule with one invariant and no path', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* obeys SomeInvariant
`);
const result = importSingleText(input, 'Obeys.fsh');
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertObeysRule(profile.rules[0], '', 'SomeInvariant');
});
it('should parse an obeys rule with one invariant and a path', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category obeys SomeInvariant
`);
const result = importSingleText(input, 'Obeys.fsh');
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertObeysRule(profile.rules[0], 'category', 'SomeInvariant');
});
it('should parse an obeys rule with multiple invariants and no path', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* obeys SomeInvariant and ThisInvariant and ThatInvariant
`);
const result = importSingleText(input, 'Obeys.fsh');
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(3);
assertObeysRule(profile.rules[0], '', 'SomeInvariant');
assertObeysRule(profile.rules[1], '', 'ThisInvariant');
assertObeysRule(profile.rules[2], '', 'ThatInvariant');
});
it('should parse an obeys rule with multiple invariants and a path', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category obeys SomeInvariant and ThisInvariant and ThatInvariant
`);
const result = importSingleText(input, 'Obeys.fsh');
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(3);
assertObeysRule(profile.rules[0], 'category', 'SomeInvariant');
assertObeysRule(profile.rules[1], 'category', 'ThisInvariant');
assertObeysRule(profile.rules[2], 'category', 'ThatInvariant');
});
it('should parse an obeys rule with a numeric invariant name', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* obeys 123
`);
const result = importSingleText(input, 'Obeys.fsh');
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertObeysRule(profile.rules[0], '', '123');
});
});
describe('#insertRule', () => {
let importer: FSHImporter;
beforeEach(() => {
// To explain a bit about why stats are used here and not in other tests:
// When parsing generated documents, the logging level is temporarily raised
// in order to suppress console output. However, messages still go to the logger
// and therefore are detected by loggerSpy. However, the stats should provide an
// accurate reflection of the number of times that errors and warnings were logged
// while the logger is at the normal level.
loggerSpy.reset();
stats.reset();
importer = new FSHImporter();
// RuleSet: OneParamRuleSet (val)
// * status = {val}
const oneParamRuleSet = new ParamRuleSet('OneParamRuleSet')
.withFile('RuleSet.fsh')
.withLocation([1, 12, 2, 27]);
oneParamRuleSet.parameters = ['val'];
oneParamRuleSet.contents = '* status = {val}';
importer.paramRuleSets.set(oneParamRuleSet.name, oneParamRuleSet);
// RuleSet: MultiParamRuleSet (status, value, maxNote)
// * status = {status}
// * valueString = {value}
// * note 0..{maxNote}
const multiParamRuleSet = new ParamRuleSet('MultiParamRuleSet')
.withFile('RuleSet.fsh')
.withLocation([4, 12, 7, 30]);
multiParamRuleSet.parameters = ['status', 'value', 'maxNote'];
multiParamRuleSet.contents = [
'* status = {status}',
'* valueString = {value}',
'* note 0..{maxNote}'
].join(EOL);
importer.paramRuleSets.set(multiParamRuleSet.name, multiParamRuleSet);
// RuleSet: EntryRules (continuation)
// * insert {continuation}Rules (5)
const entryRules = new ParamRuleSet('EntryRules')
.withFile('RuleSet.fsh')
.withLocation([9, 12, 10, 43]);
entryRules.parameters = ['continuation'];
entryRules.contents = '* insert {continuation}Rules (5)';
importer.paramRuleSets.set(entryRules.name, entryRules);
// RuleSet: RecursiveRules (value)
// * interpretation 0..{value}
// * insert EntryRules (BaseCase)
const recursiveRules = new ParamRuleSet('RecursiveRules')
.withFile('RuleSet.fsh')
.withLocation([12, 12, 14, 41]);
recursiveRules.parameters = ['value'];
recursiveRules.contents = [
'* interpretation 0..{value}',
'* insert EntryRules (BaseCase)'
].join(EOL);
importer.paramRuleSets.set(recursiveRules.name, recursiveRules);
// RuleSet: BaseCaseRules (value)
// * note 0..{value}
const baseCaseRules = new ParamRuleSet('BaseCaseRules')
.withFile('RuleSet.fsh')
.withLocation([16, 12, 17, 28]);
baseCaseRules.parameters = ['value'];
baseCaseRules.contents = '* note 0..{value}';
importer.paramRuleSets.set(baseCaseRules.name, baseCaseRules);
// RuleSet: CardRuleSet (path, min, max)
// * {path} {min}..{max}
// * note {min}..{max}
const cardRuleSet = new ParamRuleSet('CardRuleSet')
.withFile('RuleSet.fsh')
.withLocation([19, 12, 21, 30]);
cardRuleSet.parameters = ['path', 'min', 'max'];
cardRuleSet.contents = ['* {path} {min}..{max}', '* note {min}..{max}'].join(EOL);
importer.paramRuleSets.set(cardRuleSet.name, cardRuleSet);
// RuleSet: FirstRiskyRuleSet (value)
// * note ={value}
// * insert SecondRiskyRuleSet({value})
const firstRiskyRuleSet = new ParamRuleSet('FirstRiskyRuleSet')
.withFile('RuleSet.fsh')
.withLocation([23, 12, 25, 47]);
firstRiskyRuleSet.parameters = ['value'];
firstRiskyRuleSet.contents = [
'* note ={value}',
'* insert SecondRiskyRuleSet({value})'
].join(EOL);
importer.paramRuleSets.set(firstRiskyRuleSet.name, firstRiskyRuleSet);
// RuleSet: SecondRiskyRuleSet(value)
// * status ={value}
const secondRiskyRuleSet = new ParamRuleSet('SecondRiskyRuleSet')
.withFile('RuleSet.fsh')
.withLocation([27, 12, 28, 28]);
secondRiskyRuleSet.parameters = ['value'];
secondRiskyRuleSet.contents = '* status ={value}';
importer.paramRuleSets.set(secondRiskyRuleSet.name, secondRiskyRuleSet);
// RuleSet: WarningRuleSet(value)
// * focus[0] only Reference(Patient | {value})
// * focus[1] only Reference(Group | {value})
const warningRuleSet = new ParamRuleSet('WarningRuleSet')
.withFile('RuleSet.fsh')
.withLocation([30, 12, 32, 53]);
warningRuleSet.parameters = ['value'];
warningRuleSet.contents = [
'* focus[0] only Reference(Patient | {value})',
'* focus[1] only Reference(Group | {value})'
].join(EOL);
importer.paramRuleSets.set(warningRuleSet.name, warningRuleSet);
});
it('should parse an insert rule with a single RuleSet', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* insert MyRuleSet
`);
const result = importSingleText(input, 'Insert.fsh');
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertInsertRule(profile.rules[0], '', 'MyRuleSet');
});
it('should parse an insert rule with a RuleSet with one parameter', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* insert OneParamRuleSet (#final)
`);
const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(loggerSpy.getAllMessages('error')).toHaveLength(0);
expect(allDocs).toHaveLength(1);
const doc = allDocs[0];
const profile = doc.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertInsertRule(profile.rules[0], '', 'OneParamRuleSet', ['#final']);
const appliedRuleSet = doc.appliedRuleSets.get(
JSON.stringify(['OneParamRuleSet', '#final'])
);
expect(appliedRuleSet).toBeDefined();
expect(appliedRuleSet.sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 1,
startColumn: 12,
endLine: 2,
endColumn: 27
}
});
expect(appliedRuleSet.rules[0].sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 2,
startColumn: 1,
endLine: 2,
endColumn: 17
}
});
});
it('should parse an insert rule with a RuleSet with multiple parameters', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* insert MultiParamRuleSet (#preliminary, "this is a string value\\, right?", 4)
`);
const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(loggerSpy.getAllMessages('error')).toHaveLength(0);
expect(allDocs).toHaveLength(1);
const doc = allDocs[0];
const profile = doc.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertInsertRule(profile.rules[0], '', 'MultiParamRuleSet', [
'#preliminary',
'"this is a string value, right?"',
'4'
]);
const appliedRuleSet = doc.appliedRuleSets.get(
JSON.stringify([
'MultiParamRuleSet',
'#preliminary',
'"this is a string value, right?"',
'4'
])
);
expect(appliedRuleSet).toBeDefined();
expect(appliedRuleSet.sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 4,
startColumn: 12,
endLine: 7,
endColumn: 30
}
});
expect(appliedRuleSet.rules).toHaveLength(3);
assertAssignmentRule(
appliedRuleSet.rules[0],
'status',
new FshCode('preliminary').withFile('Insert.fsh').withLocation([2, 12, 2, 23]),
false,
false
);
expect(appliedRuleSet.rules[0].sourceInfo.file).toBe('RuleSet.fsh');
expect(appliedRuleSet.rules[0].sourceInfo.location.startLine).toBe(5);
expect(appliedRuleSet.rules[0].sourceInfo.location.endLine).toBe(5);
assertAssignmentRule(
appliedRuleSet.rules[1],
'valueString',
'this is a string value, right?',
false,
false
);
expect(appliedRuleSet.rules[1].sourceInfo.file).toBe('RuleSet.fsh');
expect(appliedRuleSet.rules[1].sourceInfo.location.startLine).toBe(6);
expect(appliedRuleSet.rules[1].sourceInfo.location.endLine).toBe(6);
assertCardRule(appliedRuleSet.rules[2], 'note', 0, '4');
expect(appliedRuleSet.rules[2].sourceInfo.file).toBe('RuleSet.fsh');
expect(appliedRuleSet.rules[2].sourceInfo.location.startLine).toBe(7);
expect(appliedRuleSet.rules[2].sourceInfo.location.endLine).toBe(7);
});
it('should parse an insert rule with a parameter that contains right parenthesis', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* insert OneParamRuleSet (#final "(Final\\)")
`);
const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(loggerSpy.getAllMessages('error')).toHaveLength(0);
expect(allDocs).toHaveLength(1);
const doc = allDocs[0];
const profile = doc.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertInsertRule(profile.rules[0], '', 'OneParamRuleSet', ['#final "(Final)"']);
const appliedRuleSet = doc.appliedRuleSets.get(
JSON.stringify(['OneParamRuleSet', '#final "(Final)"'])
);
expect(appliedRuleSet).toBeDefined();
expect(appliedRuleSet.rules).toHaveLength(1);
expect(appliedRuleSet.sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 1,
startColumn: 12,
endLine: 2,
endColumn: 27
}
});
assertAssignmentRule(
appliedRuleSet.rules[0],
'status',
new FshCode('final', undefined, '(Final)')
.withFile('Insert.fsh')
.withLocation([2, 12, 2, 27]),
false,
false
);
});
it('should parse an insert rule with parameters that contain newline, tab, or backslash characters', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* insert MultiParamRuleSet (#final, "very\\nstrange\\rvalue\\\\\\tindeed", 1)
`);
const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(loggerSpy.getAllMessages('error')).toHaveLength(0);
expect(allDocs).toHaveLength(1);
const doc = allDocs[0];
const profile = doc.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertInsertRule(profile.rules[0], '', 'MultiParamRuleSet', [
'#final',
'"very\\nstrange\\rvalue\\\\\\tindeed"',
'1'
]);
const appliedRuleSet = doc.appliedRuleSets.get(
JSON.stringify([
'MultiParamRuleSet',
'#final',
'"very\\nstrange\\rvalue\\\\\\tindeed"',
'1'
])
);
expect(appliedRuleSet).toBeDefined();
expect(appliedRuleSet.sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 4,
startColumn: 12,
endLine: 7,
endColumn: 30
}
});
expect(appliedRuleSet.rules).toHaveLength(3);
assertAssignmentRule(
appliedRuleSet.rules[0],
'status',
new FshCode('final').withFile('Insert.fsh').withLocation([2, 12, 2, 17]),
false,
false
);
assertAssignmentRule(
appliedRuleSet.rules[1],
'valueString',
'very\nstrange\rvalue\\\tindeed',
false,
false
);
assertCardRule(appliedRuleSet.rules[2], 'note', 0, '1');
});
it('should parse an insert rule that separates its parameters onto multiple lines', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* insert MultiParamRuleSet (
#final,
"string value",
7
)
`);
const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(loggerSpy.getAllMessages('error')).toHaveLength(0);
expect(allDocs).toHaveLength(1);
const doc = allDocs[0];
const profile = doc.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertInsertRule(profile.rules[0], '', 'MultiParamRuleSet', [
'#final',
'"string value"',
'7'
]);
const appliedRuleSet = doc.appliedRuleSets.get(
JSON.stringify(['MultiParamRuleSet', '#final', '"string value"', '7'])
);
expect(appliedRuleSet).toBeDefined();
expect(appliedRuleSet.sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 4,
startColumn: 12,
endLine: 7,
endColumn: 30
}
});
expect(appliedRuleSet.rules).toHaveLength(3);
assertAssignmentRule(
appliedRuleSet.rules[0],
'status',
new FshCode('final').withFile('Insert.fsh').withLocation([2, 12, 2, 17]),
false,
false
);
assertAssignmentRule(appliedRuleSet.rules[1], 'valueString', 'string value', false, false);
assertCardRule(appliedRuleSet.rules[2], 'note', 0, '7');
});
it('should generate a RuleSet only once when inserted with the same parameters multiple times in the same document', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* insert MultiParamRuleSet (#preliminary, "something", 3)
* insert MultiParamRuleSet (#preliminary, "something", 3)
`);
const visitDocSpy = jest.spyOn(importer, 'visitDoc');
const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(loggerSpy.getAllMessages('error')).toHaveLength(0);
expect(allDocs).toHaveLength(1);
const doc = allDocs[0];
expect(doc.appliedRuleSets.size).toBe(1);
// expect one call to visitDoc for the Profile, and one for the generated RuleSet
expect(visitDocSpy).toHaveBeenCalledTimes(2);
// ensure the insert rules are still there (once upon a time, a bug caused the repeated rules to be omitted)
const profile = doc.profiles.get('ObservationProfile');
expect(profile).toBeDefined();
expect(profile.rules).toHaveLength(2);
assertInsertRule(profile.rules[0], '', 'MultiParamRuleSet', [
'#preliminary',
'"something"',
'3'
]);
assertInsertRule(profile.rules[1], '', 'MultiParamRuleSet', [
'#preliminary',
'"something"',
'3'
]);
});
it('should parse an insert rule with parameters that will use the same RuleSet more than once with different parameters each time', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* insert EntryRules (Recursive)
`);
const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(loggerSpy.getAllMessages('error')).toHaveLength(0);
expect(allDocs).toHaveLength(1);
const doc = allDocs[0];
expect(doc.appliedRuleSets.size).toBe(4);
const firstEntryRules = doc.appliedRuleSets.get(
JSON.stringify(['EntryRules', 'Recursive'])
);
expect(firstEntryRules).toBeDefined();
expect(firstEntryRules.sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 9,
startColumn: 12,
endLine: 10,
endColumn: 43
}
});
expect(firstEntryRules.rules).toHaveLength(1);
assertInsertRule(firstEntryRules.rules[0], '', 'RecursiveRules', ['5']);
const recursiveRules = doc.appliedRuleSets.get(JSON.stringify(['RecursiveRules', '5']));
expect(recursiveRules).toBeDefined();
expect(recursiveRules.sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 12,
startColumn: 12,
endLine: 14,
endColumn: 41
}
});
expect(recursiveRules.rules).toHaveLength(2);
assertCardRule(recursiveRules.rules[0], 'interpretation', 0, '5');
assertInsertRule(recursiveRules.rules[1], '', 'EntryRules', ['BaseCase']);
const secondEntryRules = doc.appliedRuleSets.get(
JSON.stringify(['EntryRules', 'BaseCase'])
);
expect(secondEntryRules.sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 9,
startColumn: 12,
endLine: 10,
endColumn: 43
}
});
expect(secondEntryRules.rules).toHaveLength(1);
assertInsertRule(secondEntryRules.rules[0], '', 'BaseCaseRules', ['5']);
const baseCaseRules = doc.appliedRuleSets.get(JSON.stringify(['BaseCaseRules', '5']));
expect(baseCaseRules).toBeDefined();
expect(baseCaseRules.sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 16,
startColumn: 12,
endLine: 17,
endColumn: 28
}
});
expect(baseCaseRules.rules).toHaveLength(1);
assertCardRule(baseCaseRules.rules[0], 'note', 0, '5');
});
it('should log an error and not add a rule when an insert rule has the wrong number of parameters', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* insert OneParamRuleSet (#final, "Final")
`);
const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]);
const doc = allDocs[0];
const profile = doc.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(0);
expect(loggerSpy.getLastMessage('error')).toMatch(
/Incorrect number of parameters applied to RuleSet/s
);
expect(loggerSpy.getLastMessage('error')).toMatch(/File: Insert\.fsh.*Line: 4/s);
});
it('should log an error and not add a rule when an insert rule with parameters refers to an undefined parameterized RuleSet', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* insert MysteriousRuleSet ("mystery")
`);
const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]);
const doc = allDocs[0];
const profile = doc.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(0);
expect(loggerSpy.getLastMessage('error')).toMatch(
/Could not find parameterized RuleSet named MysteriousRuleSet/s
);
expect(loggerSpy.getLastMessage('error')).toMatch(/File: Insert\.fsh.*Line: 4/s);
});
it('should log an error when an insert rule with parameters results in a parser error in the generated RuleSet', () => {
const input = leftAlign(`
Profile: MyObservation
Parent: Observation
* insert CardRuleSet(path with spaces, 1, *)
`);
importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(stats.numError).toBe(1);
expect(loggerSpy.getLastMessage('error')).toMatch(
/Error parsing insert rule with parameterized RuleSet CardRuleSet/s
);
expect(loggerSpy.getLastMessage('error')).toMatch(/File: Insert\.fsh.*Line: 4/s);
});
it('should log one error when nested insert rules with parameters result in multiple parser errors in the generated RuleSets', () => {
const input = leftAlign(`
Profile: MyObservation
Parent: Observation
* note 0..1
* insert FirstRiskyRuleSet("Observation.id")
`);
importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(stats.numError).toBe(1);
expect(loggerSpy.getLastMessage('error')).toMatch(
/Error parsing insert rule with parameterized RuleSet FirstRiskyRuleSet/s
);
expect(loggerSpy.getLastMessage('error')).toMatch(
/Assignment rules must include at least one space both before and after the '=' sign.*File: Insert\.fsh.*Line: 5/s
);
});
it('should not log an error when an insert rule with parameters results in rules that are syntactically correct but semantically invalid', () => {
const input = leftAlign(`
Profile: MyObservation
Parent: Observation
* insert CardRuleSet(nonExistentPath, 7, 4)
`);
const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(allDocs).toHaveLength(1);
const doc = allDocs[0];
expect(doc.appliedRuleSets.size).toBe(1);
const appliedRuleSet = doc.appliedRuleSets.get(
JSON.stringify(['CardRuleSet', 'nonExistentPath', '7', '4'])
);
expect(appliedRuleSet).toBeDefined();
expect(appliedRuleSet.sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 19,
startColumn: 12,
endLine: 21,
endColumn: 30
}
});
// This rule is nonsense, of course, but figuring that out is the job of the exporter, not the importer.
assertCardRule(appliedRuleSet.rules[0], 'nonExistentPath', 7, '4');
assertCardRule(appliedRuleSet.rules[1], 'note', 7, '4');
expect(loggerSpy.getAllMessages('error')).toHaveLength(0);
});
it('should log one error when an insert rule with parameters results in warnings', () => {
const input = leftAlign(`
Profile: MyObservation
Parent: Observation
* insert WarningRuleSet(Device)
`);
importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(stats.numError).toBe(1);
expect(loggerSpy.getLastMessage('error')).toMatch(
/Error parsing insert rule with parameterized RuleSet WarningRuleSet/s
);
expect(loggerSpy.getLastMessage('error')).toMatch(
/Using '|' to list references is no longer supported\. Use 'or' to list multiple references.*File: Insert\.fsh.*Line: 4/s
);
});
it('should log one error when an insert rule with parameters results in non-parser errors', () => {
const input = leftAlign(`
Profile: MyObservation
Parent: Observation
* insert CardRuleSet(nonExistentPath, , )
`);
importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(stats.numError).toBe(1);
expect(loggerSpy.getLastMessage('error')).toMatch(
/Errors parsing insert rule with parameterized RuleSet CardRuleSet/s
);
expect(loggerSpy.getLastMessage('error')).toMatch(/File: Insert\.fsh.*Line: 4/s);
});
});
});
describe('LR Rules', () => {
// These rules are shared across these StructureDefinition entities:
// Resource, Logical
describe('#addElementRule', () => {
it('should parse basic addElement rules with defaulted definition', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 boolean "short boolean"
* stuff 0..* string "short string"
* address 1..* Address "short Address"
* person 0..1 Reference(Patient) "short Reference"
* medication 0..1 Canonical(Medication) "short Canonical"
`);
const result = importSingleText(input);
const resource = result.resources.get('TestResource');
expect(resource.rules).toHaveLength(5);
assertAddElementRule(resource.rules[0], 'isValid', {
card: { min: 1, max: '1' },
types: [{ type: 'boolean' }],
defs: { short: 'short boolean', definition: 'short boolean' }
});
assertAddElementRule(resource.rules[1], 'stuff', {
card: { min: 0, max: '*' },
types: [{ type: 'string' }],
defs: { short: 'short string', definition: 'short string' }
});
assertAddElementRule(resource.rules[2], 'address', {
card: { min: 1, max: '*' },
types: [{ type: 'Address' }],
defs: { short: 'short Address', definition: 'short Address' }
});
assertAddElementRule(resource.rules[3], 'person', {
card: { min: 0, max: '1' },
types: [{ type: 'Patient', isReference: true }],
defs: { short: 'short Reference', definition: 'short Reference' }
});
assertAddElementRule(resource.rules[4], 'medication', {
card: { min: 0, max: '1' },
types: [{ type: 'Medication', isCanonical: true }],
defs: { short: 'short Canonical', definition: 'short Canonical' }
});
});
it('should parse basic addElement rules with specified definition', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 boolean "short boolean" "definition boolean"
* stuff 0..* string "short string" "definition string"
* address 1..* Address "short Address" "definition Address"
* person 0..1 Reference(Patient) "short Reference" "definition Reference"
* medication 0..1 Canonical(Medication|4.0.1) "short Canonical" "definition Canonical"
`);
const result = importSingleText(input);
const resource = result.resources.get('TestResource');
expect(resource.rules).toHaveLength(5);
assertAddElementRule(resource.rules[0], 'isValid', {
card: { min: 1, max: '1' },
types: [{ type: 'boolean' }],
defs: { short: 'short boolean', definition: 'definition boolean' }
});
assertAddElementRule(resource.rules[1], 'stuff', {
card: { min: 0, max: '*' },
types: [{ type: 'string' }],
defs: { short: 'short string', definition: 'definition string' }
});
assertAddElementRule(resource.rules[2], 'address', {
card: { min: 1, max: '*' },
types: [{ type: 'Address' }],
defs: { short: 'short Address', definition: 'definition Address' }
});
assertAddElementRule(resource.rules[3], 'person', {
card: { min: 0, max: '1' },
types: [{ type: 'Patient', isReference: true }],
defs: { short: 'short Reference', definition: 'definition Reference' }
});
assertAddElementRule(resource.rules[4], 'medication', {
card: { min: 0, max: '1' },
types: [{ type: 'Medication|4.0.1', isCanonical: true }],
defs: { short: 'short Canonical', definition: 'definition Canonical' }
});
});
it('should parse addElement rules with multiple targetTypes', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 boolean or number "short boolean"
* stuff 0..* string or markdown "short string"
* address 1..* Address "short Address"
* person 0..1 HumanName or Reference(Patient or RelatedPerson) "short multi-type"
* medication 0..1 CodeableConcept or Canonical(Medication or Immunization) "short multi-type 2"
`);
const result = importSingleText(input);
const resource = result.resources.get('TestResource');
expect(resource.rules).toHaveLength(5);
assertAddElementRule(resource.rules[0], 'isValid', {
card: { min: 1, max: '1' },
types: [{ type: 'boolean' }, { type: 'number' }],
defs: { short: 'short boolean', definition: 'short boolean' }
});
assertAddElementRule(resource.rules[1], 'stuff', {
card: { min: 0, max: '*' },
types: [{ type: 'string' }, { type: 'markdown' }],
defs: { short: 'short string', definition: 'short string' }
});
assertAddElementRule(resource.rules[2], 'address', {
card: { min: 1, max: '*' },
types: [{ type: 'Address' }],
defs: { short: 'short Address', definition: 'short Address' }
});
assertAddElementRule(resource.rules[3], 'person', {
card: { min: 0, max: '1' },
types: [
{ type: 'HumanName', isReference: false },
{ type: 'Patient', isReference: true },
{ type: 'RelatedPerson', isReference: true }
],
defs: { short: 'short multi-type', definition: 'short multi-type' }
});
assertAddElementRule(resource.rules[4], 'medication', {
card: { min: 0, max: '1' },
types: [
{ type: 'CodeableConcept', isCanonical: false },
{ type: 'Medication', isCanonical: true },
{ type: 'Immunization', isCanonical: true }
],
defs: { short: 'short multi-type 2', definition: 'short multi-type 2' }
});
});
it('should parse addElement rules with flags', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 MS ?! boolean "short boolean"
* stuff 0..* MS SU string "short string"
* address 1..* N Address "short Address"
* person 0..1 D TU Reference(Patient) "short Reference"
`);
const result = importSingleText(input);
const resource = result.resources.get('TestResource');
expect(resource.rules).toHaveLength(4);
assertAddElementRule(resource.rules[0], 'isValid', {
card: { min: 1, max: '1' },
flags: { mustSupport: true, modifier: true },
types: [{ type: 'boolean' }],
defs: { short: 'short boolean', definition: 'short boolean' }
});
assertAddElementRule(resource.rules[1], 'stuff', {
card: { min: 0, max: '*' },
flags: { mustSupport: true, summary: true },
types: [{ type: 'string' }],
defs: { short: 'short string', definition: 'short string' }
});
assertAddElementRule(resource.rules[2], 'address', {
card: { min: 1, max: '*' },
flags: { normative: true },
types: [{ type: 'Address' }],
defs: { short: 'short Address', definition: 'short Address' }
});
assertAddElementRule(resource.rules[3], 'person', {
card: { min: 0, max: '1' },
flags: { draft: true, trialUse: true },
types: [{ type: 'Patient', isReference: true }],
defs: { short: 'short Reference', definition: 'short Reference' }
});
});
it('should parse addElement rules with docs', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 MS boolean "is it valid?"
* stuff 0..* string "just stuff" "a list of some stuff"
* address 1..* N Address "current addresses" "at least one address is required"
* person 0..1 D TU Reference(Patient) "an associated patient" "added for TRIAL USE"
`);
const result = importSingleText(input);
const resource = result.resources.get('TestResource');
expect(resource.rules).toHaveLength(4);
assertAddElementRule(resource.rules[0], 'isValid', {
card: { min: 1, max: '1' },
flags: { mustSupport: true },
types: [{ type: 'boolean' }],
defs: { short: 'is it valid?', definition: 'is it valid?' }
});
assertAddElementRule(resource.rules[1], 'stuff', {
card: { min: 0, max: '*' },
types: [{ type: 'string' }],
defs: { short: 'just stuff', definition: 'a list of some stuff' }
});
assertAddElementRule(resource.rules[2], 'address', {
card: { min: 1, max: '*' },
flags: { normative: true },
types: [{ type: 'Address' }],
defs: { short: 'current addresses', definition: 'at least one address is required' }
});
assertAddElementRule(resource.rules[3], 'person', {
card: { min: 0, max: '1' },
flags: { trialUse: true, draft: true },
types: [{ type: 'Patient', isReference: true }],
defs: { short: 'an associated patient', definition: 'added for TRIAL USE' }
});
});
it('should log an error for missing path', () => {
const input = leftAlign(`
Resource: TestResource
* 1..1 boolean "short boolean"
* stuff 0..* string "short string"
* address 1..* Address "short Address"
* person 0..1 Reference(Patient) "short Reference"
`);
const result = importSingleText(input, 'BadPath.fsh');
const resource = result.resources.get('TestResource');
expect(loggerSpy.getLastMessage('error')).toMatch(
/no viable alternative at input.*File: BadPath\.fsh.*Line: 3\D*/s
);
// Error results in excluding the rule with the error, hence length of 3 rather than 4
expect(resource.rules).toHaveLength(3);
});
it('should log an error for missing cardinality', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 boolean "short boolean"
* stuff string "short string"
* address 1..* Address "short Address"
* person 0..1 Reference(Patient) "short Reference"
`);
const result = importSingleText(input, 'BadCard.fsh');
const resource = result.resources.get('TestResource');
expect(loggerSpy.getLastMessage('error')).toMatch(
/extraneous input 'string' expecting {.*}.*File: BadCard\.fsh.*Line: 4\D*/s
);
// Error results in excluding the rule with the error and subsequent rules,
// hence length of 1 rather than 4
expect(resource.rules).toHaveLength(1);
});
it('should log an error when min cardinality is not specified', () => {
const input = leftAlign(`
Logical: LogicalModel
* isInValid ..* string "short string"
`);
const result = importSingleText(input, 'Invalid.fsh');
const logical = result.logicals.get('LogicalModel');
expect(logical.rules).toHaveLength(1);
assertAddElementRule(logical.rules[0], 'isInValid', {
card: { min: NaN, max: '*' },
types: [{ type: 'string' }],
defs: { short: 'short string', definition: 'short string' }
});
expect(loggerSpy.getLastMessage('error')).toMatch(
/The 'min' cardinality attribute in AddElementRule/s
);
});
it('should log an error when max cardinality is not specified', () => {
const input = leftAlign(`
Logical: LogicalModel
* isInValid 0.. string "short string"
`);
const result = importSingleText(input, 'Invalid.fsh');
const logical = result.logicals.get('LogicalModel');
expect(logical.rules).toHaveLength(1);
assertAddElementRule(logical.rules[0], 'isInValid', {
card: { min: 0, max: '' },
types: [{ type: 'string' }],
defs: { short: 'short string', definition: 'short string' }
});
expect(loggerSpy.getLastMessage('error')).toMatch(
/The 'max' cardinality attribute in AddElementRule/s
);
});
it('should log an error for extra docs/strings', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 MS boolean "is it valid?"
* stuff 0..* string "just stuff" "a list of some stuff" "invalid additional string"
* address 1..* N Address "current addresses" "at least one address is required"
* person 0..1 D TU Reference(Patient) "an associated patient" "added for TRIAL USE"
`);
const result = importSingleText(input, 'BadDocs.fsh)');
const resource = result.resources.get('TestResource');
expect(loggerSpy.getLastMessage('error')).toMatch(
/extraneous input.*File: BadDocs\.fsh.*Line: 4\D*/s
);
// Error results in excluding the following rules, hence length of 2 rather than 4
expect(resource.rules).toHaveLength(2);
});
it('should log an error for missing short', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 boolean
* stuff 0..* string "short string"
* address 1..* Address "short Address"
* person 0..1 Reference(Patient) "short Reference"
`);
const result = importSingleText(input, 'BadDefs.fsh');
const resource = result.resources.get('TestResource');
expect(loggerSpy.getLastMessage('error')).toMatch(
/The 'short' attribute in AddElementRule for path 'isValid' must be specified.*File: BadDefs\.fsh.*Line: 3\D*/s
);
// Error results in element not having defs defined
expect(resource.rules).toHaveLength(4);
assertAddElementRule(resource.rules[0], 'isValid', {
card: { min: 1, max: '1' },
types: [{ type: 'boolean' }]
});
});
it('should log an error for missing targetType with docs', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 boolean "is it valid?"
* stuff 0..* string "just stuff" "a list of some stuff"
* address 1..* "current addresses" "at least one address is required"
* person 0..1 Reference(Patient) "an associated patient" "added for TRIAL USE"
`);
const result = importSingleText(input, 'BadType.fsh');
const resource = result.resources.get('TestResource');
expect(loggerSpy.getLastMessage('error')).toMatch(
/extraneous input.*File: BadType\.fsh.*Line: 5\D*/s
);
// Error results in excluding the following rules, hence length of 3 rather than 5
expect(resource.rules).toHaveLength(3);
});
it('should log a warning for missing targetType with flags and docs', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 MS ?! boolean "is it valid?"
* stuff 0..* MS SU string "just stuff" "a list of some stuff"
* address 1..* N TU "current addresses" "at least one address is required"
* person 0..1 D TU Reference(Patient) "an associated patient" "added for TRIAL USE"
`);
const result = importSingleText(input, 'BadType.fsh');
const resource = result.resources.get('TestResource');
expect(loggerSpy.getLastMessage('warn')).toMatch(
/appears to be a flag value.*File: BadType\.fsh.*Line: 5\D*/s
);
expect(resource.rules).toHaveLength(4);
assertAddElementRule(resource.rules[0], 'isValid', {
card: { min: 1, max: '1' },
flags: { mustSupport: true, modifier: true },
types: [{ type: 'boolean' }],
defs: { short: 'is it valid?' }
});
assertAddElementRule(resource.rules[1], 'stuff', {
card: { min: 0, max: '*' },
flags: { mustSupport: true, summary: true },
types: [{ type: 'string' }],
defs: { short: 'just stuff', definition: 'a list of some stuff' }
});
assertAddElementRule(resource.rules[2], 'address', {
card: { min: 1, max: '*' },
flags: { normative: true },
types: [{ type: 'TU' }],
defs: { short: 'current addresses', definition: 'at least one address is required' }
});
assertAddElementRule(resource.rules[3], 'person', {
card: { min: 0, max: '1' },
flags: { trialUse: true, draft: true },
types: [{ type: 'Patient', isReference: true }],
defs: { short: 'an associated patient', definition: 'added for TRIAL USE' }
});
});
it('should log a error for missing targetType with modifier flag and docs', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 MS ?! boolean "is it valid?"
* stuff 0..* MS SU string "just stuff" "a list of some stuff"
* address 1..* N ?! "current addresses" "at least one address is required"
* person 0..1 D TU Reference(Patient) "an associated patient" "added for TRIAL USE"
`);
const result = importSingleText(input, 'BadType.fsh');
const resource = result.resources.get('TestResource');
expect(loggerSpy.getLastMessage('error')).toMatch(
/extraneous input.*File: BadType\.fsh.*Line: 5\D*/s
);
// The 'address' rule results in a CardRule and a FlagRule rather tha an AddElementRule.
// Due to the error, the 'person' rule is not processed.
expect(resource.rules).toHaveLength(4);
});
it('should parse rules according to rule patterns for CardRule and AddElementRule', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 boolean "is it valid?"
* stuff 0..* string "just stuff" "a list of some stuff"
* address 1..* "current addresses" "at least one address is required"
* person 0..1 Reference(Patient) "an associated patient"
`);
const result = importSingleText(input, 'BadType.fsh');
const resource = result.resources.get('TestResource');
expect(loggerSpy.getLastMessage('error')).toMatch(
/extraneous input.*File: BadType\.fsh.*Line: 5\D*/s
);
expect(resource.rules).toHaveLength(3);
assertAddElementRule(resource.rules[0], 'isValid', {
card: { min: 1, max: '1' },
types: [{ type: 'boolean' }]
});
assertAddElementRule(resource.rules[1], 'stuff', {
card: { min: 0, max: '*' },
types: [{ type: 'string' }]
});
// There is no way to distinguish between a valid CardRule
// and an invalid AddElementRule with a missing targetType,
// so the CardRule wins.
assertCardRule(resource.rules[2], 'address', 1, '*');
// Due to the error, the 'person' rule is not processed.
});
});
});
}); | the_stack |
import 'intl-pluralrules';
import '@formatjs/intl-relativetimeformat/polyfill-locales';
import IntlRelativeFormat, { IntlRelativeFormatOptions } from '../src';
import { expect as chaiExpect } from 'chai';
import { LocaleData, STYLE, SUPPORTED_FIELD } from '../src/types';
declare global {
var expect: typeof chaiExpect;
}
function past(v?: number) {
return Date.now() - (v || 0);
}
function future(v?: number) {
return Date.now() + (v || 0);
}
function early() {
return new Date().setHours(1);
}
function late() {
return new Date().setHours(23);
}
function expectNoNumberInOutput(output: string) {
expect(/\d+/.test(output)).to.be.false;
}
const isPolyfilledIntlRelativeTimeFormat =
'polyfilled' in Intl.RelativeTimeFormat;
describe('IntlRelativeFormat', function() {
it('should be a function', function() {
expect(IntlRelativeFormat).to.be.a('function');
});
it('should work w/o new', function() {
const rf = IntlRelativeFormat();
expect(rf.resolvedOptions().locale).to.equal('en-US');
});
// INSTANCE METHODS
describe('#resolvedOptions()', function() {
it('should be a function', function() {
var rf = new IntlRelativeFormat();
expect(rf.resolvedOptions).to.be.a('function');
});
it('should contain `locale`, `style`, and `units` properties', function() {
var rf = new IntlRelativeFormat();
expect(rf.resolvedOptions()).to.have.keys(['locale', 'style', 'units']);
});
describe('locale', function() {
var IRFLocaleData = IntlRelativeFormat.__localeData__;
var localeData: Record<string, LocaleData> = {};
// Helper to remove and replace the locale data available during the
// the different tests.
function transferLocaleData(
from: Record<string, LocaleData>,
to: Record<string, LocaleData>
) {
for (var locale in from) {
if (Object.prototype.hasOwnProperty.call(from, locale)) {
if (locale === IntlRelativeFormat.defaultLocale) {
continue;
}
to[locale] = from[locale];
delete from[locale];
}
}
}
beforeEach(function() {
transferLocaleData(IRFLocaleData, localeData);
});
afterEach(function() {
transferLocaleData(localeData, IRFLocaleData);
});
it('should default to default locale of Intl.RelativeTimeFormat', function() {
var rf = new IntlRelativeFormat();
expect(rf.resolvedOptions().locale).to.equal('en-US');
});
it('should normalize the casing', function() {
transferLocaleData(localeData, IRFLocaleData);
var rf = new IntlRelativeFormat('en-us');
expect(rf.resolvedOptions().locale).to.equal('en-US');
rf = new IntlRelativeFormat('EN-US');
expect(rf.resolvedOptions().locale).to.equal('en-US');
});
it('should be a fallback value when data is missing', function() {
var rf = new IntlRelativeFormat('fr-FR');
expect(rf.resolvedOptions().locale).to.equal(
isPolyfilledIntlRelativeTimeFormat ? 'fr' : 'fr-FR'
);
rf = new IntlRelativeFormat('foo');
expect(rf.resolvedOptions().locale).to.equal('en-US');
});
});
describe('style', function() {
it('should default to "best fit"', function() {
var resolvedOptions = new IntlRelativeFormat().resolvedOptions();
expect(resolvedOptions).to.have.property('style');
expect(resolvedOptions.style).to.equal('best fit');
});
it('should use relative units when "best fit"', function() {
var rf = new IntlRelativeFormat('en');
expectNoNumberInOutput(rf.format(Date.now()));
expectNoNumberInOutput(rf.format(past(24 * 60 * 60 * 1000)));
expectNoNumberInOutput(rf.format(past(30 * 24 * 60 * 60 * 1000)));
expectNoNumberInOutput(rf.format(future(24 * 60 * 60 * 1000)));
expectNoNumberInOutput(rf.format(future(30 * 24 * 60 * 60 * 1000)));
});
it('should always output a number when "numeric" is specified', function() {
var rf = new IntlRelativeFormat('en', { style: 'numeric' as STYLE });
function expectNumberInOutput(output: string) {
expect(/\d+/.test(output)).to.be.true;
}
expectNumberInOutput(rf.format(Date.now()));
expectNumberInOutput(rf.format(past(24 * 60 * 60 * 1000)));
expectNumberInOutput(rf.format(past(30 * 24 * 60 * 60 * 1000)));
expectNumberInOutput(rf.format(future(24 * 60 * 60 * 1000)));
expectNumberInOutput(rf.format(future(30 * 24 * 60 * 60 * 1000)));
});
});
describe('units', function() {
it('should default to `undefined`', function() {
var resolvedOptions = new IntlRelativeFormat().resolvedOptions();
expect(resolvedOptions).to.have.property('units');
expect(resolvedOptions.units).to.equal(undefined);
});
it('should always output in the specified units', function() {
var rf = new IntlRelativeFormat('en', {
units: 'day' as SUPPORTED_FIELD
});
expect(rf.format(Date.now())).to.equal('today');
expect(rf.format(past(24 * 60 * 60 * 1000))).to.equal('yesterday');
expect(rf.format(past(30 * 24 * 60 * 60 * 1000))).to.equal(
'30 days ago'
);
expect(rf.format(future(24 * 60 * 60 * 1000))).to.equal('tomorrow');
expect(rf.format(future(30 * 24 * 60 * 60 * 1000))).to.equal(
'in 30 days'
);
});
it('should always output in the specified units - morning', function() {
var rf = new IntlRelativeFormat('en', {
units: 'day' as SUPPORTED_FIELD
});
expect(rf.format(early(), { now: new Date().setHours(0) })).to.equal(
'today'
);
expect(rf.format(late(), { now: new Date().setHours(0) })).to.equal(
'today'
);
});
it('should always output in the specified units - evening', function() {
var rf = new IntlRelativeFormat('en', {
units: 'day' as SUPPORTED_FIELD
});
expect(rf.format(early(), { now: new Date().setHours(23) })).to.equal(
'today'
);
expect(rf.format(late(), { now: new Date().setHours(23) })).to.equal(
'today'
);
});
it('should handle short unit formats', function() {
var rf = new IntlRelativeFormat('en', {
units: 'minute-short' as SUPPORTED_FIELD
});
// Node 12 has an old version of CLDR that
// does not resolve correctly to `this minute
expect(rf.format(Date.now())).to.equal(
isPolyfilledIntlRelativeTimeFormat ? 'this minute' : 'in 0 min.'
);
expect(rf.format(past(24 * 60 * 60 * 1000))).to.equal('1,440 min. ago');
expect(rf.format(past(30 * 24 * 60 * 60 * 1000))).to.equal(
'43,200 min. ago'
);
expect(rf.format(future(24 * 60 * 60 * 1000))).to.equal(
'in 1,440 min.'
);
expect(rf.format(future(30 * 24 * 60 * 60 * 1000))).to.equal(
'in 43,200 min.'
);
});
it('should validate the specified units', function() {
function createInstance(options: IntlRelativeFormatOptions) {
return function() {
return new IntlRelativeFormat('en', options);
};
}
expect(createInstance({ units: 'bla' as any })).to.throw();
expect(createInstance({ units: 'hours' as any })).to.throw(
/did you mean: hour/
);
});
});
});
describe('#format( [object] )', function() {
var rf: typeof IntlRelativeFormat;
beforeEach(function() {
rf = new IntlRelativeFormat();
});
it('should be a function', function() {
expect(rf.format).to.be.a('function');
});
it('should throw on non-dates', function() {
expect(rf.format(Date.now())).to.be.a('string');
expect(rf.format(new Date())).to.be.a('string');
expect(function() {
return rf.format('foo');
}).to.throw();
});
it('should handle dates on and around the epoch', function() {
expect(rf.format(1)).to.be.a('string');
expect(rf.format(0)).to.be.a('string');
expect(rf.format(-1)).to.be.a('string');
});
describe('with "es" locale', function() {
var rf = new IntlRelativeFormat('es');
it('should return right now', function() {
var output = rf.format(past());
expect(output).to.equal('ahora');
});
it('should return 1 second past', function() {
var output = rf.format(past(1000));
expect(output).to.equal('hace 1 segundo');
});
it('should return 10 second past', function() {
var output = rf.format(past(10 * 1000));
expect(output).to.equal('hace 10 segundos');
});
it('should return 2 minutes past', function() {
var output = rf.format(past(2 * 60 * 1000));
expect(output).to.equal('hace 2 minutos');
});
it('should return 2 minutes future', function() {
var output = rf.format(future(2 * 60 * 1000));
expect(output).to.equal('dentro de 2 minutos');
});
it('should return 10 seconds future', function() {
var output = rf.format(future(10 * 1000));
expect(output).to.equal('dentro de 10 segundos');
});
it('should return 1 seconds future', function() {
var output = rf.format(future(1 * 1000));
expect(output).to.equal('dentro de 1 segundo');
});
it('should accept a custom value for now', function() {
var now = 1425839825400;
var output = rf.format(new Date(now - 60 * 1000), {
now: new Date(now)
});
expect(output).to.equal('hace 1 minuto');
});
});
describe('with "en" locale', function() {
var rf = new IntlRelativeFormat('en');
it('should return right now', function() {
var output = rf.format(past());
expect(output).to.equal('now');
});
it('should return 1 second past', function() {
var output = rf.format(past(1000));
expect(output).to.equal('1 second ago');
});
it('should return 10 second past', function() {
var output = rf.format(past(10 * 1000));
expect(output).to.equal('10 seconds ago');
});
it('should return 2 minutes past', function() {
var output = rf.format(past(2 * 60 * 1000));
expect(output).to.equal('2 minutes ago');
});
it('should return 1 hour past', function() {
var output = rf.format(past(60 * 60 * 1000));
expect(output).to.equal('1 hour ago');
});
it('should return 2 hours past', function() {
var output = rf.format(past(2 * 60 * 60 * 1000));
expect(output).to.equal('2 hours ago');
});
it('should return 1 day past', function() {
var output = rf.format(past(24 * 60 * 60 * 1000));
expect(output).to.equal('yesterday');
});
it('should return 2 days past', function() {
var output = rf.format(past(2 * 24 * 60 * 60 * 1000));
expect(output).to.equal('2 days ago');
});
it('should return 1 month past', function() {
var output = rf.format(past(30 * 24 * 60 * 60 * 1000));
expect(output).to.equal('last month');
});
it('should return 2 months past', function() {
var output = rf.format(past(2 * 30 * 24 * 60 * 60 * 1000));
expect(output).to.equal('2 months ago');
});
it('should return 1 year past', function() {
var output = rf.format(past(356 * 24 * 60 * 60 * 1000));
expect(output).to.equal('last year');
});
it('should return 2 years past', function() {
var output = rf.format(past(2 * 365 * 24 * 60 * 60 * 1000));
expect(output).to.equal('2 years ago');
});
it('should return 2 years future', function() {
var output = rf.format(future(2 * 365 * 24 * 60 * 60 * 1000));
expect(output).to.equal('in 2 years');
});
it('should return 1 year future', function() {
var output = rf.format(future(356 * 24 * 60 * 60 * 1000));
expect(output).to.equal('next year');
});
it('should return 2 months future', function() {
var output = rf.format(future(2 * 30 * 24 * 60 * 60 * 1000));
expect(output).to.equal('in 2 months');
});
it('should return 1 month future', function() {
var output = rf.format(future(30 * 24 * 60 * 60 * 1000));
expect(output).to.equal('next month');
});
it('should return 2 days future', function() {
var output = rf.format(future(2 * 24 * 60 * 60 * 1000));
expect(output).to.equal('in 2 days');
});
it('should return 1 day future', function() {
var output = rf.format(future(24 * 60 * 60 * 1000));
expect(output).to.equal('tomorrow');
});
it('should return 2 minutes future', function() {
var output = rf.format(future(2 * 60 * 1000));
expect(output).to.equal('in 2 minutes');
});
it('should return 10 seconds future', function() {
var output = rf.format(future(10 * 1000));
expect(output).to.equal('in 10 seconds');
});
it('should return 1 second future', function() {
var output = rf.format(future(1 * 1000));
expect(output).to.equal('in 1 second');
});
it('should accept a custom value for now', function() {
var now = 1425839825400;
var output = rf.format(new Date(now - 60 * 1000), {
now: new Date(now)
});
expect(output).to.equal('1 minute ago');
});
});
describe('with "zh" locale', function() {
var rf = new IntlRelativeFormat('zh');
it('should return right now', function() {
var output = rf.format(Date.now());
expect(output).to.equal('现在');
});
it('should return 1 second past', function() {
var output = rf.format(past(1000));
expect(output).to.equal('1秒钟前');
});
it('should return 10 seconds future', function() {
var output = rf.format(future(10 * 1000));
expect(output).to.equal('10秒钟后');
});
it('should return 3 minutes past', function() {
var output = rf.format(past(3 * 60 * 1000));
expect(output).to.equal('3分钟前');
});
it('should return 3 minutes future', function() {
var output = rf.format(future(3 * 60 * 1000));
expect(output).to.equal('3分钟后');
});
it('should return yesterday', function() {
var output = rf.format(past(1 * 24 * 60 * 60 * 1000));
expect(output).to.equal('昨天');
});
it('should return 2 days future', function() {
var output = rf.format(future(2 * 24 * 60 * 60 * 1000));
expect(output).to.equal('后天');
});
});
describe('with "zh-Hant-TW" locale', function() {
var rf = new IntlRelativeFormat('zh-Hant-TW');
it('should return right now', function() {
var output = rf.format(Date.now());
expect(output).to.equal('現在');
});
it('should return 1 second past', function() {
var output = rf.format(past(1000));
expect(output).to.equal('1 秒前');
});
it('should return 10 seconds future', function() {
var output = rf.format(future(10 * 1000));
expect(output).to.equal('10 秒後');
});
it('should return 3 minutes past', function() {
var output = rf.format(past(3 * 60 * 1000));
expect(output).to.equal('3 分鐘前');
});
it('should return 3 minutes future', function() {
var output = rf.format(future(3 * 60 * 1000));
expect(output).to.equal('3 分鐘後');
});
it('should return yesterday', function() {
var output = rf.format(past(1 * 24 * 60 * 60 * 1000));
expect(output).to.equal('昨天');
});
it('should return 2 days future', function() {
var output = rf.format(future(2 * 24 * 60 * 60 * 1000));
expect(output).to.equal('後天');
});
});
describe('with "zh-Hant-HK" locale', function() {
var rf = new IntlRelativeFormat('zh-Hant-HK');
it('should return right now', function() {
var output = rf.format(Date.now());
expect(output).to.equal('現在');
});
it('should return 1 second past', function() {
var output = rf.format(past(1000));
expect(output).to.equal('1 秒前');
});
it('should return 10 seconds future', function() {
var output = rf.format(future(10 * 1000));
expect(output).to.equal('10 秒後');
});
it('should return 3 minutes past', function() {
var output = rf.format(past(3 * 60 * 1000));
expect(output).to.equal('3 分鐘前');
});
it('should return 3 minutes future', function() {
var output = rf.format(future(3 * 60 * 1000));
expect(output).to.equal('3 分鐘後');
});
it('should return yesterday', function() {
var output = rf.format(past(1 * 24 * 60 * 60 * 1000));
expect(output).to.equal('昨日');
});
it('should return 2 days future', function() {
var output = rf.format(future(2 * 24 * 60 * 60 * 1000));
expect(output).to.equal('後日');
});
});
describe('with `now` option', function() {
var rf = new IntlRelativeFormat('en');
it('should accept the epoch value', function() {
var output = rf.format(new Date(60000), { now: 0 });
expect(output).to.equal('in 1 minute');
});
it('should use the real value of now when undefined', function() {
var output = rf.format(past(2 * 60 * 1000), { now: undefined });
expect(output).to.equal('2 minutes ago');
});
it('should throw on non-finite values', function() {
expect(function() {
rf.format(past(2 * 60 * 1000), { now: Infinity });
}).to.throw();
});
it('should treat null like the epoch', function() {
var output = rf.format(new Date(120000), { now: null });
expect(output).to.equal('in 2 minutes');
});
});
});
// INTERNAL FORMAT DELEGATION
// TODO: Rewrite this test
// describe('internal format delegation', function () {
// it('should delegate the original `locales` value to internal formats', function () {
// // NOTE: This entire test case is a huge, huge hack to get at the
// // internals of IntlRelativeFormat, IntlMessageFormat, to finally
// // grab ahold of an Intl.NumberFormat instance to check its resolved
// // locale.
// var expected = new Intl.NumberFormat('en-GB').resolvedOptions();
// var rf = new IntlRelativeFormat('en-GB');
// var internalMF = rf._compileMessage('second' as SUPPORTED_FIELD);
// function checkInternalMessagePattern(pattern: any) {
// var subPattern = pattern[0].options.future[0].options.other[0];
// var resolved = subPattern.numberFormat.resolvedOptions();
// expect(resolved.locale).to.equal(expected.locale);
// }
// // Override private method, which will expose the internal Message
// // Format pattern that we can traverse and check that its internal
// // Intl.NumberFormat pattern resolved the correct locale that was
// // originally passed to the IntlRelativeFormat instance.
// internalMF._format = checkInternalMessagePattern;
// internalMF.format({});
// });
// });
}); | the_stack |
declare module 'util' {
import * as types from 'util/types';
export interface InspectOptions extends NodeJS.InspectOptions { }
export type Style = 'special' | 'number' | 'bigint' | 'boolean' | 'undefined' | 'null' | 'string' | 'symbol' | 'date' | 'regexp' | 'module';
export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => string;
export interface InspectOptionsStylized extends InspectOptions {
stylize(text: string, styleType: Style): string;
}
export function format(format?: any, ...param: any[]): string;
export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string;
/** @deprecated since v0.11.3 - use a third party module instead. */
export function log(string: string): void;
export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string;
export function inspect(object: any, options: InspectOptions): string;
export namespace inspect {
let colors: NodeJS.Dict<[number, number]>;
let styles: {
[K in Style]: string
};
let defaultOptions: InspectOptions;
/**
* Allows changing inspect settings from the repl.
*/
let replDefaults: InspectOptions;
const custom: unique symbol;
}
/** @deprecated since v4.0.0 - use `Array.isArray()` instead. */
export function isArray(object: any): object is any[];
/** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */
export function isRegExp(object: any): object is RegExp;
/** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */
export function isDate(object: any): object is Date;
/** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */
export function isError(object: any): object is Error;
export function inherits(constructor: any, superConstructor: any): void;
export function debuglog(key: string): (msg: string, ...param: any[]) => void;
/** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */
export function isBoolean(object: any): object is boolean;
/** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */
export function isBuffer(object: any): object is Buffer;
/** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */
export function isFunction(object: any): boolean;
/** @deprecated since v4.0.0 - use `value === null` instead. */
export function isNull(object: any): object is null;
/** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */
export function isNullOrUndefined(object: any): object is null | undefined;
/** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */
export function isNumber(object: any): object is number;
/** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */
export function isObject(object: any): boolean;
/** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */
export function isPrimitive(object: any): boolean;
/** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */
export function isString(object: any): object is string;
/** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */
export function isSymbol(object: any): object is symbol;
/** @deprecated since v4.0.0 - use `value === undefined` instead. */
export function isUndefined(object: any): object is undefined;
export function deprecate<T extends Function>(fn: T, message: string, code?: string): T;
export function isDeepStrictEqual(val1: any, val2: any): boolean;
export function callbackify(fn: () => Promise<void>): (callback: (err: NodeJS.ErrnoException) => void) => void;
export function callbackify<TResult>(fn: () => Promise<TResult>): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void;
export function callbackify<T1>(fn: (arg1: T1) => Promise<void>): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void;
export function callbackify<T1, TResult>(fn: (arg1: T1) => Promise<TResult>): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void;
export function callbackify<T1, T2>(fn: (arg1: T1, arg2: T2) => Promise<void>): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void;
export function callbackify<T1, T2, TResult>(fn: (arg1: T1, arg2: T2) => Promise<TResult>): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void;
export function callbackify<T1, T2, T3>(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void;
export function callbackify<T1, T2, T3, TResult>(
fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void;
export function callbackify<T1, T2, T3, T4>(
fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void;
export function callbackify<T1, T2, T3, T4, TResult>(
fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void;
export function callbackify<T1, T2, T3, T4, T5>(
fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void;
export function callbackify<T1, T2, T3, T4, T5, TResult>(
fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>,
): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void;
export function callbackify<T1, T2, T3, T4, T5, T6>(
fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<void>,
): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void;
export function callbackify<T1, T2, T3, T4, T5, T6, TResult>(
fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<TResult>
): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void;
export interface CustomPromisifyLegacy<TCustom extends Function> extends Function {
__promisify__: TCustom;
}
export interface CustomPromisifySymbol<TCustom extends Function> extends Function {
[promisify.custom]: TCustom;
}
export type CustomPromisify<TCustom extends Function> = CustomPromisifySymbol<TCustom> | CustomPromisifyLegacy<TCustom>;
export function promisify<TCustom extends Function>(fn: CustomPromisify<TCustom>): TCustom;
export function promisify<TResult>(fn: (callback: (err: any, result: TResult) => void) => void): () => Promise<TResult>;
export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise<void>;
export function promisify<T1, TResult>(fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void): (arg1: T1) => Promise<TResult>;
export function promisify<T1>(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise<void>;
export function promisify<T1, T2, TResult>(fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise<TResult>;
export function promisify<T1, T2>(fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2) => Promise<void>;
export function promisify<T1, T2, T3, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void):
(arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>;
export function promisify<T1, T2, T3>(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise<void>;
export function promisify<T1, T2, T3, T4, TResult>(
fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void,
): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>;
export function promisify<T1, T2, T3, T4>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void):
(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>;
export function promisify<T1, T2, T3, T4, T5, TResult>(
fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void,
): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>;
export function promisify<T1, T2, T3, T4, T5>(
fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void,
): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>;
export function promisify(fn: Function): Function;
export namespace promisify {
const custom: unique symbol;
}
export class TextDecoder {
readonly encoding: string;
readonly fatal: boolean;
readonly ignoreBOM: boolean;
constructor(
encoding?: string,
options?: { fatal?: boolean; ignoreBOM?: boolean }
);
decode(
input?: NodeJS.ArrayBufferView | ArrayBuffer | null,
options?: { stream?: boolean }
): string;
}
export interface EncodeIntoResult {
/**
* The read Unicode code units of input.
*/
read: number;
/**
* The written UTF-8 bytes of output.
*/
written: number;
}
export { types };
export class TextEncoder {
readonly encoding: string;
encode(input?: string): Uint8Array;
encodeInto(input: string, output: Uint8Array): EncodeIntoResult;
}
} | the_stack |
import { Component } from 'vue-property-decorator';
import _ from 'lodash';
import $ from 'jquery';
import L, { Map as LeafletMap, LeafletEvent, LeafletMouseEvent, Circle } from 'leaflet';
import template from './map.html';
import ColumnSelect from '@/components/column-select/column-select';
import {
Visualization,
injectVisualizationTemplate,
drawBrushBox,
multiplyVisuals,
getBrushBox,
isPointInBox,
} from '@/components/visualization';
import { VisualProperties } from '@/data/visuals';
import { SELECTED_COLOR } from '@/common/constants';
import { isNumericalType } from '@/data/util';
import * as history from './history';
import { showSystemMessage } from '@/common/util';
import { ValueType } from '@/data/parser';
const MAP_ATTRIBUTION = `<a href="http://mapbox.com" target="_blank">© Mapbox</a> |
<a href="http://openstreetmap.org" target="_blank">© OpenStreetMap</a> |
<a href="https://www.mapbox.com/map-feedback/#" target="_blank">Improve this map</a>`;
// Mapbox public access token.
const MAP_ACCESS_TOKEN = 'pk.eyJ1IjoieXVib3dlbm9rIiwiYSI6ImNqMGJlMjU0dDAzNmozMm12aHEwbjZ4MDAifQ.sh8WWNXW5eaeWSxkJNZ4TQ';
const LEAFLET_LIGHT_URL = 'https://api.mapbox.com/styles/v1/mapbox/light-v9/tiles/256/{z}/{x}/{y}?access_token=';
const LEAFLET_DARK_URL = 'https://api.mapbox.com/styles/v1/mapbox/dark-v9/tiles/256/{z}/{x}/{y}?access_token=';
const LEAFLET_STREETS_URL = 'https://api.mapbox.com/styles/v1/mapbox/streets-v10/tiles/256/{z}/{x}/{y}?access_token=';
const ZOOM_EXTENT = [1, 18];
const DEFAULT_ZOOM_LEVEL = 12;
const DEFAULT_CENTER: [number, number] = [40.729, -73.988]; // Around NYC
const DEFAULT_ITEM_VISUALS: VisualProperties = {
color: '#333',
border: undefined,
width: 1.5,
size: 50,
opacity: 1,
};
const SELECTED_ITEM_VISUALS: VisualProperties = {
color: 'white',
border: SELECTED_COLOR,
};
interface MapSave {
latitudeColumn: number | null;
longitudeColumn: number | null;
isNavigating: boolean;
center: [number, number]; // map center
zoom: number; // map zoom level
}
interface MapItemProps {
index: number;
lat: number;
lon: number;
visuals: VisualProperties;
hasVisuals: boolean;
selected: boolean;
}
@Component({
template: injectVisualizationTemplate(template),
components: {
ColumnSelect,
},
})
export default class Map extends Visualization {
protected NODE_TYPE = 'map';
private latitudeColumn: number | null = null;
private longitudeColumn: number | null = null;
private isNavigating = true;
private zoom = DEFAULT_ZOOM_LEVEL;
private center: [number, number] = DEFAULT_CENTER;
private map: LeafletMap | null = null;
private itemProps: MapItemProps[] = [];
private circles: { [index: number]: Circle } = {};
private isMapCreated = false;
public onKeys(keys: string): boolean {
if (keys === 'n') {
this.toggleNavigating();
return true;
}
return this.onKeysVisualization(keys);
}
public setLatitudeColumn(column: number) {
if (!this.isValidColumn(column)) {
return;
}
this.latitudeColumn = column;
this.draw();
}
public setLongitudeColumn(column: number) {
if (!this.isValidColumn(column)) {
return;
}
this.longitudeColumn = column;
this.draw();
}
public applyColumns(columns: number[]) {
if (columns.length !== 2) {
showSystemMessage(this.$store, 'a map visualization needs latitude and longitude columns', 'warn');
return;
}
[this.latitudeColumn, this.longitudeColumn] = columns;
if (this.hasDataset()) {
this.draw();
}
}
public setNavigating(value: boolean) {
this.isNavigating = value;
}
/**
* Finds two numerical columns, preferrably with "lat" and "lon" text in names as latitude and longitude columns.
*/
protected findDefaultColumns() {
if (!this.hasDataset()) {
return;
}
const dataset = this.getDataset();
dataset.getColumns().forEach(column => {
if (isNumericalType(column.type)) {
if (column.name.match(/lat/i) !== null) {
this.latitudeColumn = column.index;
}
if (column.name.match(/lon/i) !== null) {
this.longitudeColumn = column.index;
}
}
});
}
protected created() {
this.serializationChain.push((): MapSave => ({
isNavigating: this.isNavigating,
latitudeColumn: this.latitudeColumn,
longitudeColumn: this.longitudeColumn,
center: this.center,
zoom: this.zoom,
}));
}
protected draw() {
if (this.latitudeColumn === null || this.longitudeColumn === null) {
this.coverText = 'Please select latitude/longitude columns';
return;
}
this.coverText = '';
if (!this.isMapCreated) {
this.isMapCreated = true;
this.createMap();
}
this.computeItemProps();
this.drawMap();
}
protected onResize() {
if (!this.hasNoDataset() && !this.isAnimating && this.isExpanded) {
if (this.map) {
// Leaflet map may not get correct view size upon node creation. Everytime we resize we must invalidate its
// previous size otherwise only one tile will be rendered.
this.map.invalidateSize();
}
}
}
protected isDraggable(evt: MouseEvent, ui?: JQueryUI.DraggableEventUIParams) {
if (this.isContentVisible && this.isNavigating) {
return false; // If the map is in navigation mode, then node drag is disabled.
}
return this.isDraggableBase(evt);
}
protected isBrushable(): boolean {
return !this.isNavigating;
}
protected brushed(brushPoints: Point[], isBrushStop?: boolean) {
if (isBrushStop) {
this.computeBrushedItems(brushPoints);
this.computeSelection();
this.computeItemProps();
this.drawMap();
this.propagateSelection();
}
drawBrushBox(this.$refs.brush as SVGElement, !isBrushStop ? brushPoints : []);
}
private computeBrushedItems(brushPoints: Point[]) {
if (!this.isShiftPressed || !brushPoints.length) {
this.selection.clear(); // reset selection if shift key is not down
if (!brushPoints.length) {
return;
}
}
const box = getBrushBox(brushPoints);
this.itemProps.forEach(props => {
const point = (this.map as LeafletMap).latLngToContainerPoint([props.lat, props.lon]);
if (isPointInBox(point, box)) {
this.selection.addItem(props.index);
}
});
}
private computeItemProps() {
const dataset = this.getDataset();
const pkg = this.inputPortMap.in.getSubsetPackage();
// Clear the circles that are no longer in the input.
_.each(this.circles, (circle: Circle, itemIndex: string) => {
if (!pkg.hasItem(+itemIndex)) {
circle.removeFrom(this.map as LeafletMap);
delete this.circles[+itemIndex];
}
});
this.itemProps = pkg.getItems().map(item => {
const props: MapItemProps = {
index: item.index,
lat: dataset.getCellForScale(item.index, this.latitudeColumn as number) as number,
lon: dataset.getCellForScale(item.index, this.longitudeColumn as number) as number,
visuals: _.extend({}, DEFAULT_ITEM_VISUALS, item.visuals),
hasVisuals: !_.isEmpty(item.visuals),
selected: this.selection.hasItem(item.index),
};
if (props.selected) {
_.extend(props.visuals, SELECTED_ITEM_VISUALS);
multiplyVisuals(props.visuals);
}
return props;
});
}
private drawMap() {
this.drawPoints();
}
private drawPoints() {
const map = this.map as LeafletMap;
const radiusRatio = Math.pow(2, DEFAULT_ZOOM_LEVEL - map.getZoom());
this.itemProps.forEach(props => {
if (!(props.index in this.circles)) {
this.circles[props.index] = L.circle([0, 0]).addTo(map);
}
const circle = this.circles[props.index];
circle.setLatLng([props.lat, props.lon]);
circle.setRadius((props.visuals.size as number) * radiusRatio);
circle.setStyle({
color: props.visuals.border,
weight: props.visuals.width,
fillColor: props.visuals.color,
opacity: props.visuals.opacity,
});
});
}
private createMap() {
const tileOptions = {
minZoom: ZOOM_EXTENT[0],
maxZoom: ZOOM_EXTENT[1],
accessToken: MAP_ACCESS_TOKEN,
attribution: MAP_ATTRIBUTION,
};
const light = L.tileLayer(LEAFLET_LIGHT_URL + MAP_ACCESS_TOKEN, tileOptions);
const dark = L.tileLayer(LEAFLET_DARK_URL + MAP_ACCESS_TOKEN, tileOptions);
const streets = L.tileLayer(LEAFLET_STREETS_URL + MAP_ACCESS_TOKEN, tileOptions);
this.map = L.map(this.$refs.map as HTMLElement, {
layers: [light, dark, streets],
}).setView(this.center, this.zoom);
// @types/leaflet does not know about attribution
// tslint:disable-next-line
(this.map as any).attributionControl.setPrefix('');
const baseMaps = {
gray: light,
dark,
color: streets,
};
L.control.layers(baseMaps).addTo(this.map);
// Use light layer by default
$(this.$refs.map).find('.leaflet-control-layers-base input').first().click();
this.map
.on('mousedown', (evt: LeafletEvent) => this.onMapMousedown((evt as LeafletMouseEvent).originalEvent))
.on('mouseup', (evt: LeafletEvent) => this.onMapMouseup((evt as LeafletMouseEvent).originalEvent))
.on('zoomend', () => {
this.drawMap();
this.zoom = (this.map as LeafletMap).getZoom();
const center = (this.map as LeafletMap).getCenter();
this.center = [center.lat, center.lng];
})
.on('zoomlevelchange', this.drawMap);
// Invalidates map size after reactive Vue properties are final.
this.$nextTick(() => (this.map as LeafletMap).invalidateSize());
}
private onMapMousedown(evt: MouseEvent) {
if (!this.isNavigating && this.map) {
this.map.dragging.disable();
this.map.scrollWheelZoom.disable();
this.map.boxZoom.disable();
}
}
private onMapMouseup(evt: MouseEvent) {
if (!this.isNavigating && this.map) {
this.map.dragging.enable();
this.map.scrollWheelZoom.enable();
this.map.boxZoom.enable();
}
}
private toggleNavigating() {
this.isNavigating = !this.isNavigating;
}
private onSelectLatitudeColumn(column: number, prevColumn: number | null) {
this.commitHistory(history.selectLatitudeColumnEvent(this, column, prevColumn));
this.setLatitudeColumn(column);
}
private onSelectLongitudeColumn(column: number, prevColumn: number | null) {
this.commitHistory(history.selectLongitudeColumnEvent(this, column, prevColumn));
this.setLongitudeColumn(column);
}
private onToggleNavigating(value: boolean) {
this.commitHistory(history.toggleNavigatingEvent(this, value));
}
private isValidColumn(column: number): boolean {
if (!this.dataset) {
return true;
}
const columnType = this.dataset.getColumnType(column);
if (!isNumericalType(columnType)) {
showSystemMessage(this.$store, `column ${this.dataset.getColumnName(column)} is not a numerical column`, 'warn');
return false;
}
return true;
}
} | the_stack |
import type { DataItem } from "../../core/render/Component";
import { VennDefaultTheme } from "./VennDefaultTheme";
import { Series, ISeriesSettings, ISeriesDataItem, ISeriesPrivate } from "../../core/render/Series";
import { Template } from "../../core/util/Template";
import { Graphics, visualSettings } from "../../core/render/Graphics";
import { Container } from "../../core/render/Container";
import { Label } from "../../core/render/Label";
import { ListTemplate } from "../../core/util/List";
import type { ILegendDataItem } from "../../core/render/Legend";
import type { Color } from "../../core/util/Color";
import type { ColorSet } from "../../core/util/ColorSet";
import * as $utils from "../../core/util/Utils";
import * as $array from "../../core/util/Array";
import * as $type from "../../core/util/Type";
import * as venn from "./vennjs/index.js";
export interface IVennDataItem extends ISeriesDataItem {
/**
* Array of categories that this data item is an intersection for.
*/
intersections: Array<string>;
/**
* Category.
*/
category: string;
/**
* Slice visaul element.
*/
slice: Graphics;
/**
* Slice label.
*/
label: Label;
/**
* A related legend data item.
*/
legendDataItem: DataItem<ILegendDataItem>;
/**
* Fill color used for the slice and related elements, e.g. legend marker.
*/
fill: Color;
}
export interface IVennSettings extends ISeriesSettings {
/**
* A field in data that holds array of categories that overlap.
*/
intersectionsField?: string;
/**
* A [[ColorSet]] to use when asigning colors for slices.
*/
colors?: ColorSet;
/**
* A field in data that holds category names.
*/
categoryField?: string;
/**
* A field that holds color for slice fill.
*/
fillField?: string;
}
export interface IVennPrivate extends ISeriesPrivate {
}
/**
* Creates a Venn diagram.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/venn/} for more info
* @important
*/
export class Venn extends Series {
public static className: string = "Venn";
public static classNames: Array<string> = Series.classNames.concat([Venn.className]);
declare public _settings: IVennSettings;
declare public _privateSettings: IVennPrivate;
declare public _dataItemSettings: IVennDataItem;
protected _sets: string = "";
/**
* A [[Container]] that holds all slices (circles and intersections).
*
* @default Container.new()
*/
public readonly slicesContainer = this.children.push(Container.new(this._root, {}));
/**
* A [[Container]] that holds all labels.
*
* @default Container.new()
*/
public readonly labelsContainer = this.children.push(Container.new(this._root, {}));
/**
* A [[Graphics]] element that is used to show the shape of the hovered slice
* or intersection.
*
* @default Graphics.new()
*/
public readonly hoverGraphics = this.slicesContainer.children.push(Graphics.new(this._root, { position: "absolute", isMeasured: false }))
protected _hovered?: Graphics;
protected _afterNew() {
this._defaultThemes.push(VennDefaultTheme.new(this._root));
this.fields.push("intersections", "category", "fill");
super._afterNew();
}
/**
* A [[ListTemplate]] of all slices in series.
*
* `slices.template` can also be used to configure slices.
*/
public readonly slices: ListTemplate<Graphics> = this._makeSlices();
/**
* @ignore
*/
public makeSlice(dataItem: DataItem<this["_dataItemSettings"]>): Graphics {
const slice = this.slicesContainer.children.push(this.slices.make());
slice.events.on("pointerover", (e) => {
this._hovered = e.target;
this._updateHover();
})
slice.events.on("pointerout", () => {
this._hovered = undefined;
this.hoverGraphics.hide();
})
slice.on("fill", () => {
this.updateLegendMarker(dataItem);
})
slice.on("stroke", () => {
this.updateLegendMarker(dataItem);
})
slice._setDataItem(dataItem);
dataItem.set("slice", slice);
this.slices.push(slice);
return slice;
}
protected _updateHover() {
if (this._hovered) {
const hoverGraphics = this.hoverGraphics;
hoverGraphics.set("svgPath", this._hovered.get("svgPath"));
hoverGraphics.show();
hoverGraphics.toFront();
}
}
/**
* A [[ListTemplate]] of all slice labels in series.
*
* `labels.template` can also be used to configure slice labels.
*/
public readonly labels: ListTemplate<Label> = this._makeLabels();
/**
* @ignore
*/
public makeLabel(dataItem: DataItem<this["_dataItemSettings"]>): Label {
const label = this.labelsContainer.children.push(this.labels.make());
label._setDataItem(dataItem);
dataItem.set("label", label);
this.labels.push(label);
return label;
}
protected _makeSlices(): ListTemplate<Graphics> {
return new ListTemplate(
Template.new({}),
() => Graphics._new(this._root, {
themeTags: $utils.mergeTags(this.slices.template.get("themeTags", []), ["venn", "series"])
}, [this.slices.template]),
);
}
protected _makeLabels(): ListTemplate<Label> {
return new ListTemplate(
Template.new({}),
() => Label._new(this._root, {
themeTags: $utils.mergeTags(this.labels.template.get("themeTags", []), ["venn", "series"])
}, [this.labels.template]),
);
}
protected processDataItem(dataItem: DataItem<this["_dataItemSettings"]>) {
super.processDataItem(dataItem);
if (dataItem.get("fill") == null) {
let colors = this.get("colors");
if (colors) {
dataItem.setRaw("fill", colors.next());
}
}
this.makeSlice(dataItem);
this.makeLabel(dataItem);
}
public _prepareChildren() {
super._prepareChildren();
if (this._valuesDirty || this._sizeDirty) {
const sets: any[] = [];
// prepare data for venn
$array.each(this.dataItems, (dataItem) => {
const set: any = {};
const intersections = dataItem.get("intersections");
if (intersections) {
set.sets = intersections;
}
else {
set.sets = [dataItem.get("category")];
}
set.size = dataItem.get("valueWorking");
if (set.size > 0) {
sets.push(set);
}
})
const newSets = sets.toString();
this._sets = newSets;
if (sets.length > 0) {
let vennData = venn.venn(sets);
vennData = venn.normalizeSolution(vennData, null, null);
vennData = venn.scaleSolution(vennData, this.innerWidth(), this.innerHeight(), 0);
const circles: any = {};
for (let name in vennData) {
let item = vennData[name];
let r = item.radius;
const dataItem = this.getDataItemByCategory(name);
if (dataItem) {
const slice = dataItem.get("slice");
const color = dataItem.get("fill");
slice._setDefault("fill", color);
slice._setDefault("stroke", color);
this.updateLegendMarker(dataItem);
slice.set("svgPath", "M" + item.x + "," + item.y + " m -" + r + ", 0 a " + r + "," + r + " 0 1,1 " + r * 2 + ",0 a " + r + "," + r + " 0 1,1 -" + r * 2 + ",0");
circles[name] = item;
}
}
let centers: any = venn.computeTextCentres(circles, sets);
$array.each(this.dataItems, (dataItem) => {
let name = dataItem.get("category");
let center = centers[name];
const intersections = dataItem.get("intersections");
if (intersections) {
name = intersections.toString();
center = centers[name];
if (center) {
let set = intersections;
let cc = [];
for (let s = 0; s < set.length; s++) {
cc.push(circles[set[s]]);
}
let intersectionPath = venn.intersectionAreaPath(cc)
let slice = dataItem.get("slice");
const color = dataItem.get("fill");
slice._setDefault("fill", color);
slice._setDefault("stroke", color);
slice.setAll({ svgPath: intersectionPath });
}
}
if (center) {
let label = dataItem.get("label");
label.setAll({ x: center.x, y: center.y });
}
this.updateLegendValue(dataItem);
})
}
this._updateHover();
}
}
/**
* Looks up and returns a data item by its category.
*
* @param category Category
* @return Data item
*/
public getDataItemByCategory(id: string): DataItem<this["_dataItemSettings"]> | undefined {
return $array.find(this.dataItems, (dataItem: any) => {
return dataItem.get("category") == id;
})
}
/**
* Shows series's data item.
*
* @param dataItem Data item
* @param duration Animation duration in milliseconds
* @return Promise
*/
public async showDataItem(dataItem: DataItem<this["_dataItemSettings"]>, duration?: number): Promise<void> {
const promises = [super.showDataItem(dataItem, duration)];
if (!$type.isNumber(duration)) {
duration = this.get("stateAnimationDuration", 0);
}
const easing = this.get("stateAnimationEasing");
let value = dataItem.get("value");
const animation = dataItem.animate({ key: "valueWorking", to: value, duration: duration, easing: easing });
if (animation) {
promises.push(animation.waitForStop());
}
const label = dataItem.get("label");
if (label) {
promises.push(label.show(duration));
}
const slice = dataItem.get("slice");
if (slice) {
promises.push(slice.show(duration));
}
const intersections = dataItem.get("intersections");
if (intersections) {
$array.each(intersections, (cat) => {
const di = this.getDataItemByCategory(cat);
if (di && di.isHidden()) {
this.showDataItem(di, duration);
}
})
}
if (!intersections) {
const category = dataItem.get("category");
$array.each(this.dataItems, (di) => {
const intersections = di.get("intersections");
if (di != dataItem && intersections) {
let allVisible = true;
$array.each(intersections, (cat) => {
const dii = this.getDataItemByCategory(cat);
if (dii && dii.isHidden()) {
allVisible = false;
}
})
if (allVisible && intersections.indexOf(category) != -1) {
if (di.isHidden()) {
this.showDataItem(di, duration);
}
}
}
})
}
await Promise.all(promises);
}
/**
* Hides series's data item.
*
* @param dataItem Data item
* @param duration Animation duration in milliseconds
* @return Promise
*/
public async hideDataItem(dataItem: DataItem<this["_dataItemSettings"]>, duration?: number): Promise<void> {
const promises = [super.hideDataItem(dataItem, duration)];
const hiddenState = this.states.create("hidden", {})
if (!$type.isNumber(duration)) {
duration = hiddenState.get("stateAnimationDuration", this.get("stateAnimationDuration", 0));
}
const easing = hiddenState.get("stateAnimationEasing", this.get("stateAnimationEasing"));
const animation = dataItem.animate({ key: "valueWorking", to: 0, duration: duration, easing: easing });
if (animation) {
promises.push(animation.waitForStop());
}
const label = dataItem.get("label");
if (label) {
promises.push(label.hide(duration));
}
const slice = dataItem.get("slice");
if (slice) {
promises.push(slice.hide(duration));
slice.hideTooltip();
}
if (!dataItem.get("intersections")) {
$array.each(this.dataItems, (di) => {
const intersections = di.get("intersections");
if (di != dataItem && intersections) {
if (intersections.indexOf(dataItem.get("category")) != -1) {
this.hideDataItem(di, duration);
}
}
})
}
await Promise.all(promises);
}
/**
* @ignore
*/
public disposeDataItem(dataItem: DataItem<this["_dataItemSettings"]>) {
super.disposeDataItem(dataItem);
let label = dataItem.get("label");
if (label) {
this.labels.removeValue(label);
label.dispose();
}
let slice = dataItem.get("slice");
if (slice) {
this.slices.removeValue(slice);
slice.dispose();
}
}
/**
* @ignore
*/
public updateLegendMarker(dataItem: DataItem<this["_dataItemSettings"]>) {
const slice = dataItem.get("slice");
if (slice) {
const legendDataItem = dataItem.get("legendDataItem");
if (legendDataItem) {
const markerRectangle = legendDataItem.get("markerRectangle");
$array.each(visualSettings, (setting: any) => {
markerRectangle.set(setting, slice.get(setting));
})
}
}
}
/**
* Triggers hover on a series data item.
*
* @since 5.0.7
* @param dataItem Target data item
*/
public hoverDataItem(dataItem: DataItem<this["_dataItemSettings"]>) {
const slice = dataItem.get("slice");
if (slice && !slice.isHidden()) {
slice.hover();
}
}
/**
* Triggers un-hover on a series data item.
*
* @since 5.0.7
* @param dataItem Target data item
*/
public unhoverDataItem(dataItem: DataItem<this["_dataItemSettings"]>) {
const slice = dataItem.get("slice");
if (slice) {
slice.unhover();
}
}
} | the_stack |
import { Rule, Diagnostic } from "@siteimprove/alfa-act";
import { Cache } from "@siteimprove/alfa-cache";
import { Color } from "@siteimprove/alfa-css";
import { Device } from "@siteimprove/alfa-device";
import { Element, Node, Text } from "@siteimprove/alfa-dom";
import { Equatable } from "@siteimprove/alfa-equatable";
import { Hash, Hashable } from "@siteimprove/alfa-hash";
import { Serializable } from "@siteimprove/alfa-json";
import { Map } from "@siteimprove/alfa-map";
import { Option, None } from "@siteimprove/alfa-option";
import { Predicate } from "@siteimprove/alfa-predicate";
import { Refinement } from "@siteimprove/alfa-refinement";
import { Err, Ok, Result } from "@siteimprove/alfa-result";
import { Context } from "@siteimprove/alfa-selector";
import { Sequence } from "@siteimprove/alfa-sequence";
import { Set } from "@siteimprove/alfa-set";
import { Property, Style } from "@siteimprove/alfa-style";
import { Criterion } from "@siteimprove/alfa-wcag";
import { Page } from "@siteimprove/alfa-web";
import * as json from "@siteimprove/alfa-json";
import { expectation } from "../common/expectation";
import {
hasBorder,
hasComputedStyle,
hasOutline,
hasRole,
hasTextDecoration,
isVisible,
} from "../common/predicate";
import { Serialise } from "./serialise";
const { isElement } = Element;
const { isText } = Text;
const { or, not, test } = Predicate;
const { and } = Refinement;
export default Rule.Atomic.of<Page, Element>({
uri: "https://alfa.siteimprove.com/rules/sia-r62",
requirements: [Criterion.of("1.4.1")],
evaluate({ device, document }) {
let containers: Map<Element, Element> = Map.empty();
return {
applicability() {
return visit(document, None);
function* visit(
node: Node,
container: Option<Element>
): Iterable<Element> {
if (isElement(node)) {
// If the element is a semantic link, it might be applicable.
if (
test(
hasRole(device, (role) => role.is("link")),
node
)
) {
if (
container.isSome() &&
node
.descendants({ flattened: true })
.some(and(isText, isVisible(device)))
) {
containers = containers.set(node, container.get());
return yield node;
}
}
// Otherwise, if the element is a <p> element with non-link text
// content then start collecting applicable elements.
else if (
test(
and(hasRole(device, "paragraph"), hasNonLinkText(device)),
node
)
) {
container = Option.of(node);
}
}
const children = node.children({
flattened: true,
nested: true,
});
for (const child of children) {
yield* visit(child, container);
}
}
},
expectations(target) {
const nonLinkElements = containers
.get(target)
.get()
.inclusiveDescendants({
flattened: true,
nested: true,
})
.filter(and(isElement, hasNonLinkText(device)));
const linkElements = target
// All descendants of the link.
.inclusiveDescendants({
flattened: true,
nested: true,
})
.filter(isElement)
// Plus those ancestors who don't include non-link text.
.concat(
target
.ancestors({
flattened: true,
nested: true,
})
.takeWhile(and(isElement, not(hasNonLinkText(device))))
);
const hasDistinguishingStyle = (context?: Context) =>
Set.from(
linkElements.map((link) =>
// If the link element is distinguishable from at least one
// non-link element, this is good enough.
// Note that ACT rules draft requires the link-element to be
// distinguishable from *all* non-link elements in order to be good.
nonLinkElements.some((container) =>
isDistinguishable(container, device, context)(link)
)
? Ok.of(ComputedStyles.from(link, device, context))
: Err.of(ComputedStyles.from(link, device, context))
)
)
.toArray()
// sort the Ok before the Err, relative order doesn't matter.
.sort((a, b) => (b.isOk() ? 1 : -1));
// The context needs to be set on the *target*, not on its ancestors
// or descendants
const isDefaultDistinguishable = hasDistinguishingStyle();
const isHoverDistinguishable = hasDistinguishingStyle(
Context.hover(target)
);
const isFocusDistinguishable = hasDistinguishingStyle(
Context.focus(target)
);
return {
1: expectation(
// If at least one link element is good, this is enough. The sorting
// guarantees it is first in the array.
isDefaultDistinguishable[0].isOk() &&
isHoverDistinguishable[0].isOk() &&
isFocusDistinguishable[0].isOk(),
() =>
Outcomes.IsDistinguishable(
isDefaultDistinguishable,
isHoverDistinguishable,
isFocusDistinguishable
),
() =>
Outcomes.IsNotDistinguishable(
isDefaultDistinguishable,
isHoverDistinguishable,
isFocusDistinguishable
)
),
};
},
};
},
});
export namespace Outcomes {
// We could tweak typing to ensure that isDistinguishable only accepts Ok and
// that isNotDistinguishable has at least one Err.
// This would requires changing the expectation since it does not refine
// and is thus probably not worth the effort.
export const IsDistinguishable = (
defaultStyles: Iterable<Result<ComputedStyles>>,
hoverStyles: Iterable<Result<ComputedStyles>>,
focusStyles: Iterable<Result<ComputedStyles>>
) =>
Ok.of(
DistinguishingStyles.of(
`The link is distinguishable from the surrounding text`,
defaultStyles,
hoverStyles,
focusStyles
)
);
export const IsNotDistinguishable = (
defaultStyles: Iterable<Result<ComputedStyles>>,
hoverStyles: Iterable<Result<ComputedStyles>>,
focusStyles: Iterable<Result<ComputedStyles>>
) =>
Err.of(
DistinguishingStyles.of(
`The link is not distinguishable from the surrounding text`,
defaultStyles,
hoverStyles,
focusStyles
)
);
}
const hasNonLinkTextCache = Cache.empty<Element, boolean>();
function hasNonLinkText(device: Device): Predicate<Element> {
return function hasNonLinkText(element) {
return hasNonLinkTextCache.get(element, () => {
// If we are already below a link, escape.
if (
element
.inclusiveAncestors({
flattened: true,
})
.some(
and(
isElement,
hasRole(device, (role) => role.is("link"))
)
)
) {
return false;
}
const children = element.children({
flattened: true,
});
// If we've found text, we're done.
if (children.some(and(isText, isVisible(device)))) {
return true;
}
// Otherwise, go down.
return children
.filter(isElement)
.reject(hasRole(device, (role) => role.is("link")))
.some(hasNonLinkText);
});
};
}
function isDistinguishable(
container: Element,
device: Device,
context: Context = Context.empty()
): Predicate<Element> {
return or(
// Things like text decoration and backgrounds risk blending with the
// container element. We therefore need to check if these can be distinguished
// from what the container element might itself set.
hasDistinguishableTextDecoration(container, device, context),
hasDistinguishableBackground(container, device, context),
hasDistinguishableFontWeight(container, device, context),
hasDistinguishableVerticalAlign(container, device, context),
// We consider the mere presence of borders or outlines on the element as
// distinguishable features. There's of course a risk of these blending with
// other features of the container element, such as its background, but this
// should hopefully not happen (too often) in practice. When it does, we
// risk false negatives.
hasOutline(device, context),
hasBorder(device, context)
);
}
function hasDistinguishableTextDecoration(
container: Element,
device: Device,
context?: Context
): Predicate<Element> {
return (element) =>
test(not(hasTextDecoration(device, context)), container) &&
test(hasTextDecoration(device, context), element);
}
/**
* Check if an element has a distinguishable background from the given container
* element.
*
* @remarks
* This predicate currently only considers `background-color` and
* `background-image` as a possibly distinguishable background. Other
* `background-*` properties should ideally also be considered.
*
* Additionally, this predicate do not handle transparency in the topmost layer.
* The exact same (partly transparent) `background-color` or `background-image`
* could be on top of a different (opaque) background and thus creates a
* difference. However, in these cases the (lower layer) distinguishing
* background would be on an ancestor of the link but of no non-link text (in
* order to be distinguishing), so should be found when looking at the ancestors
* of the link.
*
* Lastly, this does not account for absolutely positioned backgrounds from
* random nodes in the DOM. Using these to push an image below links in
* paragraph sounds so crazy (from a sheer code maintenance point of view) that
* this hopefully won't be a problem.
*/
function hasDistinguishableBackground(
container: Element,
device: Device,
context?: Context
): Predicate<Element> {
const colorReference = Style.from(container, device, context).computed(
"background-color"
).value;
const imageReference = Style.from(container, device, context).computed(
"background-image"
).value;
return or(
hasComputedStyle(
"background-color",
not(
// If the background is fully transparent, we assume it will end up
// being the same as the container. Intermediate backgrounds may change
// that, but these would need to be set on ancestor of the link and of
// no non-link text, so will be caught in one of the other comparisons.
(color) => Color.isTransparent(color) || color.equals(colorReference)
),
device,
context
),
// Any difference in `background-image` is considered enough. If different
// `background-image` ultimately yield the same background (e.g. the same
// image at two different URLs), this creates false negatives.
hasComputedStyle(
"background-image",
not((image) => image.equals(imageReference)),
device,
context
)
);
}
/**
* Check if an element has a different font weight than its container.
*
* This is brittle and imperfect but removes a strong pain point until we find
* a better solution.
*/
function hasDistinguishableFontWeight(
container: Element,
device: Device,
context?: Context
): Predicate<Element> {
const reference = Style.from(container, device, context).computed(
"font-weight"
).value;
return hasComputedStyle(
"font-weight",
not((weight) => weight.equals(reference)),
device,
context
);
}
function hasDistinguishableVerticalAlign(
container: Element,
device: Device,
context?: Context
): Predicate<Element> {
const reference = Style.from(container, device, context).computed(
"vertical-align"
).value;
return hasComputedStyle(
"vertical-align",
not((alignment) => alignment.equals(reference)),
device,
context
);
}
type Name = Property.Name | Property.Shorthand.Name;
export class ComputedStyles implements Equatable, Hashable, Serializable {
public static of(
style: Iterable<readonly [Name, string]> = []
): ComputedStyles {
return new ComputedStyles(Map.from(style));
}
private readonly _style: Map<Name, string>;
private constructor(style: Map<Name, string>) {
this._style = style;
}
public get style(): Map<Name, string> {
return this._style;
}
public equals(value: ComputedStyles): boolean;
public equals(value: unknown): value is this;
public equals(value: unknown): boolean {
return value instanceof ComputedStyles && value._style.equals(this._style);
}
public hash(hash: Hash): void {
this._style.hash(hash);
}
public toJSON(): ComputedStyles.JSON {
return {
style: this._style.toJSON(),
};
}
}
export namespace ComputedStyles {
export interface JSON {
[key: string]: json.JSON;
style: Map.JSON<Name, string>;
}
export function isComputedStyles(value: unknown): value is ComputedStyles {
return value instanceof ComputedStyles;
}
export function from(
element: Element,
device: Device,
context: Context = Context.empty()
): ComputedStyles {
const style = Style.from(element, device, context);
const border = (["color", "style", "width"] as const).map((property) =>
Serialise.borderShorthand(style, property)
);
return ComputedStyles.of(
[
...border,
["color", Serialise.getLonghand(style, "color")] as const,
["font-weight", Serialise.getLonghand(style, "font-weight")] as const,
[
"vertical-align",
Serialise.getLonghand(style, "vertical-align"),
] as const,
["background", Serialise.background(style)] as const,
["outline", Serialise.outline(style)] as const,
["text-decoration", Serialise.textDecoration(style)] as const,
].filter(([_, value]) => value !== "")
);
}
}
export class DistinguishingStyles extends Diagnostic {
public static of(
message: string,
defaultStyles: Iterable<Result<ComputedStyles>> = Sequence.empty(),
hoverStyles: Iterable<Result<ComputedStyles>> = Sequence.empty(),
focusStyles: Iterable<Result<ComputedStyles>> = Sequence.empty()
): DistinguishingStyles {
return new DistinguishingStyles(
message,
Sequence.from(defaultStyles),
Sequence.from(hoverStyles),
Sequence.from(focusStyles)
);
}
private readonly _defaultStyles: Sequence<Result<ComputedStyles>>;
private readonly _hoverStyles: Sequence<Result<ComputedStyles>>;
private readonly _focusStyles: Sequence<Result<ComputedStyles>>;
private constructor(
message: string,
defaultStyles: Sequence<Result<ComputedStyles>>,
hoverStyles: Sequence<Result<ComputedStyles>>,
focusStyles: Sequence<Result<ComputedStyles>>
) {
super(message);
this._defaultStyles = defaultStyles;
this._hoverStyles = hoverStyles;
this._focusStyles = focusStyles;
}
public get defaultStyles(): Iterable<Result<ComputedStyles>> {
return this._defaultStyles;
}
public get hoverStyles(): Iterable<Result<ComputedStyles>> {
return this._hoverStyles;
}
public get focusStyles(): Iterable<Result<ComputedStyles>> {
return this._focusStyles;
}
public equals(value: DistinguishingStyles): boolean;
public equals(value: unknown): value is this;
public equals(value: unknown): boolean {
return (
value instanceof DistinguishingStyles &&
value._defaultStyles.equals(this._defaultStyles) &&
value._hoverStyles.equals(this._hoverStyles) &&
value._focusStyles.equals(this._focusStyles)
);
}
public toJSON(): DistinguishingStyles.JSON {
return {
...super.toJSON(),
defaultStyle: this._defaultStyles.toJSON(),
hoverStyle: this._hoverStyles.toJSON(),
focusStyle: this._focusStyles.toJSON(),
};
}
}
export namespace DistinguishingStyles {
export interface JSON extends Diagnostic.JSON {
defaultStyle: Sequence.JSON<Result<ComputedStyles>>;
hoverStyle: Sequence.JSON<Result<ComputedStyles>>;
focusStyle: Sequence.JSON<Result<ComputedStyles>>;
}
export function isDistinguishingStyles(
value: unknown
): value is DistinguishingStyles {
return value instanceof DistinguishingStyles;
}
} | the_stack |
//import expect = require("chai").expect;
import chai = require("chai");
import chaiAsPromised = require("chai-as-promised");
import lb_constants = require("../../lib/constants/loopback_constants");
import {LoopbackRelationDefinition} from "../../lib/types/loopbacktypes";
import {ODataGetBase} from "../../../lib/base/get/odata_get";
import proxyquire = require("proxyquire");
import {ODataServerConfig} from "../../../lib/types/n_odata_types";
import {SinonSpy} from "sinon";
import * as sinon from "sinon";
import sinonChai = require("~sinon-chai/index");
import loopback = require("loopback");
/* see here for a good description of chai-as-promised: http://www.sitepoint.com/promises-in-javascript-unit-tests-the-definitive-guide/ */
describe("ODataGetBase", function() {
let odataConfig:ODataServerConfig;
before(() => {
chai.use(chaiAsPromised);
chai.should(); // found this hack on the internet, otherwise tests with should fail
odataConfig = {
maxpagesize: 200,
odataversion: "2",
odataPrefix: "odata"
} as ODataServerConfig;
});
describe("getCollectionData", () => {
let sut:ODataGetBase;
beforeEach(() => {
});
it("should be rejected cause no ModelClass can be found", () => {
let req:any = {
url: "http://localhost:3000/Customer?$orderby=quantity",
app: {
models: () => {}
},
params: [
"one"
]
};
let res:any = {
status: 0
};
// Stubbing the commons module that is used in metadata.ts
let commonsStub:any = {
getRequestModelClass: (models, param) => {
return Promise.resolve({});
}
};
// create the proxyquire proxy for metadata with the injected module stubs
let sutProxy = proxyquire("../../../lib/base/get/odata_get", {'../../common/odata_common': commonsStub});
// create sut (subject under test)
sut = new sutProxy.ODataGetBase();
// invoke method to test
let promise = sut._getCollectionData(req, res);
// check assertions
return promise.should.eventually.be.rejected;
});
it("should return an empty result but fulfill the promise", () => {
let req:any = {
url: "http://localhost:3000/Customer?$orderby=quantity",
app: {
models: () => {}
},
params: [
"one"
],
query: {}
};
let res:any = {
status: 0,
set: (key:string, value:string) => {}
};
// spy the res.set method
let resSpy:SinonSpy = sinon.spy(res, 'set');
// Stubbing the commons and other modules that are used in .ts file
let commonsStub:any = { // stubbing odata_common.ts
getRequestModelClass: (models, param) => {
return Promise.resolve({
modelClass: {
count: () => {},
find: (filter, callback) => {return Promise.resolve([])},
}
});
},
getBaseURL: (req) => {return "http://localhost:3000"},
getPluralForModel: (ModelClass) => {return "Customers"}
};
let requestheaderStub:any = { // stubbing requestHeader
getPreferHeader: (req) => {return [
{ 0: "maxpagesize", 1: 50 }
]}
};
// create the proxyquire proxy for sut module with the injected module stubs
let sutProxy = proxyquire("../../../lib/base/get/odata_get", {
'../../common/odata_common': commonsStub,
'../../common/odata_req_header': requestheaderStub
});
// create sut (subject under test)
sut = new sutProxy.ODataGetBase();
sut.setConfig(odataConfig);
// invoke method to test
let promise = sut._getCollectionData(req, res);
// check assertions
//resSpy.should.eventually.have.been.calledOnce;
let expectedResult = {
data: [],
nextLink: "http://localhost:3000/Customers?$skiptoken=200"
};
return Promise.all([
promise.should.eventually.have.property('data'),
promise.should.eventually.have.property('nextLink'),
promise.should.eventually.have.property('nextLink').equals("http://localhost:3000/Customers?$skiptoken=50")
]);
});
it("should return a unfiltered result set", () => {
let oModel:any = loopback.createModel('my-model', {name: String});
var dataSource = loopback.createDataSource({
connector: loopback.Memory
} as any);
oModel.attachTo(dataSource);
let req:any = {
url: "http://localhost:3000/Customer?$orderby=quantity",
app: {
models: () => {}
},
params: [
"one"
],
query: {}
};
let res:any = {
status: 0,
set: (key:string, value:string) => {}
};
// spy the res.set method
let resSpy:SinonSpy = sinon.spy(res, 'set');
let commonsStub:any = { // stubbing odata_common.ts
getRequestModelClass: (models, param) => {
return Promise.resolve({
modelClass: oModel
});
},
getBaseURL: (req) => {return "http://localhost:3000"},
getPluralForModel: (ModelClass) => {return "Customers"}
};
let requestheaderStub:any = { // stubbing requestHeader
getPreferHeader: (req) => {return [
{ 0: "maxpagesize", 1: 50 }
]}
};
// create the proxyquire proxy for sut module with the injected module stubs
let sutProxy = proxyquire("../../../lib/base/get/odata_get", {
'../../common/odata_common': commonsStub,
'../../common/odata_req_header': requestheaderStub
});
// create sut (subject under test)
sut = new sutProxy.ODataGetBase();
sut.setConfig(odataConfig);
// invoke method to test
let promise = sut._getCollectionData(req, res);
// check assertions
//resSpy.should.eventually.have.been.calledOnce;
let expectedResult = {
data: [],
nextLink: "http://localhost:3000/Customers?$skiptoken=200"
};
return Promise.all([
promise.should.eventually.have.property('data'),
promise.should.eventually.have.property('data').to.have.lengthOf(0)
]);
});
});
describe("getCollectionCount", () => {
beforeEach(function () {
});
it("should return with bad request error cause param $count is not defined", () => {
let req:any = {
params: [
"someWrongParam"
]
};
// create the proxyquire proxy for sut module with the injected module stubs
let sutProxy = proxyquire("../../../lib/base/get/odata_get", {});
// create sut (subject under test)
let sut:ODataGetBase = new sutProxy.ODataGetBase();
// invoke method to test
let promise = sut._getCollectionCount(req, null);
// check assertions
return promise.should.eventually.be.rejectedWith("Error: bad request");
});
it("should return error code 415 cause of wrong accept header", () => {
let req:any = {
app: {
models: () => {}
},
params: [
"$count"
],
accepts: (type:string) => {return false}
};
// Stubbing the commons and other modules that are used in .ts file
let commonsStub:any = {
getRequestModelClass: (models, param) => {
return Promise.resolve({
modelClass: {
count: (filter:string, fn:Function) => {fn(null, 15)}
}
});
}
}; // stubbing odata_common.ts
// create the proxyquire proxy for sut module with the injected module stubs
let sutProxy = proxyquire("../../../lib/base/get/odata_get", {
'../../common/odata_common': commonsStub
});
// create sut (subject under test)
let sut:ODataGetBase = new sutProxy.ODataGetBase();
// invoke method to test
let promise = sut._getCollectionCount(req, null);
// check assertions
return promise.should.eventually.be.rejectedWith("415");
})
it("should return correct number of records", () => {
let req:any = {
app: {
models: () => {}
},
params: [
"$count"
],
accepts: (type:string) => {
if (type === 'text/plain') {
return true
} else return false
}
};
// Stubbing the commons and other modules that are used in .ts file
// when count is called from n-odata-server it will return the value of 15
// that is defined here.
let commonsStub:any = {
getRequestModelClass: (models, param) => {
return Promise.resolve({
modelClass: {
count: (filter:string, fn:Function) => {fn(null, 15)}
}
});
}
}; // stubbing odata_common.ts
// create the proxyquire proxy for sut module with the injected module stubs
let sutProxy = proxyquire("../../../lib/base/get/odata_get", {
'../../common/odata_common': commonsStub
});
// create sut (subject under test)
let sut:ODataGetBase = new sutProxy.ODataGetBase();
// invoke method to test
let promise = sut._getCollectionCount(req, null);
// check assertions
return promise.should.eventually.be.equal(15);
})
it("should return an error cause count() threw error", () => {
let req:any = {
app: {
models: () => {}
},
params: [
"$count"
],
accepts: (type:string) => {
if (type === 'text/plain') {
return true
} else return false
}
};
// Stubbing the commons and other modules that are used in .ts file
// when count is called from n-odata-server it will return the value of 15
// that is defined here.
let commonsStub:any = {
getRequestModelClass: (models, param) => {
return Promise.resolve({
modelClass: {
count: (filter:string, fn:Function) => {fn(new Error("this is an error case"), null)}
}
});
}
}; // stubbing odata_common.ts
// create the proxyquire proxy for sut module with the injected module stubs
let sutProxy = proxyquire("../../../lib/base/get/odata_get", {
'../../common/odata_common': commonsStub
});
// create sut (subject under test)
let sut:ODataGetBase = new sutProxy.ODataGetBase();
// invoke method to test
let promise = sut._getCollectionCount(req, null);
// check assertions
return promise.should.eventually.be.rejectedWith("Error: this is an error case");
})
});
describe("getServiceDocument", () => {
beforeEach(function () {
});
it("should return an empty service document", () => {
let req:any = {
app: {
models: () => {return []}
}
};
// create sut (subject under test)
let sut:ODataGetBase = new ODataGetBase();
// invoke method to test
let promise = sut._getServiceDocument(req, null);
// check assertions
return Promise.all([
promise.should.eventually.have.property('data'),
promise.should.eventually.have.property('data').is.empty
]);
});
it("should return a service document with n models", () => {
let req:any = {
app: {
models: () => {return [
{definition: {
settings: {},
name: "Customer"
}},
{definition: {
settings: {},
name: "Product"
}}
]}
}
};
// create sut (subject under test)
let sut:ODataGetBase = new ODataGetBase();
// invoke method to test
let promise = sut._getServiceDocument(req, null);
// check assertions
return Promise.all([
promise.should.eventually.have.property('data'),
promise.should.eventually.have.property('data').not.is.empty,
promise.should.eventually.have.property('data').to.have.lengthOf(2),
promise.should.eventually.to.have.deep.property('data[0].name', "Customers"),
promise.should.eventually.to.have.deep.property('data[1].name', "Products")
]);
});
it("should return a service document with n models where the plural of the model gets read from model.definition.settings", () => {
let req:any = {
app: {
models: () => {return [
{definition: {
settings: {plural: "People"},
name: "Person"
}},
{definition: {
settings: {plural: "Plural"},
name: "Single"
}},
{definition: {
settings: {plural: "MoreProducts"},
name: "Product"
}}
]}
}
};
// create sut (subject under test)
let sut:ODataGetBase = new ODataGetBase();
// invoke method to test
let promise = sut._getServiceDocument(req, null);
// check assertions
return Promise.all([
promise.should.eventually.have.property('data'),
promise.should.eventually.have.property('data').not.is.empty,
promise.should.eventually.have.property('data').to.have.lengthOf(3),
promise.should.eventually.to.have.deep.property('data[0].name', "People"),
promise.should.eventually.to.have.deep.property('data[1].name', "Plural"),
promise.should.eventually.to.have.deep.property('data[2].name', "MoreProducts")
]);
})
});
}); | the_stack |
import { isNullOrUndefined } from '@syncfusion/ej2-base';
import { DataManager } from '@syncfusion/ej2-data';
import { Grid } from '../../../src/grid/base/grid';
import { ReturnType } from '../../../src/grid/base/type';
import { Sort } from '../../../src/grid/actions/sort';
import { Selection } from '../../../src/grid/actions/selection';
import { Filter } from '../../../src/grid/actions/filter';
import { Page } from '../../../src/grid/actions/page';
import { Group } from '../../../src/grid/actions/group';
import { Reorder } from '../../../src/grid/actions/reorder';
import { getComplexFieldID } from '../../../src/grid/base/util';
import { filterData } from '../base/datasource.spec';
import { createGrid, destroy, getClickObj, getKeyActionObj } from '../base/specutil.spec';
import { VirtualScroll } from '../../../src/grid/actions/virtual-scroll';
import '../../../node_modules/es6-promise/dist/es6-promise';
import { Render } from '../../../src/grid/renderer/render';
import {profile , inMB, getMemoryProfile} from '../base/common.spec';
Grid.Inject(Sort, Page, Filter, Group, Selection, Reorder, VirtualScroll);
function copyObject(source: Object, destiation: Object): Object {
for (let prop in source) {
destiation[prop] = source[prop];
}
return destiation;
}
function getEventObject(eventType: string, eventName: string, target?: Element, x?: number, y?: number): Object {
let tempEvent: any = document.createEvent(eventType);
tempEvent.initEvent(eventName, true, true);
let returnObject: any = copyObject(tempEvent, {});
returnObject.preventDefault = () => { return true; };
if (!isNullOrUndefined(x)) {
returnObject.pageX = x;
returnObject.clientX = x;
}
if (!isNullOrUndefined(y)) {
returnObject.pageY = y;
returnObject.clientY = y;
}
if (!isNullOrUndefined(target)) {
returnObject.target = returnObject.srcElement = returnObject.toElement = returnObject.currentTarget = target;
}
return returnObject;
}
describe('Grouping module => ', () => {
describe('Grouping functionalites => ', () => {
let gridObj: Grid;
let actionBegin: () => void;
let actionComplete: () => void;
beforeAll((done: Function) => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
}
gridObj = createGrid(
{
dataSource: filterData,
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'ShipCity', headerText: 'Ship City' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowGrouping: true,
allowSelection: true,
groupSettings: { showGroupedColumn: true },
allowPaging: true,
actionBegin: actionBegin,
actionComplete: actionComplete,
}, done);
});
it('group drop area testing', () => {
let dropArea: any = gridObj.element.querySelectorAll('.e-groupdroparea');
expect(dropArea.length).toBe(1);
expect(dropArea[0].textContent).toBe('Drag a column header here to group its column');
});
it('Single column group testing', (done: Function) => {
actionComplete = (args?: Object): void => {
let grpHIndent = gridObj.getHeaderContent().querySelectorAll('.e-grouptopleftcell');
let content = gridObj.getContent().querySelectorAll('tr');
let gHeader = gridObj.element.querySelectorAll('.e-groupheadercell');
expect(grpHIndent.length).toBe(1);
expect(grpHIndent[0].querySelector('.e-headercelldiv').classList.contains('e-emptycell')).toBeTruthy();
expect(content[0].querySelectorAll('.e-recordplusexpand').length).toBe(1);
expect(content[0].querySelectorAll('.e-recordplusexpand'
)[0].firstElementChild.classList.contains('e-gdiagonaldown')).toBeTruthy();
expect(content[0].querySelectorAll('.e-groupcaption').length).toBe(1);
expect(content[0].querySelectorAll('.e-groupcaption')[0].getAttribute('colspan')).toBe('6');
expect(content[0].querySelectorAll('.e-groupcaption')[0].textContent).toBe('Ship City: Albuquerque - 5 items');
expect(content[1].querySelectorAll('.e-indentcell').length).toBe(1);
expect(gridObj.getContent().querySelectorAll('.e-recordplusexpand').length).toBe(6);
expect(gHeader.length).toBe(1);
expect(gHeader[0].querySelectorAll('.e-grouptext').length).toBe(1);
expect(gHeader[0].querySelectorAll('.e-grouptext')[0].textContent).toBe('Ship City');
expect(gHeader[0].querySelectorAll('.e-groupsort').length).toBe(1);
expect(gHeader[0].querySelectorAll('.e-groupsort')[0].classList.contains('e-ascending')).toBeTruthy();
expect(gHeader[0].querySelectorAll('.e-ungroupbutton').length).toBe(1);
expect(gridObj.groupSettings.columns.length).toBe(1);
expect(gridObj.sortSettings.columns.length).toBe(1);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.groupModule.groupColumn('ShipCity');
});
it('Expandcollase row shortcut testing', () => {
gridObj.selectRow(1, true);
(<any>gridObj.groupModule).keyPressHandler(getKeyActionObj('altUpArrow'));
expect(gridObj.getContent().querySelectorAll('tr:not([style*="display: none"])').length).toBe(13);
(<any>gridObj.groupModule).keyPressHandler(getKeyActionObj('altUpArrow'));
expect(gridObj.getContent().querySelectorAll('tr:not([style*="display: none"])').length).toBe(13);
(<any>gridObj.groupModule).keyPressHandler(getKeyActionObj('altDownArrow'));
expect(gridObj.getContent().querySelectorAll('tr:not([style*="display: none"])').length).toBe(18);
(<any>gridObj.groupModule).keyPressHandler(getKeyActionObj('altDownArrow'));
expect(gridObj.getContent().querySelectorAll('tr:not([style*="display: none"])').length).toBe(18);
});
it('Expandcollase row - selection disable testing', () => {
gridObj.allowSelection = false;
gridObj.dataBind();
(<any>gridObj.groupModule).keyPressHandler(getKeyActionObj('altUpArrow'));
expect(gridObj.getContent().querySelectorAll('tr:not([style*="display: none"])').length).toBe(18);
gridObj.allowSelection = true;
gridObj.dataBind();
});
it('multi column group testing', (done: Function) => {
actionComplete = (args?: Object): void => {
expect(gridObj.groupSettings.columns.length).toBe(2);
expect(gridObj.sortSettings.columns.length).toBe(2);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.groupModule.groupColumn('ShipCountry');
});
it('multiple column group testing', (done: Function) => {
actionComplete = (args?: Object): void => {
let grpHIndent = gridObj.getHeaderContent().querySelectorAll('.e-grouptopleftcell');
let content = gridObj.getContent().querySelectorAll('tr');
let gHeader = gridObj.element.querySelectorAll('.e-groupheadercell');
expect(grpHIndent.length).toBe(3);
expect(gridObj.getHeaderContent().querySelectorAll('.e-grouptopleftcell').length).toBe(3);
expect(content[0].querySelectorAll('.e-recordplusexpand').length).toBe(1);
expect((content[0].querySelectorAll('.e-recordplusexpand')[0] as HTMLTableCellElement).cellIndex).toBe(0);
expect(content[0].querySelectorAll('.e-indentcell').length).toBe(0);
expect(content[0].querySelectorAll('.e-recordplusexpand'
)[0].firstElementChild.classList.contains('e-gdiagonaldown')).toBeTruthy();
expect(content[1].querySelectorAll('.e-recordplusexpand').length).toBe(1);
expect((content[1].querySelectorAll('.e-recordplusexpand')[0] as HTMLTableCellElement).cellIndex).toBe(1);
expect(content[1].querySelectorAll('.e-indentcell').length).toBe(1);
expect(content[1].querySelectorAll('.e-recordplusexpand'
)[0].firstElementChild.classList.contains('e-gdiagonaldown')).toBeTruthy();
expect(content[2].querySelectorAll('.e-recordplusexpand').length).toBe(1);
expect((content[2].querySelectorAll('.e-recordplusexpand')[0] as HTMLTableCellElement).cellIndex).toBe(2);
expect(content[2].querySelectorAll('.e-indentcell').length).toBe(2);
expect(content[2].querySelectorAll('.e-recordplusexpand'
)[0].firstElementChild.classList.contains('e-gdiagonaldown')).toBeTruthy();
expect(content[0].querySelectorAll('.e-groupcaption')[0].getAttribute('colspan')).toBe('8');
expect(content[1].querySelectorAll('.e-groupcaption')[0].getAttribute('colspan')).toBe('7');
expect(content[2].querySelectorAll('.e-groupcaption')[0].getAttribute('colspan')).toBe('6');
expect(content[0].querySelectorAll('.e-groupcaption').length).toBe(1);
expect(content[1].querySelectorAll('.e-groupcaption').length).toBe(1);
expect(content[2].querySelectorAll('.e-groupcaption').length).toBe(1);
expect(content[0].querySelectorAll('.e-groupcaption')[0].textContent).toBe('Ship City: Albuquerque - 1 item');
expect(content[1].querySelectorAll('.e-groupcaption')[0].textContent).toBe('Ship Country: USA - 1 item');
expect(content[2].querySelectorAll('.e-groupcaption')[0].textContent).toBe('CustomerID: RATTC - 5 items');
expect(content[3].querySelectorAll('.e-indentcell').length).toBe(3);
expect(gridObj.getContent().querySelectorAll('.e-recordplusexpand').length).toBe(18);
expect(gHeader.length).toBe(3);
expect(gridObj.groupSettings.columns.length).toBe(3);
expect(gridObj.sortSettings.columns.length).toBe(3);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.groupModule.groupColumn('CustomerID');
});
it('ungroup testing', (done: Function) => {
actionComplete = (args?: Object): void => {
let grpHIndent = gridObj.getHeaderContent().querySelectorAll('.e-grouptopleftcell');
let content = gridObj.getContent().querySelectorAll('tr');
let gHeader = gridObj.element.querySelectorAll('.e-groupheadercell');
expect(grpHIndent.length).toBe(2);
expect(gridObj.getHeaderContent().querySelectorAll('.e-grouptopleftcell').length).toBe(2);
expect(content[0].querySelectorAll('.e-recordplusexpand').length).toBe(1);
expect((content[0].querySelectorAll('.e-recordplusexpand')[0] as HTMLTableCellElement).cellIndex).toBe(0);
expect(content[0].querySelectorAll('.e-indentcell').length).toBe(0);
expect(content[0].querySelectorAll('.e-recordplusexpand'
)[0].firstElementChild.classList.contains('e-gdiagonaldown')).toBeTruthy();
expect(content[1].querySelectorAll('.e-recordplusexpand').length).toBe(1);
expect((content[1].querySelectorAll('.e-recordplusexpand')[0] as HTMLTableCellElement).cellIndex).toBe(1);
expect(content[1].querySelectorAll('.e-indentcell').length).toBe(1);
expect(content[1].querySelectorAll('.e-recordplusexpand'
)[0].firstElementChild.classList.contains('e-gdiagonaldown')).toBeTruthy();
expect(content[0].querySelectorAll('.e-groupcaption')[0].getAttribute('colspan')).toBe('7');
expect(content[1].querySelectorAll('.e-groupcaption')[0].getAttribute('colspan')).toBe('6');
expect(content[0].querySelectorAll('.e-groupcaption').length).toBe(1);
expect(content[1].querySelectorAll('.e-groupcaption').length).toBe(1);
expect(content[0].querySelectorAll('.e-groupcaption')[0].textContent).toBe('Ship City: Albuquerque - 1 item');
expect(content[1].querySelectorAll('.e-groupcaption')[0].textContent).toBe('CustomerID: RATTC - 5 items');
expect(content[2].querySelectorAll('.e-indentcell').length).toBe(2);
expect(gridObj.getContent().querySelectorAll('.e-recordplusexpand').length).toBe(12);
expect(gHeader.length).toBe(2);
expect(gridObj.groupSettings.columns.length).toBe(2);
expect(gridObj.sortSettings.columns.length).toBe(2);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.groupModule.ungroupColumn('ShipCountry');
});
it('Sort column with sorting disabled testing', (done: Function) => {
actionComplete = (args?: Object): void => {
expect(gridObj.element.querySelector('.e-groupdroparea').querySelectorAll('.e-descending').length).toBe(0);
expect(gridObj.element.querySelector('.e-groupdroparea').querySelectorAll('.e-ascending').length).toBe(2);
expect(gridObj.sortSettings.columns[0].direction).toBe('Ascending');
expect(gridObj.sortSettings.columns[1].direction).toBe('Ascending');
expect(gridObj.getColumnHeaderByField('CustomerID').querySelectorAll('.e-ascending').length).toBe(1);
expect(gridObj.getColumnHeaderByField('ShipCity').querySelectorAll('.e-ascending').length).toBe(1);
done();
};
gridObj.actionComplete = actionComplete;
let grpHCell = gridObj.element.querySelectorAll('.e-groupheadercell');
(gridObj.groupModule as any).clickHandler(getClickObj(grpHCell[0]));
(gridObj.groupModule as any).clickHandler(getClickObj(grpHCell[1]));
gridObj.allowSorting = true;
gridObj.dataBind();
});
it('Sort column with sorting enable testing', (done: Function) => {
actionComplete = (args?: Object): void => {
expect(gridObj.element.querySelector('.e-groupdroparea').querySelectorAll('.e-descending').length).toBe(1);
expect(gridObj.element.querySelector('.e-groupdroparea').querySelectorAll('.e-ascending').length).toBe(1);
expect(gridObj.sortSettings.columns[1].direction).toBe('Descending');
expect(gridObj.getColumnHeaderByField('ShipCity').querySelectorAll('.e-descending').length).toBe(1);
done();
};
let grpHCell = gridObj.element.querySelectorAll('.e-groupheadercell');
gridObj.actionComplete = actionComplete;
(gridObj.groupModule as any).clickHandler(getClickObj(grpHCell[0]));
});
it('Sort column with sorting enable testing', (done: Function) => {
actionComplete = (args?: Object): void => {
expect(gridObj.element.querySelector('.e-groupdroparea').querySelectorAll('.e-descending').length).toBe(2);
expect(gridObj.element.querySelector('.e-groupdroparea').querySelectorAll('.e-ascending').length).toBe(0);
expect(gridObj.sortSettings.columns[1].direction).toBe('Descending');
expect(gridObj.getColumnHeaderByField('CustomerID').querySelectorAll('.e-descending').length).toBe(1);
done();
};
let grpHCell = gridObj.element.querySelectorAll('.e-groupheadercell');
gridObj.actionComplete = actionComplete;
(gridObj.groupModule as any).clickHandler(getClickObj(grpHCell[1]));
});
it('ungroup from button click testing', (done: Function) => {
actionComplete = (args?: Object): void => {
let grpHIndent = gridObj.getHeaderContent().querySelectorAll('.e-grouptopleftcell');
let gHeader = gridObj.element.querySelectorAll('.e-groupheadercell');
expect(grpHIndent.length).toBe(1);
expect(gridObj.getContent().querySelectorAll('.e-recordplusexpand').length).toBe(8);
expect(gHeader.length).toBe(1);
expect(gridObj.groupSettings.columns.length).toBe(1);
expect(gridObj.sortSettings.columns.length).toBe(2);
done();
};
gridObj.actionComplete = actionComplete;
(gridObj.groupModule as any).clickHandler(getClickObj(gridObj.element.getElementsByClassName('e-groupheadercell')[0].querySelector('.e-ungroupbutton')));
});
// it('ungroup from drag and drop testing', (done: Function) => {
// actionComplete = (args?: Object): void => {
// let grpHIndent = gridObj.getHeaderContent().querySelectorAll('.e-grouptopleftcell');
// let gHeader = gridObj.element.querySelectorAll('.e-groupheadercell');
// expect(grpHIndent.length).toBe(0);
// expect(gridObj.getContent().querySelectorAll('.e-recordplusexpand').length).toBe(0);
// expect(gHeader.length).toBe(0);
// expect(gridObj.groupSettings.columns.length).toBe(0);
// expect(gridObj.sortSettings.columns.length).toBe(2);
// done();
// };
// gridObj.actionComplete = actionComplete;
// let gHeaders = gridObj.element.querySelectorAll('.e-groupheadercell');
// let mousedown: any = getEventObject('MouseEvents', 'mousedown', gHeaders[0], 10, 10);
// EventHandler.trigger(gridObj.element.querySelector('.e-groupdroparea') as HTMLElement, 'mousedown', mousedown);
// let mousemove: any = getEventObject('MouseEvents', 'mousemove', gHeaders[0]);
// EventHandler.trigger(<any>(document), 'mousemove', mousemove);
// mousemove.srcElement = mousemove.target = mousemove.toElement = gridObj.element.querySelector('.e-cloneproperties');
// EventHandler.trigger(<any>(document), 'mousemove', mousemove);
// mousemove.srcElement = mousemove.target = mousemove.toElement = gridObj.getContent().querySelectorAll('.e-rowcell')[1];
// EventHandler.trigger(<any>(document), 'mousemove', mousemove);
// let mouseup: any = getEventObject('MouseEvents', 'mouseup', gridObj.getContent().querySelectorAll('.e-rowcell')[1], 198, 198);
// EventHandler.trigger(<any>(document), 'mouseup', mouseup);
// });
// it('group from drag and drop testing', (done: Function) => {
// actionComplete = (args?: Object): void => {
// let grpHIndent = gridObj.getHeaderContent().querySelectorAll('.e-grouptopleftcell');
// let gHeader = gridObj.element.querySelectorAll('.e-groupheadercell');
// expect(grpHIndent.length).toBe(1);
// expect(gridObj.getContent().querySelectorAll('.e-recordplusexpand').length).toBe(8);
// expect(gHeader.length).toBe(1);
// expect(gridObj.groupSettings.columns.length).toBe(1);
// expect(gridObj.sortSettings.columns.length).toBe(2);
// done();
// };
// gridObj.actionComplete = actionComplete;
// let gHeaders = gridObj.element.querySelectorAll('.e-groupheadercell');
// let headers = gridObj.getHeaderContent().querySelectorAll('.e-headercell');
// let mousedown: any = getEventObject('MouseEvents', 'mousedown', headers[1].querySelector('.e-headercelldiv'), 20, 40);
// EventHandler.trigger(gridObj.getHeaderContent().querySelector('.e-columnheader') as HTMLElement, 'mousedown', mousedown);
// let mousemove: any = getEventObject('MouseEvents', 'mousemove', headers[1]);
// EventHandler.trigger(<any>(document), 'mousemove', mousemove);
// mousemove.srcElement = mousemove.target = mousemove.toElement = gridObj.element.querySelector('.e-cloneproperties');
// EventHandler.trigger(<any>(document), 'mousemove', mousemove);
// mousemove.srcElement = mousemove.target = mousemove.toElement = gridObj.element.querySelector('.e-groupdroparea');
// EventHandler.trigger(<any>(document), 'mousemove', mousemove);
// let mouseup: any = getEventObject('MouseEvents', 'mouseup', gridObj.element.querySelector('.e-groupdroparea'), 10, 13);
// EventHandler.trigger(<any>(document), 'mouseup', mouseup);
// });
it('collapseAll method testing', () => {
let expandElem = gridObj.getContent().querySelectorAll('.e-recordplusexpand');
gridObj.groupModule.expandCollapseRows(expandElem[1]);
gridObj.groupModule.expandCollapseRows(expandElem[0]);
gridObj.groupModule.collapseAll();
expect(gridObj.getContent().querySelectorAll('tr:not([style*="display: none"])').length).toBe(8);
});
it('expandAll method testing', () => {
gridObj.groupModule.expandAll();
expect(gridObj.getContent().querySelectorAll('tr:not([style*="display: none"])').length).toBe(20);
});
it('collapseAll shortcut testing', () => {
let expandElem = gridObj.getContent().querySelectorAll('.e-recordplusexpand');
gridObj.groupModule.expandCollapseRows(expandElem[1]);
gridObj.groupModule.expandCollapseRows(expandElem[0]);
(<any>gridObj.groupModule).keyPressHandler(getKeyActionObj('ctrlUpArrow'));
expect(gridObj.getContent().querySelectorAll('tr:not([style*="display: none"])').length).toBe(8);
});
it('expandAll shortcut testing', () => {
(<any>gridObj.groupModule).keyPressHandler(getKeyActionObj('ctrlDownArrow'));
expect(gridObj.getContent().querySelectorAll('tr:not([style*="display: none"])').length).toBe(20);
});
it('multi column group testing', (done: Function) => {
actionComplete = (args?: Object): void => {
expect(gridObj.groupSettings.columns.length).toBe(2);
expect(gridObj.sortSettings.columns.length).toBe(2);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.groupModule.groupColumn('ShipCity');
});
it('expandcollapse rows method testing', () => {
let expandElem = gridObj.getContent().querySelectorAll('.e-recordplusexpand');
gridObj.groupModule.expandCollapseRows(expandElem[1]);
expect(gridObj.getContent().querySelectorAll('tr:not([style*="display: none"])').length).toBe(28);
gridObj.groupModule.expandCollapseRows(expandElem[0]);
expect(gridObj.getContent().querySelectorAll('tr:not([style*="display: none"])').length).toBe(27);
gridObj.groupModule.expandCollapseRows(expandElem[0]);
expect(gridObj.getContent().querySelectorAll('tr:not([style*="display: none"])').length).toBe(28);
gridObj.groupModule.expandCollapseRows(expandElem[1]);
expect(gridObj.getContent().querySelectorAll('tr:not([style*="display: none"])').length).toBe(30);
gridObj.groupModule.expandCollapseRows(expandElem[2]);
expect(gridObj.getContent().querySelectorAll('tr:not([style*="display: none"])').length).toBe(27);
gridObj.groupModule.expandCollapseRows(expandElem[2]);
expect(gridObj.getContent().querySelectorAll('tr:not([style*="display: none"])').length).toBe(30);
});
afterAll(() => {
destroy(gridObj);
gridObj = actionBegin = actionComplete = null;
});
});
describe('Grouping columns hide => ', () => {
let gridObj: Grid;
let actionBegin: () => void;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'ShipCity', headerText: 'Ship City' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowGrouping: true,
allowSorting: true,
groupSettings: { showGroupedColumn: false },
allowPaging: true,
actionBegin: actionBegin,
actionComplete: actionComplete
}, done);
});
it('Single column group testing', (done: Function) => {
actionComplete = (args?: Object): void => {
expect(gridObj.groupSettings.columns.length).toBe(1);
expect(gridObj.sortSettings.columns.length).toBe(1);
expect(gridObj.element.querySelectorAll('.e-headercell:not(.e-hide)').length).toBe(5);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.groupModule.groupColumn('ShipCity');
});
it('Single column ungroup testing', (done: Function) => {
actionComplete = (args?: Object): void => {
expect(gridObj.groupSettings.columns.length).toBe(0);
expect(gridObj.sortSettings.columns.length).toBe(0);
expect(gridObj.element.querySelectorAll('.e-headercell:not(.e-hide)').length).toBe(6);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.groupModule.ungroupColumn('ShipCity');
});
afterAll(() => {
destroy(gridObj);
gridObj = actionBegin = actionComplete = null;
});
});
describe('Grouping set model test case and reorder => ', () => {
let gridObj: Grid;
let actionBegin: () => void;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'ShipCity', headerText: 'Ship City' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowGrouping: true,
allowSorting: true,
allowPaging: true,
allowReordering: true,
groupSettings: { showDropArea: false, showToggleButton: true, showUngroupButton: true },
actionBegin: actionBegin,
actionComplete: actionComplete
}, done);
});
it('check default group property rendering', () => {
expect(gridObj.element.querySelectorAll('.e-groupdroparea').length).toBe(1);
expect(gridObj.getHeaderTable().querySelectorAll('.e-grptogglebtn').length).toBe(gridObj.columns.length);
});
it('disable Grouping', (done: Function) => {
actionComplete = () => {
expect(gridObj.element.querySelectorAll('.e-groupdroparea').length).toBe(0);
expect(gridObj.getHeaderTable().querySelectorAll('.e-grptogglebtn').length).toBe(0);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.allowGrouping = false;
gridObj.dataBind();
});
it('enable Grouping', (done: Function) => {
actionComplete = () => {
expect(gridObj.element.querySelectorAll('.e-groupdroparea').length).toBe(1);
expect(gridObj.getHeaderTable().querySelectorAll('.e-grptogglebtn').length).toBe(gridObj.columns.length);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.allowGrouping = true;
gridObj.dataBind();
});
it('group a column', (done: Function) => {
actionComplete = () => {
expect(gridObj.element.querySelectorAll('.e-groupdroparea').length).toBe(1);
expect(gridObj.getHeaderTable().querySelectorAll('.e-grptogglebtn.e-toggleungroup').length).toBe(1);
expect(gridObj.element.querySelectorAll('.e-groupdroparea')[0].querySelectorAll('.e-ungroupbutton').length).toBe(1);
expect(gridObj.getHeaderTable().querySelectorAll('.e-ascending').length).toBe(1);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.groupModule.groupColumn('EmployeeID');
});
it('reOrder the grouped column', (done: Function) => {
actionComplete = () => {
expect(gridObj.getHeaderTable().querySelectorAll('.e-grptogglebtn.e-toggleungroup').length).toBe(1);
expect(gridObj.element.querySelectorAll('.e-groupdroparea')[0].querySelectorAll('.e-ungroupbutton').length).toBe(1);
expect(gridObj.getHeaderTable().querySelectorAll('.e-ascending').length).toBe(1);
expect(gridObj.getHeaderContent().querySelectorAll('.e-headercell')[5].children[0].innerHTML).toMatch('Employee ID');
expect(gridObj.getContent().querySelectorAll('.e-row').length).toBe(12);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.reorderColumns('EmployeeID', 'ShipCountry');
});
afterAll(() => {
destroy(gridObj);
gridObj = actionBegin = actionComplete = null;
});
});
describe('Group settings apis => ', () => {
let gridObj: Grid;
let actionBegin: () => void;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'ShipCity', headerText: 'Ship City' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowGrouping: true,
allowSorting: true,
groupSettings: { showToggleButton: true, showGroupedColumn: true },
allowPaging: true,
actionBegin: actionBegin,
actionComplete: actionComplete,
}, done);
});
it('sort after group testing', (done: Function) => {
actionComplete = (args?: Object): void => {
expect(gridObj.groupSettings.columns.length).toBe(1);
done();
};
gridObj.actionComplete = actionComplete;
let headers = gridObj.getHeaderContent().querySelectorAll('.e-headercell');
(gridObj.groupModule as any).clickHandler(getClickObj(headers[0].querySelector('.e-grptogglebtn')));
});
it('group from toogle header testing', (done: Function) => {
actionComplete = (args?: Object): void => {
expect(gridObj.sortSettings.columns.length).toBe(2);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.sortColumn('CustomerID', 'Ascending', false);
});
it('hide drop area', () => {
gridObj.groupSettings.showDropArea = false;
gridObj.dataBind();
expect((gridObj.element.querySelectorAll('.e-groupdroparea')[0] as HTMLElement).style.display).toBe('none');
});
it('show drop area', () => {
gridObj.groupSettings.showDropArea = true;
gridObj.dataBind();
expect((gridObj.element.querySelectorAll('.e-groupdroparea')[0] as HTMLElement).style.display).toBe('')
});
it('hide group toggle button', () => {
gridObj.groupSettings.showToggleButton = false;
gridObj.dataBind();
expect(gridObj.getHeaderTable().querySelectorAll('.e-grptogglebtn').length).toBe(0);
});
it('show group toggle button', () => {
gridObj.groupSettings.showToggleButton = true;
gridObj.dataBind();
expect(gridObj.getHeaderTable().querySelectorAll('.e-grptogglebtn').length).toBe(gridObj.columns.length);
});
it('hide ungroup button', () => {
gridObj.groupSettings.showUngroupButton = false;
gridObj.dataBind();
expect((gridObj.element.querySelectorAll('.e-groupdroparea')[0].
querySelectorAll('.e-ungroupbutton')[0] as HTMLElement).style.display).toBe('none');
});
it('show ungroup button', () => {
gridObj.groupSettings.showUngroupButton = true;
gridObj.dataBind();
expect((gridObj.element.querySelectorAll('.e-groupdroparea')[0].
querySelectorAll('.e-ungroupbutton')[0] as HTMLElement).style.display).toBe('');
});
it('ungroup from toogele header testing', (done: Function) => {
actionComplete = (args?: Object): void => {
expect(gridObj.groupSettings.columns.length).toBe(0);
done();
};
gridObj.actionComplete = actionComplete;
let headers = gridObj.getHeaderContent().querySelectorAll('.e-headercell');
(gridObj.groupModule as any).clickHandler(getClickObj(headers[0].querySelector('.e-grptogglebtn')));
});
afterAll(() => {
destroy(gridObj);
gridObj = actionBegin = actionComplete = null;
});
});
describe('Stacked header with grouping => ', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData, allowPaging: false,
columns: [
{
headerText: 'Order Details', toolTip: 'Order Details',
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'OrderDate', headerText: 'Order Date', format: { skeleton: 'yMd', type: 'date' }, type: 'date' }]
},
{ field: 'CustomerID', headerText: 'Customer ID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{
headerText: 'Ship Details',
columns: [
{ field: 'ShipCity', headerText: 'Ship City' },
{ field: 'ShipCountry', headerText: 'Ship Country' },
{
headerText: 'Ship Name Verified', columns: [{ field: 'ShipName', headerText: 'Ship Name' },
{ field: 'Verified', headerText: 'Verified' }]
},
],
}
],
allowGrouping: true,
allowSorting: true,
}, done);
});
it('group a column', (done: Function) => {
let actionComplete = (args: Object) => {
expect(gridObj.element.querySelectorAll('.e-groupheadercell').length).toBe(1);
expect(gridObj.getHeaderContent().querySelectorAll('.e-ascending').length).toBe(1);
expect(gridObj.getHeaderContent().querySelectorAll('.e-emptycell').length).toBe(3);
done();
};
gridObj.groupModule.groupColumn('EmployeeID');
gridObj.actionComplete = actionComplete;
});
it('sort a column', (done: Function) => {
let actionComplete = (args: Object) => {
expect(gridObj.element.querySelectorAll('.e-groupheadercell').length).toBe(1);
expect(gridObj.getHeaderContent().querySelectorAll('.e-ascending').length).toBe(2);
expect(gridObj.getHeaderContent().querySelectorAll('.e-emptycell').length).toBe(3);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.sortColumn('OrderDate', 'Ascending');
});
it('ungroup a column', (done: Function) => {
let actionComplete = (args: Object) => {
expect(gridObj.element.querySelectorAll('.e-groupheadercell').length).toBe(0);
expect(gridObj.getHeaderContent().querySelectorAll('.e-ascending').length).toBe(1);
expect(gridObj.getHeaderContent().querySelectorAll('.e-emptycell').length).toBe(0);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.groupModule.ungroupColumn('EmployeeID');
});
it('clear sort', (done: Function) => {
let actionComplete = (args: Object) => {
expect(gridObj.getHeaderContent().querySelectorAll('.e-ascending').length).toBe(0);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.clearSorting();
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('Grouping set model test case and reorder => ', () => {
let gridObj: Grid;
let actionBegin: () => void;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'ShipCity', headerText: 'Ship City' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowGrouping: true,
allowSorting: true,
allowPaging: true,
allowReordering: true,
groupSettings: { showDropArea: false, showToggleButton: true, showUngroupButton: true },
actionBegin: actionBegin,
actionComplete: actionComplete
}, done);
});
it('check default group property rendering', () => {
expect(gridObj.element.querySelectorAll('.e-groupdroparea').length).toBe(1);
expect(gridObj.getHeaderTable().querySelectorAll('.e-grptogglebtn').length).toBe(gridObj.columns.length);
});
it('disable Grouping', (done: Function) => {
actionComplete = () => {
expect(gridObj.element.querySelectorAll('.e-groupdroparea').length).toBe(0);
expect(gridObj.getHeaderTable().querySelectorAll('.e-grptogglebtn').length).toBe(0);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.allowGrouping = false;
gridObj.dataBind();
});
it('enable Grouping', (done: Function) => {
actionComplete = () => {
expect(gridObj.element.querySelectorAll('.e-groupdroparea').length).toBe(1);
expect(gridObj.getHeaderTable().querySelectorAll('.e-grptogglebtn').length).toBe(gridObj.columns.length);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.allowGrouping = true;
gridObj.dataBind();
});
it('group a column', (done: Function) => {
actionComplete = () => {
expect(gridObj.element.querySelectorAll('.e-groupdroparea').length).toBe(1);
expect(gridObj.getHeaderTable().querySelectorAll('.e-grptogglebtn.e-toggleungroup').length).toBe(1);
expect(gridObj.element.querySelectorAll('.e-groupdroparea')[0].querySelectorAll('.e-ungroupbutton').length).toBe(1);
expect(gridObj.getHeaderTable().querySelectorAll('.e-ascending').length).toBe(1);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.groupModule.groupColumn('EmployeeID');
});
it('reOrder the grouped column', (done: Function) => {
actionComplete = () => {
expect(gridObj.getHeaderTable().querySelectorAll('.e-grptogglebtn.e-toggleungroup').length).toBe(1);
expect(gridObj.element.querySelectorAll('.e-groupdroparea')[0].querySelectorAll('.e-ungroupbutton').length).toBe(1);
expect(gridObj.getHeaderTable().querySelectorAll('.e-ascending').length).toBe(1);
expect(gridObj.getHeaderContent().querySelectorAll('.e-headercell')[5].children[0].innerHTML).toMatch('Employee ID');
expect(gridObj.getContent().querySelectorAll('.e-row').length).toBe(12);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.reorderColumns('EmployeeID', 'ShipCountry');
});
afterAll(() => {
destroy(gridObj);
gridObj = actionBegin = actionComplete = null;
});
});
//initial render with grouping
describe('Grouping a column in default =>', () => {
let gridObj: Grid;
let actionBegin: () => void;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'ShipCity', headerText: 'Ship City' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowGrouping: true,
groupSettings: { columns: ['EmployeeID'] },
allowSorting: true,
allowPaging: true,
allowFiltering: true,
actionBegin: actionBegin,
actionComplete: actionComplete
}, done);
});
it('check default group property rendering', () => {
expect(gridObj.element.querySelectorAll('.e-groupdroparea').length).toBe(1);
expect(gridObj.element.querySelectorAll('.e-groupdroparea')[0].children.length).toBe(1);
expect(gridObj.element.querySelectorAll('.e-groupdroparea')[0].querySelectorAll('.e-ungroupbutton').length).toBe(1);
expect(gridObj.getHeaderContent().querySelectorAll('.e-ascending').length).toBe(1);
expect(gridObj.getHeaderContent().querySelectorAll('.e-grouptopleftcell').length).toBe(2);
expect(gridObj.getContent().querySelectorAll('.e-indentcell').length > 0).toBeTruthy()
expect(gridObj.getContent().querySelectorAll('.e-rowcell')[0].innerHTML).toBe('10258');
expect(gridObj.groupSettings.columns.length).toBe(1);
});
afterAll(() => {
destroy(gridObj);
gridObj = actionBegin = actionComplete = null;
});
});
//initial render with two columns grouped.
describe('Grouping two columns initial => ', () => {
let gridObj: Grid;
let actionBegin: () => void;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'ShipCity', headerText: 'Ship City' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowGrouping: true,
groupSettings: { columns: ['EmployeeID', 'ShipCity'] },
allowSorting: true,
allowPaging: true,
actionBegin: actionBegin,
actionComplete: actionComplete
}, done);
});
it('check default group property rendering', () => {
expect(gridObj.element.querySelectorAll('.e-groupdroparea').length).toBe(1);
expect(gridObj.element.querySelectorAll('.e-groupdroparea')[0].children.length).toBe(2);
expect(gridObj.element.querySelectorAll('.e-groupdroparea')[0].querySelectorAll('.e-ungroupbutton').length).toBe(2);
expect(gridObj.getHeaderContent().querySelectorAll('.e-ascending').length).toBe(2);
expect(gridObj.getHeaderContent().querySelectorAll('.e-grouptopleftcell').length).toBe(2);
expect(gridObj.getContentTable().querySelectorAll('.e-indentcell').length > 0).toBeTruthy();
expect(gridObj.groupSettings.columns.length).toBe(2);
});
afterAll(() => {
destroy(gridObj);
gridObj = actionBegin = actionComplete = null;
});
});
// initially grouping and sort same column
describe('Grouping and sorting same column and aria => ', () => {
let gridObj: Grid;
let actionBegin: () => void;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'ShipCity', headerText: 'Ship City' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowGrouping: true,
groupSettings: { columns: ['EmployeeID'] },
sortSettings: { columns: [{ field: 'EmployeeID', direction: 'Ascending' }] },
allowSorting: true,
allowPaging: true,
actionBegin: actionBegin,
actionComplete: actionComplete
}, done);
});
it('initial render testing', () => {
expect(gridObj.groupSettings.columns.length).toBe(gridObj.sortSettings.columns.length);
expect(gridObj.getHeaderContent().querySelectorAll('.e-sortnumber').length).toBe(0);
expect(gridObj.getHeaderContent().querySelectorAll('.e-ascending').length).toBe(1);
});
it('check aria attribute', () => {
let groupDropArea: Element = gridObj.element.querySelector('.e-groupdroparea');
expect(groupDropArea.querySelector('.e-grouptext').hasAttribute('tabindex')).toBeTruthy();
expect(groupDropArea.querySelector('.e-groupsort').hasAttribute('tabindex')).toBeTruthy();
expect(groupDropArea.querySelector('.e-ungroupbutton').hasAttribute('tabindex')).toBeTruthy();
expect(groupDropArea.querySelector('.e-grouptext').hasAttribute('aria-label')).toBeTruthy();
expect(groupDropArea.querySelector('.e-groupsort').hasAttribute('aria-label')).toBeTruthy();
expect(groupDropArea.querySelector('.e-ungroupbutton').hasAttribute('aria-label')).toBeTruthy();
expect(gridObj.element.querySelector('.e-recordplusexpand').hasAttribute('tabindex')).toBeTruthy();
});
it('clear Grouping', (done: Function) => {
actionComplete = () => {
expect(gridObj.sortSettings.columns.length).toBe(1);
expect(gridObj.groupSettings.columns.length).toBe(0);
expect(gridObj.getHeaderContent().querySelectorAll('.e-ascending').length).toBe(1);
expect(gridObj.getContent().querySelectorAll('tr').length).toBe(12);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.groupModule.ungroupColumn('EmployeeID');
});
it('clear sorting', (done: Function) => {
actionComplete = () => {
expect(gridObj.sortSettings.columns.length).toBe(0);
expect(gridObj.getHeaderContent().querySelectorAll('.e-ascending').length).toBe(0);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.clearSorting();
});
afterAll(() => {
destroy(gridObj);
gridObj = actionBegin = actionComplete = null;
});
});
describe('Grouping remote data => ', () => {
let gridObj: Grid;
let old: (e: ReturnType) => Promise<Object> = Render.prototype.validateGroupRecords;
beforeAll((done: Function) => {
jasmine.Ajax.install();
gridObj = createGrid(
{
dataSource: new DataManager({ url: '/api/test' }),
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'OrderDate', headerText: 'Ship City' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowGrouping: true,
groupSettings: { disablePageWiseAggregates: true, columns: ['EmployeeID', 'CustomerID'] },
allowPaging: true
}, done);
let first: JasmineAjaxRequest = jasmine.Ajax.requests.at(1);
first.respondWith({
'status': 200,
'contentType': 'application/json',
'responseText': JSON.stringify({ d: { results: filterData, __count: 100 } })
});
Render.prototype.validateGroupRecords = (e: ReturnType) => {
let promise: Promise<Object> = old.call(gridObj.renderModule, e);
let first: JasmineAjaxRequest = jasmine.Ajax.requests.at(1);
first.respondWith({
'status': 200,
'contentType': 'application/json',
'responseText': JSON.stringify({ d: { results: filterData, __count: 100 } })
});
return promise;
};
});
it('check data', () => {
expect(gridObj.groupSettings.columns.length).not.toBeNull();
});
afterAll(() => {
Render.prototype.validateGroupRecords = old;
destroy(gridObj);
jasmine.Ajax.uninstall();
gridObj = old = null;
});
});
describe('Grouping column by format using setmodel => ', () => {
let gridObj: Grid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'OrderDate', headerText: 'Order Date', format: 'y', enableGroupByFormat: true, type: 'date' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowGrouping: true,
// groupSettings: { disablePageWiseAggregates: true, columns: ['OrderDate', 'ShipCountry'] },
allowPaging: true,
allowSorting: true
}, done);
});
it('Single column group testing', (done: Function) => {
actionComplete = (args?: Object): void => {
let grpHIndent = gridObj.getHeaderContent().querySelectorAll('.e-grouptopleftcell');
let content = gridObj.getContent().querySelectorAll('tr');
let gHeader = gridObj.element.querySelectorAll('.e-groupheadercell');
expect(grpHIndent.length).toBe(1);
expect(content[0].querySelectorAll('.e-groupcaption').length).toBe(1);
expect(gHeader.length).toBe(1);
expect(gHeader[0].querySelectorAll('.e-grouptext').length).toBe(1);
expect(gHeader[0].querySelectorAll('.e-grouptext')[0].textContent).toBe('Order Date');
expect(gHeader[0].querySelectorAll('.e-groupsort').length).toBe(1);
expect(gHeader[0].querySelectorAll('.e-groupsort')[0].classList.contains('e-ascending')).toBeTruthy();
expect(gHeader[0].querySelectorAll('.e-ungroupbutton').length).toBe(1);
expect(gridObj.groupSettings.columns.length).toBe(1);
expect(gridObj.sortSettings.columns.length).toBe(1);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.groupModule.groupColumn('OrderDate');
});
it('multi grouping with group by format', (done: Function) => {
let actionComplete: any = (args: Object) => {
expect(gridObj.element.querySelectorAll('.e-groupcaption')[0].innerHTML.indexOf('Order Date: 1996 ') > -1).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-groupheadercell').length).toBe(2);
expect(gridObj.getHeaderContent().querySelectorAll('.e-ascending').length).toBe(2);
expect(gridObj.getHeaderContent().querySelectorAll('.e-emptycell').length).toBe(2);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.groupModule.groupColumn('EmployeeID');
});
it('sort a column with multi grouping', (done: Function) => {
let actionComplete: any = (args: Object) => {
expect(gridObj.element.querySelectorAll('.e-groupcaption')[0].innerHTML.indexOf('Order Date: 1996 ') > -1).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-groupheadercell').length).toBe(2);
expect(gridObj.getHeaderContent().querySelectorAll('.e-ascending').length).toBe(3);
expect(gridObj.getHeaderContent().querySelectorAll('.e-emptycell').length).toBe(2);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.sortColumn('OrderID', 'Ascending');
});
it('ungroup a column', (done: Function) => {
let actionComplete: any = (args: Object) => {
expect(gridObj.element.querySelectorAll('.e-groupcaption')[0].innerHTML.indexOf('Order Date: 1996 ') > -1).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-groupheadercell').length).toBe(1);
expect(gridObj.getHeaderContent().querySelectorAll('.e-ascending').length).toBe(2);
expect(gridObj.getHeaderContent().querySelectorAll('.e-emptycell').length).toBe(1);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.groupModule.ungroupColumn('EmployeeID');
});
it('clear Grouping', (done: Function) => {
actionComplete = () => {
expect(gridObj.groupSettings.columns.length).toBe(0);
expect(gridObj.getContent().querySelectorAll('tr').length).toBe(12);
expect(gridObj.getHeaderContent().querySelectorAll('.e-ascending').length).toBe(1);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.groupModule.ungroupColumn('OrderDate');
});
afterAll(() => {
destroy(gridObj);
gridObj = actionComplete = null;
});
});
describe('Grouping remote data for group by format => ', () => {
let gridObj: Grid;
let old: (e: ReturnType) => Promise<Object> = Render.prototype.validateGroupRecords;
beforeAll((done: Function) => {
jasmine.Ajax.install();
gridObj = createGrid(
{
dataSource: new DataManager({ url: '/api/test' }),
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'OrderDate', headerText: 'Order Date', format: 'y', enableGroupByFormat: true, type: 'date' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowGrouping: true,
groupSettings: { disablePageWiseAggregates: true, columns: ['OrderDate', 'CustomerID'] },
allowPaging: true
}, done);
let first: JasmineAjaxRequest = jasmine.Ajax.requests.at(1);
first.respondWith({
'status': 200,
'contentType': 'application/json',
'responseText': JSON.stringify({ d: { results: filterData, __count: 100 } })
});
Render.prototype.validateGroupRecords = (e: ReturnType) => {
let promise: Promise<Object> = old.call(gridObj.renderModule, e);
let first: JasmineAjaxRequest = jasmine.Ajax.requests.at(1);
first.respondWith({
'status': 200,
'contentType': 'application/json',
'responseText': JSON.stringify({ d: { results: filterData, __count: 100 } })
});
return promise;
};
});
it('check data', () => {
expect(gridObj.groupSettings.columns.length).not.toBeNull();
});
afterAll(() => {
Render.prototype.validateGroupRecords = old;
destroy(gridObj);
jasmine.Ajax.uninstall();
gridObj = old = null;
});
});
describe('Grouping column by format at initial settings => ', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight', format: 'C1', enableGroupByFormat: true, type: 'number' },
{ field: 'OrderDate', headerText: 'Order Date', format: 'y', enableGroupByFormat: true, type: 'date' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowGrouping: true,
groupSettings: { disablePageWiseAggregates: true, columns: ['OrderDate', 'Freight'] },
allowPaging: true,
allowSorting: true
}, done);
});
it('multi grouping with group by format at initial', (done: Function) => {
let actionComplete: any = (args: Object) => {
expect(gridObj.element.querySelectorAll('.e-groupcaption')[0].getAttribute('aria-label').indexOf('Order Date: 1996 ') > -1).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-groupheadercell').length).toBe(3);
expect(gridObj.getHeaderContent().querySelectorAll('.e-ascending').length).toBe(3);
expect(gridObj.getHeaderContent().querySelectorAll('.e-emptycell').length).toBe(3);
done();
};
gridObj.groupModule.groupColumn('EmployeeID');
gridObj.getColumnByField('OrderDate').type = 'undefined';
gridObj.dataSource[0].OrderDate = new Date('07 07 1996 00:00:23');
gridObj.actionComplete = actionComplete;
gridObj.dataBind();
});
it('sort a column with multi grouping', (done: Function) => {
let actionComplete: any = (args: Object) => {
expect(gridObj.element.querySelectorAll('.e-groupcaption')[0].getAttribute('aria-label').indexOf('Order Date: 1996 ') > -1).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-groupheadercell').length).toBe(3);
expect(gridObj.getHeaderContent().querySelectorAll('.e-ascending').length).toBe(4);
expect(gridObj.getHeaderContent().querySelectorAll('.e-emptycell').length).toBe(3);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.getColumnByField('OrderDate').type = 'undefined';
gridObj.dataSource[0].OrderDate = new Date('07 07 1996 00:01:23');
gridObj.sortColumn('OrderID', 'Ascending');
gridObj.dataBind();
});
it('ungroup a column', (done: Function) => {
let actionComplete: any = (args: Object) => {
expect(gridObj.element.querySelectorAll('.e-groupheadercell').length).toBe(2);
expect(gridObj.getHeaderContent().querySelectorAll('.e-ascending').length).toBe(3);
expect(gridObj.getHeaderContent().querySelectorAll('.e-emptycell').length).toBe(2);
done();
};
gridObj.actionComplete = actionComplete;
gridObj.groupModule.ungroupColumn('EmployeeID');
gridObj.getColumnByField('OrderDate').type = 'undefined';
gridObj.dataSource[0].OrderDate = new Date('07 07 1996 00:00:20');
gridObj.dataBind();
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('Grouping column by format at initial settings without column type declaration => ', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight', format: 'C1', enableGroupByFormat: true },
{ field: 'OrderDate', headerText: 'Order Date', format: 'y', enableGroupByFormat: true },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowGrouping: true,
groupSettings: { disablePageWiseAggregates: true, columns: ['OrderDate', 'Freight'] },
allowPaging: true,
allowSorting: true
}, done);
});
it('multi grouping with group by format at initial', (done: Function) => {
let actionComplete: any = (args: Object) => {
expect(gridObj.element.querySelectorAll('.e-groupcaption')[0].getAttribute('aria-label').indexOf('Order Date: 1996 ') > -1).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-groupheadercell').length).toBe(3);
expect(gridObj.getHeaderContent().querySelectorAll('.e-ascending').length).toBe(3);
expect(gridObj.getHeaderContent().querySelectorAll('.e-emptycell').length).toBe(3);
done();
};
gridObj.groupModule.groupColumn('EmployeeID');
gridObj.actionComplete = actionComplete;
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('Grouping disablePageWiseAggregates with empty datasource => ', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: [],
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'OrderDate', headerText: 'Ship City' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowGrouping: true,
groupSettings: { disablePageWiseAggregates: true, columns: ['OrderDate', 'ShipCountry'] },
allowPaging: true
}, done);
});
it('check data length', () => {
expect(gridObj.currentViewData.length).toBe(0);
});
it('EJ2-7165-complex data group', () => {
expect((<any>gridObj.groupModule).getGHeaderCell('Name.FirstName')).toBeNull();
});
afterAll((done) => {
destroy(gridObj);
gridObj = null;
});
});
describe('EJ2-6791-Groped content not renders properly , when grouping enabled throw set model => ', () => {
let gridObj: Grid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'ShipCity', headerText: 'Ship City' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowSorting: true,
allowPaging: true,
allowReordering: true,
actionComplete: actionComplete
}, done);
});
it('Grouping enabled throw set model', () => {
gridObj.allowGrouping = true;
gridObj.groupSettings.columns = ['EmployeeID'];
let actionComplete: any = (args: Object) => {
expect(gridObj.getContent().querySelectorAll('.e-recordplusexpand').length).toBe(7);
};
});
afterAll(() => {
destroy(gridObj);
gridObj = actionComplete = null;
});
});
describe('Grouping functionalites with empty grid => ', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: [],
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'ShipCity', headerText: 'Ship City' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowGrouping: true,
groupSettings: {columns:['OrderID']}
}, done);
});
it('group drop area - header present testing', (done: Function) => {
//Since no event for group complete on init, used set timeout
setTimeout(function(){
let dropArea: any = gridObj.element.querySelectorAll('.e-groupdroparea');
expect(dropArea.length).toBe(1);
let headerCell = dropArea[0].querySelectorAll('.e-groupheadercell')
expect(headerCell.length).toBe(1);
done();
}, 100);
});
it('group drop area - ungroup column', (done) => {
gridObj.actionComplete = function (args) {
if (args.requestType === 'ungrouping') {
expect(gridObj.groupSettings.columns.length).toBe(0);
let dropArea: any = gridObj.element.querySelectorAll('.e-groupdroparea');
let headerCell = dropArea[0].querySelectorAll('.e-groupheadercell')
expect(headerCell.length).toBe(0);
done();
}
}
gridObj.ungroupColumn('OrderID')
});
it('group drop area - group column', (done) => {
gridObj.actionComplete = function (args) {
if (args.requestType === 'grouping') {
expect(gridObj.groupSettings.columns.length).toBe(1);
let dropArea: any = gridObj.element.querySelectorAll('.e-groupdroparea');
let headerCell = dropArea[0].querySelectorAll('.e-groupheadercell')
expect(headerCell.length).toBe(1);
done();
}
}
gridObj.groupColumn('OrderID')
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('EJ2-23852-Data row not renders properly , when grouping the all columns in grid => ', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
groupSettings: { showGroupedColumn: true, columns: ['OrderID', 'CustomerID', 'EmployeeID', 'Freight'] },
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'ShipCity', headerText: 'Ship City' }],
allowSorting: true,
allowPaging: true,
allowGrouping: true
}, done);
});
it('Check whether data row is rendered while we grouping all columns in grid', () => {
expect(gridObj.element.querySelector('.e-row').querySelector('.e-rowcell').classList.contains('e-hide')).toBeFalsy();
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('Group with disable pageWise aggregate', () => {
let grid: Grid;
let actionComplete: () => void;
beforeAll((done: Function) => {
grid = createGrid(
{
allowGrouping: true,
groupSettings: { disablePageWiseAggregates: true },
columns: [
{
field: 'OrderID', headerText: 'Order ID', headerTextAlign: 'Right',
textAlign: 'Right'
},
{ field: 'Verified', displayAsCheckBox: true, type: 'boolean' },
{ field: 'Freight', format: 'C1' },
{ field: 'OrderDate', format: 'yMd', type: 'datetime' },
{ field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right' }
],
aggregates: [{
columns: [{
type: 'Average',
field: 'Freight',
groupFooterTemplate: '${Average}'
}]
},
{
columns: [{
type: ['Max'],
field: 'OrderDate',
format: 'yMd',
groupCaptionTemplate: '${Max}'
}]
}],
actionComplete: actionComplete
},
done
);
});
it('checking aggreagates with grouping', (done: Function) => {
let actionComplete: any = function (args: any) {
if (args.requestType === 'grouping') {
expect(grid.groupSettings.columns.length).toBe(1);
done();
}
};
grid.groupModule.groupColumn('Verified');
grid.actionComplete = actionComplete;
});
afterAll(() => {
destroy(grid);
grid = actionComplete = null;
});
});
//focus strategy script error
// describe('expand and collapse on enter => ', () => {
// let gridObj: Grid;
// let actionBegin: () => void;
// let actionComplete: () => void;
// let columns: any;
// beforeAll((done: Function) => {
// gridObj = createGrid(
// {
// dataSource: filterData,
// columns: [{ field: 'OrderID', headerText: 'Order ID' },
// { field: 'CustomerID', headerText: 'CustomerID' },
// { field: 'EmployeeID', headerText: 'Employee ID' },
// { field: 'Freight', headerText: 'Freight' },
// { field: 'ShipCity', headerText: 'Ship City' },
// { field: 'ShipCountry', headerText: 'Ship Country' }],
// allowGrouping: true,
// allowSelection: true,
// groupSettings: { columns: ['OrderID'] },
// allowPaging: true,
// actionBegin: actionBegin,
// actionComplete: actionComplete
// }, done);
// });
// it('collapse check', () => {
// gridObj.element.focus();
// gridObj.keyboardModule.keyAction(<any>{ action: 'enter', target: (<any>gridObj.contentModule.getTable()).rows[0].cells[0],
// preventDefault: () => {} });
// });
// it('expand check', () => {
// gridObj.keyboardModule.keyAction(<any>{ action: 'enter', target: (<any>gridObj.contentModule.getTable()).rows[0].cells[0],
// preventDefault: () => {} });
// });
// it('collapse check with edit', () => {
// gridObj.isEdit = true;
// gridObj.keyboardModule.keyAction(<any>{ action: 'enter', target: (<any>gridObj.contentModule.getTable()).rows[0].cells[0],
// preventDefault: () => {} });
// expect((<any>gridObj.contentModule.getTable()).rows[0].querySelector('.e-recordplusexpand')).not.toBeNull();
// gridObj.isEdit = false;
// });
// afterAll((done) => {
// destroy(gridObj);
// setTimeout(function () {
// done();
// }, 1000);
// });
// });
describe('EJ2-35816-Grouping with animation => ', () => {
let gridObj: Grid;
let actionComplete: () => void;
let allowGroupReordering:string = 'allowGroupReordering';
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
groupSettings: { columns: ['OrderID', 'CustomerID'], allowReordering: true },
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'ShipCity', headerText: 'Ship City' }],
allowSorting: true,
allowPaging: true,
allowGrouping: true,
actionComplete: actionComplete
}, done);
});
it('Check whether grouped columns added in the droparea', (done) => {
gridObj.actionComplete = (args?: Object): void => {
expect(gridObj.element.querySelectorAll('.e-group-animator').length).toBe(3);
expect(gridObj.element.querySelectorAll('.e-icon-drag').length).toBe(3);
expect(gridObj.element.querySelectorAll('.e-group-animator .e-icon-next').length).toBe(3);
done();
}
gridObj.groupColumn('EmployeeID');
});
it('Check whether ungroup is working', (done) => {
gridObj.actionComplete = (args?: Object): void => {
expect(gridObj.element.querySelectorAll('.e-group-animator').length).toBe(2);
expect(gridObj.element.querySelectorAll('.e-icon-drag').length).toBe(2);
expect(gridObj.element.querySelectorAll('.e-group-animator .e-icon-next').length).toBe(2);
done();
};
gridObj.ungroupColumn('EmployeeID');
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
});
describe('EJ2-43460-Ungrouping arguments => ', () => {
let gridObj: Grid;
let actionBegin: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'ShipCity', headerText: 'Ship City' }],
allowSorting: true,
allowPaging: true,
allowGrouping: true,
actionBegin: actionBegin,
}, done);
});
it('Check whether column name is defined while grouping', (done) => {
gridObj.actionBegin = (args?: any): void => {
expect(args.columnName).toBeDefined();
gridObj.actionBegin= null;
done();
}
gridObj.groupModule.groupColumn('EmployeeID');
});
it('Check whether column name is defined while ungrouping', (done) => {
gridObj.actionBegin = (args?: any): void => {
expect(args.columnName).toBeDefined();
gridObj.actionBegin= null;
done();
}
gridObj.groupModule.ungroupColumn('EmployeeID');
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
gridObj = actionBegin = null;
});
});
describe('EJ2-44597-Sorting not removed when groupsettings column is changed => ', () => {
let gridObj: Grid;
let actionBegin: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
groupSettings: { showGroupedColumn: true , columns:['OrderID'] },
sortSettings: {columns:[{field:'CustomerID', direction:'Descending'}]},
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'ShipCity', headerText: 'Ship City' }],
allowSorting: true,
allowPaging: true,
allowGrouping: true,
actionBegin: actionBegin,
}, done);
});
it('Checking initial Grouping sorting columns', () => {
expect(gridObj.sortSettings.columns.length).toBe(2);
});
it('Checking sorting columns after changing groupsetting columns', (done) => {
gridObj.actionBegin = (args?: any): void => {
expect(gridObj.sortSettings.columns.length).toBe(2);
done();
}
gridObj.groupSettings = { showGroupedColumn:true, columns : ['EmployeeID']};
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
gridObj = actionBegin = null;
});
});
describe('EJ2-49314- Error hiding/showing columns => ', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData.slice(0,40),
enableVirtualization: true,
allowGrouping: true,
height: 300,
pageSettings : { pageSize: 100 },
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'ShipCity', headerText: 'Ship City' }],
}, done);
});
it('Checking initial Grouping sorting columns', () => {
expect(Object.keys(gridObj.currentViewData).length).toBe(40);
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('EJ2-49647- Column grouping with complex binding is broken when allowReordering is set => ', () => {
let gridObj: Grid;
let complexData: Object[] = [
{ OrderID: { ID: { ordID: 10248 } }, CustomerID: "VINET", Freight: 32.38, ShipCountry: "France" },
{ OrderID: { ID: { ordID: 10249 } }, CustomerID: "TOMSP", Freight: 11.61, ShipCountry: "Germany" },
{ OrderID: { ID: { ordID: 10250 } }, CustomerID: "HANAR", Freight: 65.83, ShipCountry: "Brazil" },
{ OrderID: { ID: { ordID: 10251 } }, CustomerID: "VICTE", Freight: 41.34, ShipCountry: "France" }];
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: complexData,
allowPaging: true,
allowGrouping: true,
groupSettings: { allowReordering: true },
columns: [
{ headerText: 'OrderID', field: 'OrderID.ID.ordID', isPrimaryKey: true },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'Freight', field: 'Freight', },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
],
}, done);
});
it('Check the grouping complex field', (done: Function) => {
let actionComplete: any = (args: any) => {
expect(gridObj.element.querySelector('.e-groupdroparea div[ej-complexname=' + getComplexFieldID(args.columnName) + ']') ).toBeDefined();
done();
};
gridObj.actionComplete = actionComplete;
gridObj.groupModule.groupColumn('OrderID.ID.ordID');
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
}); | the_stack |
import * as assert from 'assert';
import { isWindows } from 'vs/base/common/platform';
import { tmpdir } from 'os';
import { createHash } from 'crypto';
import { insert } from 'vs/base/common/arrays';
import { hash } from 'vs/base/common/hash';
import { isEqual } from 'vs/base/common/resources';
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
import { dirname, join } from 'vs/base/common/path';
import { Promises, readdirSync } from 'vs/base/node/pfs';
import { URI } from 'vs/base/common/uri';
import { WorkingCopyBackupsModel, hashIdentifier } from 'vs/workbench/services/workingCopy/common/workingCopyBackupService';
import { createTextModel } from 'vs/editor/test/common/testTextModel';
import { flakySuite, getPathFromAmdModule, getRandomTestPath } from 'vs/base/test/node/testUtils';
import { Schemas } from 'vs/base/common/network';
import { FileService } from 'vs/platform/files/common/fileService';
import { NullLogService } from 'vs/platform/log/common/log';
import { DiskFileSystemProvider } from 'vs/platform/files/node/diskFileSystemProvider';
import { NativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-sandbox/environmentService';
import { toBufferOrReadable } from 'vs/workbench/services/textfile/common/textfiles';
import { IFileService } from 'vs/platform/files/common/files';
import { NativeWorkingCopyBackupService } from 'vs/workbench/services/workingCopy/electron-sandbox/workingCopyBackupService';
import { FileUserDataProvider } from 'vs/platform/userData/common/fileUserDataProvider';
import { bufferToReadable, bufferToStream, streamToBuffer, VSBuffer, VSBufferReadable, VSBufferReadableStream } from 'vs/base/common/buffer';
import { TestNativeWindowConfiguration } from 'vs/workbench/test/electron-browser/workbenchTestServices';
import { TestLifecycleService, toTypedWorkingCopyId, toUntypedWorkingCopyId } from 'vs/workbench/test/browser/workbenchTestServices';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { IWorkingCopyBackupMeta, IWorkingCopyIdentifier } from 'vs/workbench/services/workingCopy/common/workingCopy';
import { consumeStream } from 'vs/base/common/stream';
import { TestProductService } from 'vs/workbench/test/common/workbenchTestServices';
class TestWorkbenchEnvironmentService extends NativeWorkbenchEnvironmentService {
constructor(testDir: string, backupPath: string) {
super({ ...TestNativeWindowConfiguration, backupPath, 'user-data-dir': testDir }, TestProductService);
}
}
export class NodeTestWorkingCopyBackupService extends NativeWorkingCopyBackupService {
override readonly fileService: IFileService;
private backupResourceJoiners: Function[];
private discardBackupJoiners: Function[];
discardedBackups: IWorkingCopyIdentifier[];
discardedAllBackups: boolean;
private pendingBackupsArr: Promise<void>[];
private diskFileSystemProvider: DiskFileSystemProvider;
constructor(testDir: string, workspaceBackupPath: string) {
const environmentService = new TestWorkbenchEnvironmentService(testDir, workspaceBackupPath);
const logService = new NullLogService();
const fileService = new FileService(logService);
const lifecycleService = new TestLifecycleService();
super(environmentService, fileService, logService, lifecycleService);
this.diskFileSystemProvider = new DiskFileSystemProvider(logService);
fileService.registerProvider(Schemas.file, this.diskFileSystemProvider);
fileService.registerProvider(Schemas.vscodeUserData, new FileUserDataProvider(Schemas.file, this.diskFileSystemProvider, Schemas.vscodeUserData, logService));
this.fileService = fileService;
this.backupResourceJoiners = [];
this.discardBackupJoiners = [];
this.discardedBackups = [];
this.pendingBackupsArr = [];
this.discardedAllBackups = false;
}
async waitForAllBackups(): Promise<void> {
await Promise.all(this.pendingBackupsArr);
}
joinBackupResource(): Promise<void> {
return new Promise(resolve => this.backupResourceJoiners.push(resolve));
}
override async backup(identifier: IWorkingCopyIdentifier, content?: VSBufferReadableStream | VSBufferReadable, versionId?: number, meta?: any, token?: CancellationToken): Promise<void> {
const p = super.backup(identifier, content, versionId, meta, token);
const removeFromPendingBackups = insert(this.pendingBackupsArr, p.then(undefined, undefined));
try {
await p;
} finally {
removeFromPendingBackups();
}
while (this.backupResourceJoiners.length) {
this.backupResourceJoiners.pop()!();
}
}
joinDiscardBackup(): Promise<void> {
return new Promise(resolve => this.discardBackupJoiners.push(resolve));
}
override async discardBackup(identifier: IWorkingCopyIdentifier): Promise<void> {
await super.discardBackup(identifier);
this.discardedBackups.push(identifier);
while (this.discardBackupJoiners.length) {
this.discardBackupJoiners.pop()!();
}
}
override async discardBackups(filter?: { except: IWorkingCopyIdentifier[] }): Promise<void> {
this.discardedAllBackups = true;
return super.discardBackups(filter);
}
async getBackupContents(identifier: IWorkingCopyIdentifier): Promise<string> {
const backupResource = this.toBackupResource(identifier);
const fileContents = await this.fileService.readFile(backupResource);
return fileContents.value.toString();
}
dispose() {
this.diskFileSystemProvider.dispose();
}
}
flakySuite('WorkingCopyBackupService', () => {
let testDir: string;
let backupHome: string;
let workspacesJsonPath: string;
let workspaceBackupPath: string;
let service: NodeTestWorkingCopyBackupService;
const workspaceResource = URI.file(isWindows ? 'c:\\workspace' : '/workspace');
const fooFile = URI.file(isWindows ? 'c:\\Foo' : '/Foo');
const customFile = URI.parse('customScheme://some/path');
const customFileWithFragment = URI.parse('customScheme2://some/path#fragment');
const barFile = URI.file(isWindows ? 'c:\\Bar' : '/Bar');
const fooBarFile = URI.file(isWindows ? 'c:\\Foo Bar' : '/Foo Bar');
const untitledFile = URI.from({ scheme: Schemas.untitled, path: 'Untitled-1' });
setup(async () => {
testDir = getRandomTestPath(tmpdir(), 'vsctests', 'workingcopybackupservice');
backupHome = join(testDir, 'Backups');
workspacesJsonPath = join(backupHome, 'workspaces.json');
workspaceBackupPath = join(backupHome, hash(workspaceResource.fsPath).toString(16));
service = new NodeTestWorkingCopyBackupService(testDir, workspaceBackupPath);
await Promises.mkdir(backupHome, { recursive: true });
return Promises.writeFile(workspacesJsonPath, '');
});
teardown(() => {
service.dispose();
return Promises.rm(testDir);
});
suite('hashIdentifier', () => {
test('should correctly hash the identifier for untitled scheme URIs', () => {
const uri = URI.from({ scheme: Schemas.untitled, path: 'Untitled-1' });
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// If these hashes change people will lose their backed up files
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
const untypedBackupHash = hashIdentifier(toUntypedWorkingCopyId(uri));
assert.strictEqual(untypedBackupHash, '-7f9c1a2e');
assert.strictEqual(untypedBackupHash, hash(uri.fsPath).toString(16));
const typedBackupHash = hashIdentifier({ typeId: 'hashTest', resource: uri });
if (isWindows) {
assert.strictEqual(typedBackupHash, '-17c47cdc');
} else {
assert.strictEqual(typedBackupHash, '-8ad5f4f');
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// If these hashes collide people will lose their backed up files
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
assert.notStrictEqual(untypedBackupHash, typedBackupHash);
});
test('should correctly hash the identifier for file scheme URIs', () => {
const uri = URI.file('/foo');
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// If these hashes change people will lose their backed up files
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
const untypedBackupHash = hashIdentifier(toUntypedWorkingCopyId(uri));
if (isWindows) {
assert.strictEqual(untypedBackupHash, '20ffaa13');
} else {
assert.strictEqual(untypedBackupHash, '20eb3560');
}
assert.strictEqual(untypedBackupHash, hash(uri.fsPath).toString(16));
const typedBackupHash = hashIdentifier({ typeId: 'hashTest', resource: uri });
if (isWindows) {
assert.strictEqual(typedBackupHash, '-55fc55db');
} else {
assert.strictEqual(typedBackupHash, '51e56bf');
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// If these hashes collide people will lose their backed up files
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
assert.notStrictEqual(untypedBackupHash, typedBackupHash);
});
test('should correctly hash the identifier for custom scheme URIs', () => {
const uri = URI.from({
scheme: 'vscode-custom',
path: 'somePath'
});
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// If these hashes change people will lose their backed up files
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
const untypedBackupHash = hashIdentifier(toUntypedWorkingCopyId(uri));
assert.strictEqual(untypedBackupHash, '-44972d98');
assert.strictEqual(untypedBackupHash, hash(uri.toString()).toString(16));
const typedBackupHash = hashIdentifier({ typeId: 'hashTest', resource: uri });
assert.strictEqual(typedBackupHash, '502149c7');
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// If these hashes collide people will lose their backed up files
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
assert.notStrictEqual(untypedBackupHash, typedBackupHash);
});
test('should not fail for URIs without path', () => {
const uri = URI.from({
scheme: 'vscode-fragment',
fragment: 'frag'
});
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// If these hashes change people will lose their backed up files
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
const untypedBackupHash = hashIdentifier(toUntypedWorkingCopyId(uri));
assert.strictEqual(untypedBackupHash, '-2f6b2f1b');
assert.strictEqual(untypedBackupHash, hash(uri.toString()).toString(16));
const typedBackupHash = hashIdentifier({ typeId: 'hashTest', resource: uri });
assert.strictEqual(typedBackupHash, '6e82ca57');
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// If these hashes collide people will lose their backed up files
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
assert.notStrictEqual(untypedBackupHash, typedBackupHash);
});
});
suite('getBackupResource', () => {
test('should get the correct backup path for text files', () => {
// Format should be: <backupHome>/<workspaceHash>/<scheme>/<filePathHash>
const backupResource = fooFile;
const workspaceHash = hash(workspaceResource.fsPath).toString(16);
// No Type ID
let backupId = toUntypedWorkingCopyId(backupResource);
let filePathHash = hashIdentifier(backupId);
let expectedPath = URI.file(join(backupHome, workspaceHash, Schemas.file, filePathHash)).with({ scheme: Schemas.vscodeUserData }).toString();
assert.strictEqual(service.toBackupResource(backupId).toString(), expectedPath);
// With Type ID
backupId = toTypedWorkingCopyId(backupResource);
filePathHash = hashIdentifier(backupId);
expectedPath = URI.file(join(backupHome, workspaceHash, Schemas.file, filePathHash)).with({ scheme: Schemas.vscodeUserData }).toString();
assert.strictEqual(service.toBackupResource(backupId).toString(), expectedPath);
});
test('should get the correct backup path for untitled files', () => {
// Format should be: <backupHome>/<workspaceHash>/<scheme>/<filePathHash>
const backupResource = URI.from({ scheme: Schemas.untitled, path: 'Untitled-1' });
const workspaceHash = hash(workspaceResource.fsPath).toString(16);
// No Type ID
let backupId = toUntypedWorkingCopyId(backupResource);
let filePathHash = hashIdentifier(backupId);
let expectedPath = URI.file(join(backupHome, workspaceHash, Schemas.untitled, filePathHash)).with({ scheme: Schemas.vscodeUserData }).toString();
assert.strictEqual(service.toBackupResource(backupId).toString(), expectedPath);
// With Type ID
backupId = toTypedWorkingCopyId(backupResource);
filePathHash = hashIdentifier(backupId);
expectedPath = URI.file(join(backupHome, workspaceHash, Schemas.untitled, filePathHash)).with({ scheme: Schemas.vscodeUserData }).toString();
assert.strictEqual(service.toBackupResource(backupId).toString(), expectedPath);
});
test('should get the correct backup path for custom files', () => {
// Format should be: <backupHome>/<workspaceHash>/<scheme>/<filePathHash>
const backupResource = URI.from({ scheme: 'custom', path: 'custom/file.txt' });
const workspaceHash = hash(workspaceResource.fsPath).toString(16);
// No Type ID
let backupId = toUntypedWorkingCopyId(backupResource);
let filePathHash = hashIdentifier(backupId);
let expectedPath = URI.file(join(backupHome, workspaceHash, 'custom', filePathHash)).with({ scheme: Schemas.vscodeUserData }).toString();
assert.strictEqual(service.toBackupResource(backupId).toString(), expectedPath);
// With Type ID
backupId = toTypedWorkingCopyId(backupResource);
filePathHash = hashIdentifier(backupId);
expectedPath = URI.file(join(backupHome, workspaceHash, 'custom', filePathHash)).with({ scheme: Schemas.vscodeUserData }).toString();
assert.strictEqual(service.toBackupResource(backupId).toString(), expectedPath);
});
});
suite('backup', () => {
function toExpectedPreamble(identifier: IWorkingCopyIdentifier, content = '', meta?: object): string {
return `${identifier.resource.toString()} ${JSON.stringify({ ...meta, typeId: identifier.typeId })}\n${content}`;
}
test('joining', async () => {
let backupJoined = false;
const joinBackupsPromise = service.joinBackups();
joinBackupsPromise.then(() => backupJoined = true);
await joinBackupsPromise;
assert.strictEqual(backupJoined, true);
backupJoined = false;
service.joinBackups().then(() => backupJoined = true);
const identifier = toUntypedWorkingCopyId(fooFile);
const backupPath = join(workspaceBackupPath, identifier.resource.scheme, hashIdentifier(identifier));
const backupPromise = service.backup(identifier);
assert.strictEqual(backupJoined, false);
await backupPromise;
assert.strictEqual(backupJoined, true);
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 1);
assert.strictEqual(existsSync(backupPath), true);
assert.strictEqual(readFileSync(backupPath).toString(), toExpectedPreamble(identifier));
assert.ok(service.hasBackupSync(identifier));
});
test('no text', async () => {
const identifier = toUntypedWorkingCopyId(fooFile);
const backupPath = join(workspaceBackupPath, identifier.resource.scheme, hashIdentifier(identifier));
await service.backup(identifier);
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 1);
assert.strictEqual(existsSync(backupPath), true);
assert.strictEqual(readFileSync(backupPath).toString(), toExpectedPreamble(identifier));
assert.ok(service.hasBackupSync(identifier));
});
test('text file', async () => {
const identifier = toUntypedWorkingCopyId(fooFile);
const backupPath = join(workspaceBackupPath, identifier.resource.scheme, hashIdentifier(identifier));
await service.backup(identifier, bufferToReadable(VSBuffer.fromString('test')));
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 1);
assert.strictEqual(existsSync(backupPath), true);
assert.strictEqual(readFileSync(backupPath).toString(), toExpectedPreamble(identifier, 'test'));
assert.ok(service.hasBackupSync(identifier));
});
test('text file (with version)', async () => {
const identifier = toUntypedWorkingCopyId(fooFile);
const backupPath = join(workspaceBackupPath, identifier.resource.scheme, hashIdentifier(identifier));
await service.backup(identifier, bufferToReadable(VSBuffer.fromString('test')), 666);
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 1);
assert.strictEqual(existsSync(backupPath), true);
assert.strictEqual(readFileSync(backupPath).toString(), toExpectedPreamble(identifier, 'test'));
assert.ok(!service.hasBackupSync(identifier, 555));
assert.ok(service.hasBackupSync(identifier, 666));
});
test('text file (with meta)', async () => {
const identifier = toUntypedWorkingCopyId(fooFile);
const backupPath = join(workspaceBackupPath, identifier.resource.scheme, hashIdentifier(identifier));
const meta = { etag: '678', orphaned: true };
await service.backup(identifier, bufferToReadable(VSBuffer.fromString('test')), undefined, meta);
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 1);
assert.strictEqual(existsSync(backupPath), true);
assert.strictEqual(readFileSync(backupPath).toString(), toExpectedPreamble(identifier, 'test', meta));
assert.ok(service.hasBackupSync(identifier));
});
test('text file with whitespace in name and type (with meta)', async () => {
const fileWithSpace = URI.file(isWindows ? 'c:\\Foo \n Bar' : '/Foo \n Bar');
const identifier = toTypedWorkingCopyId(fileWithSpace, ' test id \n');
const backupPath = join(workspaceBackupPath, identifier.resource.scheme, hashIdentifier(identifier));
const meta = { etag: '678 \n k', orphaned: true };
await service.backup(identifier, bufferToReadable(VSBuffer.fromString('test')), undefined, meta);
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 1);
assert.strictEqual(existsSync(backupPath), true);
assert.strictEqual(readFileSync(backupPath).toString(), toExpectedPreamble(identifier, 'test', meta));
assert.ok(service.hasBackupSync(identifier));
});
test('text file with unicode character in name and type (with meta)', async () => {
const fileWithUnicode = URI.file(isWindows ? 'c:\\so𒀅meࠄ' : '/so𒀅meࠄ');
const identifier = toTypedWorkingCopyId(fileWithUnicode, ' test so𒀅meࠄ id \n');
const backupPath = join(workspaceBackupPath, identifier.resource.scheme, hashIdentifier(identifier));
const meta = { etag: '678so𒀅meࠄ', orphaned: true };
await service.backup(identifier, bufferToReadable(VSBuffer.fromString('test')), undefined, meta);
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 1);
assert.strictEqual(existsSync(backupPath), true);
assert.strictEqual(readFileSync(backupPath).toString(), toExpectedPreamble(identifier, 'test', meta));
assert.ok(service.hasBackupSync(identifier));
});
test('untitled file', async () => {
const identifier = toUntypedWorkingCopyId(untitledFile);
const backupPath = join(workspaceBackupPath, identifier.resource.scheme, hashIdentifier(identifier));
await service.backup(identifier, bufferToReadable(VSBuffer.fromString('test')));
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'untitled')).length, 1);
assert.strictEqual(existsSync(backupPath), true);
assert.strictEqual(readFileSync(backupPath).toString(), toExpectedPreamble(identifier, 'test'));
assert.ok(service.hasBackupSync(identifier));
});
test('text file (readable)', async () => {
const identifier = toUntypedWorkingCopyId(fooFile);
const backupPath = join(workspaceBackupPath, identifier.resource.scheme, hashIdentifier(identifier));
const model = createTextModel('test');
await service.backup(identifier, toBufferOrReadable(model.createSnapshot()));
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 1);
assert.strictEqual(existsSync(backupPath), true);
assert.strictEqual(readFileSync(backupPath).toString(), toExpectedPreamble(identifier, 'test'));
assert.ok(service.hasBackupSync(identifier));
model.dispose();
});
test('untitled file (readable)', async () => {
const identifier = toUntypedWorkingCopyId(untitledFile);
const backupPath = join(workspaceBackupPath, identifier.resource.scheme, hashIdentifier(identifier));
const model = createTextModel('test');
await service.backup(identifier, toBufferOrReadable(model.createSnapshot()));
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'untitled')).length, 1);
assert.strictEqual(existsSync(backupPath), true);
assert.strictEqual(readFileSync(backupPath).toString(), toExpectedPreamble(identifier, 'test'));
model.dispose();
});
test('text file (large file, stream)', () => {
const largeString = (new Array(30 * 1024)).join('Large String\n');
return testLargeTextFile(largeString, bufferToStream(VSBuffer.fromString(largeString)));
});
test('text file (large file, readable)', async () => {
const largeString = (new Array(30 * 1024)).join('Large String\n');
const model = createTextModel(largeString);
await testLargeTextFile(largeString, toBufferOrReadable(model.createSnapshot()));
model.dispose();
});
async function testLargeTextFile(largeString: string, buffer: VSBufferReadable | VSBufferReadableStream) {
const identifier = toUntypedWorkingCopyId(fooFile);
const backupPath = join(workspaceBackupPath, identifier.resource.scheme, hashIdentifier(identifier));
await service.backup(identifier, buffer, undefined, { largeTest: true });
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 1);
assert.strictEqual(existsSync(backupPath), true);
assert.strictEqual(readFileSync(backupPath).toString(), toExpectedPreamble(identifier, largeString, { largeTest: true }));
assert.ok(service.hasBackupSync(identifier));
}
test('untitled file (large file, readable)', async () => {
const identifier = toUntypedWorkingCopyId(untitledFile);
const backupPath = join(workspaceBackupPath, identifier.resource.scheme, hashIdentifier(identifier));
const largeString = (new Array(30 * 1024)).join('Large String\n');
const model = createTextModel(largeString);
await service.backup(identifier, toBufferOrReadable(model.createSnapshot()));
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'untitled')).length, 1);
assert.strictEqual(existsSync(backupPath), true);
assert.strictEqual(readFileSync(backupPath).toString(), toExpectedPreamble(identifier, largeString));
assert.ok(service.hasBackupSync(identifier));
model.dispose();
});
test('cancellation', async () => {
const identifier = toUntypedWorkingCopyId(fooFile);
const backupPath = join(workspaceBackupPath, identifier.resource.scheme, hashIdentifier(identifier));
const cts = new CancellationTokenSource();
const promise = service.backup(identifier, undefined, undefined, undefined, cts.token);
cts.cancel();
await promise;
assert.strictEqual(existsSync(backupPath), false);
assert.ok(!service.hasBackupSync(identifier));
});
test('multiple', async () => {
const identifier = toUntypedWorkingCopyId(fooFile);
const backupPath = join(workspaceBackupPath, identifier.resource.scheme, hashIdentifier(identifier));
await Promise.all([
service.backup(identifier),
service.backup(identifier),
service.backup(identifier),
service.backup(identifier)
]);
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 1);
assert.strictEqual(existsSync(backupPath), true);
assert.strictEqual(readFileSync(backupPath).toString(), toExpectedPreamble(identifier));
assert.ok(service.hasBackupSync(identifier));
});
test('multiple same resource, different type id', async () => {
const backupId1 = toUntypedWorkingCopyId(fooFile);
const backupId2 = toTypedWorkingCopyId(fooFile, 'type1');
const backupId3 = toTypedWorkingCopyId(fooFile, 'type2');
await Promise.all([
service.backup(backupId1),
service.backup(backupId2),
service.backup(backupId3)
]);
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 3);
for (const backupId of [backupId1, backupId2, backupId3]) {
const fooBackupPath = join(workspaceBackupPath, backupId.resource.scheme, hashIdentifier(backupId));
assert.strictEqual(existsSync(fooBackupPath), true);
assert.strictEqual(readFileSync(fooBackupPath).toString(), toExpectedPreamble(backupId));
assert.ok(service.hasBackupSync(backupId));
}
});
});
suite('discardBackup', () => {
test('joining', async () => {
const identifier = toUntypedWorkingCopyId(fooFile);
const backupPath = join(workspaceBackupPath, identifier.resource.scheme, hashIdentifier(identifier));
await service.backup(identifier, bufferToReadable(VSBuffer.fromString('test')));
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 1);
assert.ok(service.hasBackupSync(identifier));
let backupJoined = false;
service.joinBackups().then(() => backupJoined = true);
const discardBackupPromise = service.discardBackup(identifier);
assert.strictEqual(backupJoined, false);
await discardBackupPromise;
assert.strictEqual(backupJoined, true);
assert.strictEqual(existsSync(backupPath), false);
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 0);
assert.ok(!service.hasBackupSync(identifier));
});
test('text file', async () => {
const identifier = toUntypedWorkingCopyId(fooFile);
const backupPath = join(workspaceBackupPath, identifier.resource.scheme, hashIdentifier(identifier));
await service.backup(identifier, bufferToReadable(VSBuffer.fromString('test')));
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 1);
assert.ok(service.hasBackupSync(identifier));
await service.discardBackup(identifier);
assert.strictEqual(existsSync(backupPath), false);
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 0);
assert.ok(!service.hasBackupSync(identifier));
});
test('untitled file', async () => {
const identifier = toUntypedWorkingCopyId(untitledFile);
const backupPath = join(workspaceBackupPath, identifier.resource.scheme, hashIdentifier(identifier));
await service.backup(identifier, bufferToReadable(VSBuffer.fromString('test')));
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'untitled')).length, 1);
await service.discardBackup(identifier);
assert.strictEqual(existsSync(backupPath), false);
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'untitled')).length, 0);
});
test('multiple same resource, different type id', async () => {
const backupId1 = toUntypedWorkingCopyId(fooFile);
const backupId2 = toTypedWorkingCopyId(fooFile, 'type1');
const backupId3 = toTypedWorkingCopyId(fooFile, 'type2');
await Promise.all([
service.backup(backupId1),
service.backup(backupId2),
service.backup(backupId3)
]);
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 3);
for (const backupId of [backupId1, backupId2, backupId3]) {
const backupPath = join(workspaceBackupPath, backupId.resource.scheme, hashIdentifier(backupId));
await service.discardBackup(backupId);
assert.strictEqual(existsSync(backupPath), false);
}
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 0);
});
});
suite('discardBackups (all)', () => {
test('text file', async () => {
const backupId1 = toUntypedWorkingCopyId(fooFile);
const backupId2 = toUntypedWorkingCopyId(barFile);
const backupId3 = toTypedWorkingCopyId(barFile);
await service.backup(backupId1, bufferToReadable(VSBuffer.fromString('test')));
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 1);
await service.backup(backupId2, bufferToReadable(VSBuffer.fromString('test')));
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 2);
await service.backup(backupId3, bufferToReadable(VSBuffer.fromString('test')));
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 3);
await service.discardBackups();
for (const backupId of [backupId1, backupId2, backupId3]) {
const backupPath = join(workspaceBackupPath, backupId.resource.scheme, hashIdentifier(backupId));
assert.strictEqual(existsSync(backupPath), false);
}
assert.strictEqual(existsSync(join(workspaceBackupPath, 'file')), false);
});
test('untitled file', async () => {
const backupId = toUntypedWorkingCopyId(untitledFile);
const backupPath = join(workspaceBackupPath, backupId.resource.scheme, hashIdentifier(backupId));
await service.backup(backupId, bufferToReadable(VSBuffer.fromString('test')));
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'untitled')).length, 1);
await service.discardBackups();
assert.strictEqual(existsSync(backupPath), false);
assert.strictEqual(existsSync(join(workspaceBackupPath, 'untitled')), false);
});
test('can backup after discarding all', async () => {
await service.discardBackups();
await service.backup(toUntypedWorkingCopyId(untitledFile), bufferToReadable(VSBuffer.fromString('test')));
assert.strictEqual(existsSync(workspaceBackupPath), true);
});
});
suite('discardBackups (except some)', () => {
test('text file', async () => {
const backupId1 = toUntypedWorkingCopyId(fooFile);
const backupId2 = toUntypedWorkingCopyId(barFile);
const backupId3 = toTypedWorkingCopyId(barFile);
await service.backup(backupId1, bufferToReadable(VSBuffer.fromString('test')));
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 1);
await service.backup(backupId2, bufferToReadable(VSBuffer.fromString('test')));
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 2);
await service.backup(backupId3, bufferToReadable(VSBuffer.fromString('test')));
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'file')).length, 3);
await service.discardBackups({ except: [backupId2, backupId3] });
let backupPath = join(workspaceBackupPath, backupId1.resource.scheme, hashIdentifier(backupId1));
assert.strictEqual(existsSync(backupPath), false);
backupPath = join(workspaceBackupPath, backupId2.resource.scheme, hashIdentifier(backupId2));
assert.strictEqual(existsSync(backupPath), true);
backupPath = join(workspaceBackupPath, backupId3.resource.scheme, hashIdentifier(backupId3));
assert.strictEqual(existsSync(backupPath), true);
await service.discardBackups({ except: [backupId1] });
for (const backupId of [backupId1, backupId2, backupId3]) {
const backupPath = join(workspaceBackupPath, backupId.resource.scheme, hashIdentifier(backupId));
assert.strictEqual(existsSync(backupPath), false);
}
});
test('untitled file', async () => {
const backupId = toUntypedWorkingCopyId(untitledFile);
const backupPath = join(workspaceBackupPath, backupId.resource.scheme, hashIdentifier(backupId));
await service.backup(backupId, bufferToReadable(VSBuffer.fromString('test')));
assert.strictEqual(existsSync(backupPath), true);
assert.strictEqual(readdirSync(join(workspaceBackupPath, 'untitled')).length, 1);
await service.discardBackups({ except: [backupId] });
assert.strictEqual(existsSync(backupPath), true);
});
});
suite('getBackups', () => {
test('text file', async () => {
await Promise.all([
service.backup(toUntypedWorkingCopyId(fooFile), bufferToReadable(VSBuffer.fromString('test'))),
service.backup(toTypedWorkingCopyId(fooFile, 'type1'), bufferToReadable(VSBuffer.fromString('test'))),
service.backup(toTypedWorkingCopyId(fooFile, 'type2'), bufferToReadable(VSBuffer.fromString('test')))
]);
let backups = await service.getBackups();
assert.strictEqual(backups.length, 3);
for (const backup of backups) {
if (backup.typeId === '') {
assert.strictEqual(backup.resource.toString(), fooFile.toString());
} else if (backup.typeId === 'type1') {
assert.strictEqual(backup.resource.toString(), fooFile.toString());
} else if (backup.typeId === 'type2') {
assert.strictEqual(backup.resource.toString(), fooFile.toString());
} else {
assert.fail('Unexpected backup');
}
}
await service.backup(toUntypedWorkingCopyId(barFile), bufferToReadable(VSBuffer.fromString('test')));
backups = await service.getBackups();
assert.strictEqual(backups.length, 4);
});
test('untitled file', async () => {
await Promise.all([
service.backup(toUntypedWorkingCopyId(untitledFile), bufferToReadable(VSBuffer.fromString('test'))),
service.backup(toTypedWorkingCopyId(untitledFile, 'type1'), bufferToReadable(VSBuffer.fromString('test'))),
service.backup(toTypedWorkingCopyId(untitledFile, 'type2'), bufferToReadable(VSBuffer.fromString('test')))
]);
const backups = await service.getBackups();
assert.strictEqual(backups.length, 3);
for (const backup of backups) {
if (backup.typeId === '') {
assert.strictEqual(backup.resource.toString(), untitledFile.toString());
} else if (backup.typeId === 'type1') {
assert.strictEqual(backup.resource.toString(), untitledFile.toString());
} else if (backup.typeId === 'type2') {
assert.strictEqual(backup.resource.toString(), untitledFile.toString());
} else {
assert.fail('Unexpected backup');
}
}
});
});
suite('resolve', () => {
interface IBackupTestMetaData extends IWorkingCopyBackupMeta {
mtime?: number;
size?: number;
etag?: string;
orphaned?: boolean;
}
test('should restore the original contents (untitled file)', async () => {
const contents = 'test\nand more stuff';
await testResolveBackup(untitledFile, contents);
});
test('should restore the original contents (untitled file with metadata)', async () => {
const contents = 'test\nand more stuff';
const meta = {
etag: 'the Etag',
size: 666,
mtime: Date.now(),
orphaned: true
};
await testResolveBackup(untitledFile, contents, meta);
});
test('should restore the original contents (untitled file empty with metadata)', async () => {
const contents = '';
const meta = {
etag: 'the Etag',
size: 666,
mtime: Date.now(),
orphaned: true
};
await testResolveBackup(untitledFile, contents, meta);
});
test('should restore the original contents (untitled large file with metadata)', async () => {
const contents = (new Array(30 * 1024)).join('Large String\n');
const meta = {
etag: 'the Etag',
size: 666,
mtime: Date.now(),
orphaned: true
};
await testResolveBackup(untitledFile, contents, meta);
});
test('should restore the original contents (text file)', async () => {
const contents = [
'Lorem ipsum ',
'dolor öäü sit amet ',
'consectetur ',
'adipiscing ßß elit'
].join('');
await testResolveBackup(fooFile, contents);
});
test('should restore the original contents (text file - custom scheme)', async () => {
const contents = [
'Lorem ipsum ',
'dolor öäü sit amet ',
'consectetur ',
'adipiscing ßß elit'
].join('');
await testResolveBackup(customFile, contents);
});
test('should restore the original contents (text file with metadata)', async () => {
const contents = [
'Lorem ipsum ',
'dolor öäü sit amet ',
'adipiscing ßß elit',
'consectetur '
].join('');
const meta = {
etag: 'theEtag',
size: 888,
mtime: Date.now(),
orphaned: false
};
await testResolveBackup(fooFile, contents, meta);
});
test('should restore the original contents (empty text file with metadata)', async () => {
const contents = '';
const meta = {
etag: 'theEtag',
size: 888,
mtime: Date.now(),
orphaned: false
};
await testResolveBackup(fooFile, contents, meta);
});
test('should restore the original contents (large text file with metadata)', async () => {
const contents = (new Array(30 * 1024)).join('Large String\n');
const meta = {
etag: 'theEtag',
size: 888,
mtime: Date.now(),
orphaned: false
};
await testResolveBackup(fooFile, contents, meta);
});
test('should restore the original contents (text file with metadata changed once)', async () => {
const contents = [
'Lorem ipsum ',
'dolor öäü sit amet ',
'adipiscing ßß elit',
'consectetur '
].join('');
const meta = {
etag: 'theEtag',
size: 888,
mtime: Date.now(),
orphaned: false
};
await testResolveBackup(fooFile, contents, meta);
// Change meta and test again
meta.size = 999;
await testResolveBackup(fooFile, contents, meta);
});
test('should restore the original contents (text file with metadata and fragment URI)', async () => {
const contents = [
'Lorem ipsum ',
'dolor öäü sit amet ',
'adipiscing ßß elit',
'consectetur '
].join('');
const meta = {
etag: 'theEtag',
size: 888,
mtime: Date.now(),
orphaned: false
};
await testResolveBackup(customFileWithFragment, contents, meta);
});
test('should restore the original contents (text file with space in name with metadata)', async () => {
const contents = [
'Lorem ipsum ',
'dolor öäü sit amet ',
'adipiscing ßß elit',
'consectetur '
].join('');
const meta = {
etag: 'theEtag',
size: 888,
mtime: Date.now(),
orphaned: false
};
await testResolveBackup(fooBarFile, contents, meta);
});
test('should restore the original contents (text file with too large metadata to persist)', async () => {
const contents = [
'Lorem ipsum ',
'dolor öäü sit amet ',
'adipiscing ßß elit',
'consectetur '
].join('');
const meta = {
etag: (new Array(100 * 1024)).join('Large String'),
size: 888,
mtime: Date.now(),
orphaned: false
};
await testResolveBackup(fooFile, contents, meta, true);
});
async function testResolveBackup(resource: URI, contents: string, meta?: IBackupTestMetaData, expectNoMeta?: boolean) {
await doTestResolveBackup(toUntypedWorkingCopyId(resource), contents, meta, expectNoMeta);
await doTestResolveBackup(toTypedWorkingCopyId(resource), contents, meta, expectNoMeta);
}
async function doTestResolveBackup(identifier: IWorkingCopyIdentifier, contents: string, meta?: IBackupTestMetaData, expectNoMeta?: boolean) {
await service.backup(identifier, bufferToReadable(VSBuffer.fromString(contents)), 1, meta);
const backup = await service.resolve<IBackupTestMetaData>(identifier);
assert.ok(backup);
assert.strictEqual(contents, (await streamToBuffer(backup.value)).toString());
if (expectNoMeta || !meta) {
assert.strictEqual(backup.meta, undefined);
} else {
assert.ok(backup.meta);
assert.strictEqual(backup.meta.etag, meta.etag);
assert.strictEqual(backup.meta.size, meta.size);
assert.strictEqual(backup.meta.mtime, meta.mtime);
assert.strictEqual(backup.meta.orphaned, meta.orphaned);
assert.strictEqual(Object.keys(meta).length, Object.keys(backup.meta).length);
}
}
test('should restore the original contents (text file with broken metadata)', async () => {
await testShouldRestoreOriginalContentsWithBrokenBackup(toUntypedWorkingCopyId(fooFile));
await testShouldRestoreOriginalContentsWithBrokenBackup(toTypedWorkingCopyId(fooFile));
});
async function testShouldRestoreOriginalContentsWithBrokenBackup(identifier: IWorkingCopyIdentifier): Promise<void> {
const contents = [
'Lorem ipsum ',
'dolor öäü sit amet ',
'adipiscing ßß elit',
'consectetur '
].join('');
const meta = {
etag: 'theEtag',
size: 888,
mtime: Date.now(),
orphaned: false
};
await service.backup(identifier, bufferToReadable(VSBuffer.fromString(contents)), 1, meta);
const backupPath = join(workspaceBackupPath, identifier.resource.scheme, hashIdentifier(identifier));
const fileContents = readFileSync(backupPath).toString();
assert.strictEqual(fileContents.indexOf(identifier.resource.toString()), 0);
const metaIndex = fileContents.indexOf('{');
const newFileContents = fileContents.substring(0, metaIndex) + '{{' + fileContents.substr(metaIndex);
writeFileSync(backupPath, newFileContents);
const backup = await service.resolve(identifier);
assert.ok(backup);
assert.strictEqual(contents, (await streamToBuffer(backup.value)).toString());
assert.strictEqual(backup.meta, undefined);
}
test('should update metadata from file into model when resolving', async () => {
await testShouldUpdateMetaFromFileWhenResolving(toUntypedWorkingCopyId(fooFile));
await testShouldUpdateMetaFromFileWhenResolving(toTypedWorkingCopyId(fooFile));
});
async function testShouldUpdateMetaFromFileWhenResolving(identifier: IWorkingCopyIdentifier): Promise<void> {
const contents = 'Foo Bar';
const meta = {
etag: 'theEtagForThisMetadataTest',
size: 888,
mtime: Date.now(),
orphaned: false
};
const updatedMeta = {
...meta,
etag: meta.etag + meta.etag
};
await service.backup(identifier, bufferToReadable(VSBuffer.fromString(contents)), 1, meta);
const backupPath = join(workspaceBackupPath, identifier.resource.scheme, hashIdentifier(identifier));
// Simulate the condition of the backups model loading initially without
// meta data information and then getting the meta data updated on the
// first call to resolve the backup. We simulate this by explicitly changing
// the meta data in the file and then verifying that the updated meta data
// is persisted back into the model (verified via `hasBackupSync`).
// This is not really something that would happen in real life because any
// backup that is made via backup service will update the model accordingly.
const originalFileContents = readFileSync(backupPath).toString();
writeFileSync(backupPath, originalFileContents.replace(meta.etag, updatedMeta.etag));
await service.resolve(identifier);
assert.strictEqual(service.hasBackupSync(identifier, undefined, meta), false);
assert.strictEqual(service.hasBackupSync(identifier, undefined, updatedMeta), true);
writeFileSync(backupPath, originalFileContents);
await service.getBackups();
assert.strictEqual(service.hasBackupSync(identifier, undefined, meta), true);
assert.strictEqual(service.hasBackupSync(identifier, undefined, updatedMeta), false);
}
test('should ignore invalid backups (empty file)', async () => {
const contents = 'test\nand more stuff';
await service.backup(toUntypedWorkingCopyId(fooFile), bufferToReadable(VSBuffer.fromString(contents)), 1);
let backup = await service.resolve(toUntypedWorkingCopyId(fooFile));
assert.ok(backup);
await service.fileService.writeFile(service.toBackupResource(toUntypedWorkingCopyId(fooFile)), VSBuffer.fromString(''));
backup = await service.resolve<IBackupTestMetaData>(toUntypedWorkingCopyId(fooFile));
assert.ok(!backup);
});
test('should ignore invalid backups (no preamble)', async () => {
const contents = 'testand more stuff';
await service.backup(toUntypedWorkingCopyId(fooFile), bufferToReadable(VSBuffer.fromString(contents)), 1);
let backup = await service.resolve(toUntypedWorkingCopyId(fooFile));
assert.ok(backup);
await service.fileService.writeFile(service.toBackupResource(toUntypedWorkingCopyId(fooFile)), VSBuffer.fromString(contents));
backup = await service.resolve<IBackupTestMetaData>(toUntypedWorkingCopyId(fooFile));
assert.ok(!backup);
});
test('file with binary data', async () => {
const identifier = toUntypedWorkingCopyId(fooFile);
const sourceDir = getPathFromAmdModule(require, './fixtures');
const buffer = await Promises.readFile(join(sourceDir, 'binary.txt'));
const hash = createHash('md5').update(buffer).digest('base64');
await service.backup(identifier, bufferToReadable(VSBuffer.wrap(buffer)), undefined, { binaryTest: 'true' });
const backup = await service.resolve(toUntypedWorkingCopyId(fooFile));
assert.ok(backup);
const backupBuffer = await consumeStream(backup.value, chunks => VSBuffer.concat(chunks));
assert.strictEqual(backupBuffer.buffer.byteLength, buffer.byteLength);
const backupHash = createHash('md5').update(backupBuffer.buffer).digest('base64');
assert.strictEqual(hash, backupHash);
});
});
suite('WorkingCopyBackupsModel', () => {
test('simple', async () => {
const model = await WorkingCopyBackupsModel.create(URI.file(workspaceBackupPath), service.fileService);
const resource1 = URI.file('test.html');
assert.strictEqual(model.has(resource1), false);
model.add(resource1);
assert.strictEqual(model.has(resource1), true);
assert.strictEqual(model.has(resource1, 0), true);
assert.strictEqual(model.has(resource1, 1), false);
assert.strictEqual(model.has(resource1, 1, { foo: 'bar' }), false);
model.remove(resource1);
assert.strictEqual(model.has(resource1), false);
model.add(resource1);
assert.strictEqual(model.has(resource1), true);
assert.strictEqual(model.has(resource1, 0), true);
assert.strictEqual(model.has(resource1, 1), false);
model.clear();
assert.strictEqual(model.has(resource1), false);
model.add(resource1, 1);
assert.strictEqual(model.has(resource1), true);
assert.strictEqual(model.has(resource1, 0), false);
assert.strictEqual(model.has(resource1, 1), true);
const resource2 = URI.file('test1.html');
const resource3 = URI.file('test2.html');
const resource4 = URI.file('test3.html');
model.add(resource2);
model.add(resource3);
model.add(resource4, undefined, { foo: 'bar' });
assert.strictEqual(model.has(resource1), true);
assert.strictEqual(model.has(resource2), true);
assert.strictEqual(model.has(resource3), true);
assert.strictEqual(model.has(resource4), true);
assert.strictEqual(model.has(resource4, undefined, { foo: 'bar' }), true);
assert.strictEqual(model.has(resource4, undefined, { bar: 'foo' }), false);
model.update(resource4, { foo: 'nothing' });
assert.strictEqual(model.has(resource4, undefined, { foo: 'nothing' }), true);
assert.strictEqual(model.has(resource4, undefined, { foo: 'bar' }), false);
model.update(resource4);
assert.strictEqual(model.has(resource4), true);
assert.strictEqual(model.has(resource4, undefined, { foo: 'nothing' }), false);
const resource5 = URI.file('test4.html');
model.move(resource4, resource5);
assert.strictEqual(model.has(resource4), false);
assert.strictEqual(model.has(resource5), true);
});
test('create', async () => {
const fooBackupPath = join(workspaceBackupPath, fooFile.scheme, hashIdentifier(toUntypedWorkingCopyId(fooFile)));
await Promises.mkdir(dirname(fooBackupPath), { recursive: true });
writeFileSync(fooBackupPath, 'foo');
const model = await WorkingCopyBackupsModel.create(URI.file(workspaceBackupPath), service.fileService);
assert.strictEqual(model.has(URI.file(fooBackupPath)), true);
});
test('get', async () => {
const model = await WorkingCopyBackupsModel.create(URI.file(workspaceBackupPath), service.fileService);
assert.deepStrictEqual(model.get(), []);
const file1 = URI.file('/root/file/foo.html');
const file2 = URI.file('/root/file/bar.html');
const untitled = URI.file('/root/untitled/bar.html');
model.add(file1);
model.add(file2);
model.add(untitled);
assert.deepStrictEqual(model.get().map(f => f.fsPath), [file1.fsPath, file2.fsPath, untitled.fsPath]);
});
});
suite('Hash migration', () => {
test('works', async () => {
const fooBackupId = toUntypedWorkingCopyId(fooFile);
const untitledBackupId = toUntypedWorkingCopyId(untitledFile);
const customBackupId = toUntypedWorkingCopyId(customFile);
const fooBackupPath = join(workspaceBackupPath, fooFile.scheme, hashIdentifier(fooBackupId));
const untitledBackupPath = join(workspaceBackupPath, untitledFile.scheme, hashIdentifier(untitledBackupId));
const customFileBackupPath = join(workspaceBackupPath, customFile.scheme, hashIdentifier(customBackupId));
// Prepare backups of the old MD5 hash format
mkdirSync(join(workspaceBackupPath, fooFile.scheme), { recursive: true });
mkdirSync(join(workspaceBackupPath, untitledFile.scheme), { recursive: true });
mkdirSync(join(workspaceBackupPath, customFile.scheme), { recursive: true });
writeFileSync(join(workspaceBackupPath, fooFile.scheme, '8a8589a2f1c9444b89add38166f50229'), `${fooFile.toString()}\ntest file`);
writeFileSync(join(workspaceBackupPath, untitledFile.scheme, '13264068d108c6901b3592ea654fcd57'), `${untitledFile.toString()}\ntest untitled`);
writeFileSync(join(workspaceBackupPath, customFile.scheme, 'bf018572af7b38746b502893bd0adf6c'), `${customFile.toString()}\ntest custom`);
service.reinitialize(URI.file(workspaceBackupPath));
const backups = await service.getBackups();
assert.strictEqual(backups.length, 3);
assert.ok(backups.some(backup => isEqual(backup.resource, fooFile)));
assert.ok(backups.some(backup => isEqual(backup.resource, untitledFile)));
assert.ok(backups.some(backup => isEqual(backup.resource, customFile)));
assert.strictEqual(readdirSync(join(workspaceBackupPath, fooFile.scheme)).length, 1);
assert.strictEqual(existsSync(fooBackupPath), true);
assert.strictEqual(readFileSync(fooBackupPath).toString(), `${fooFile.toString()}\ntest file`);
assert.ok(service.hasBackupSync(fooBackupId));
assert.strictEqual(readdirSync(join(workspaceBackupPath, untitledFile.scheme)).length, 1);
assert.strictEqual(existsSync(untitledBackupPath), true);
assert.strictEqual(readFileSync(untitledBackupPath).toString(), `${untitledFile.toString()}\ntest untitled`);
assert.ok(service.hasBackupSync(untitledBackupId));
assert.strictEqual(readdirSync(join(workspaceBackupPath, customFile.scheme)).length, 1);
assert.strictEqual(existsSync(customFileBackupPath), true);
assert.strictEqual(readFileSync(customFileBackupPath).toString(), `${customFile.toString()}\ntest custom`);
assert.ok(service.hasBackupSync(customBackupId));
});
});
suite('typeId migration', () => {
test('works (when meta is missing)', async () => {
const fooBackupId = toUntypedWorkingCopyId(fooFile);
const untitledBackupId = toUntypedWorkingCopyId(untitledFile);
const customBackupId = toUntypedWorkingCopyId(customFile);
const fooBackupPath = join(workspaceBackupPath, fooFile.scheme, hashIdentifier(fooBackupId));
const untitledBackupPath = join(workspaceBackupPath, untitledFile.scheme, hashIdentifier(untitledBackupId));
const customFileBackupPath = join(workspaceBackupPath, customFile.scheme, hashIdentifier(customBackupId));
// Prepare backups of the old format without meta
mkdirSync(join(workspaceBackupPath, fooFile.scheme), { recursive: true });
mkdirSync(join(workspaceBackupPath, untitledFile.scheme), { recursive: true });
mkdirSync(join(workspaceBackupPath, customFile.scheme), { recursive: true });
writeFileSync(fooBackupPath, `${fooFile.toString()}\ntest file`);
writeFileSync(untitledBackupPath, `${untitledFile.toString()}\ntest untitled`);
writeFileSync(customFileBackupPath, `${customFile.toString()}\ntest custom`);
service.reinitialize(URI.file(workspaceBackupPath));
const backups = await service.getBackups();
assert.strictEqual(backups.length, 3);
assert.ok(backups.some(backup => isEqual(backup.resource, fooFile)));
assert.ok(backups.some(backup => isEqual(backup.resource, untitledFile)));
assert.ok(backups.some(backup => isEqual(backup.resource, customFile)));
assert.ok(backups.every(backup => backup.typeId === ''));
});
test('works (when typeId in meta is missing)', async () => {
const fooBackupId = toUntypedWorkingCopyId(fooFile);
const untitledBackupId = toUntypedWorkingCopyId(untitledFile);
const customBackupId = toUntypedWorkingCopyId(customFile);
const fooBackupPath = join(workspaceBackupPath, fooFile.scheme, hashIdentifier(fooBackupId));
const untitledBackupPath = join(workspaceBackupPath, untitledFile.scheme, hashIdentifier(untitledBackupId));
const customFileBackupPath = join(workspaceBackupPath, customFile.scheme, hashIdentifier(customBackupId));
// Prepare backups of the old format without meta
mkdirSync(join(workspaceBackupPath, fooFile.scheme), { recursive: true });
mkdirSync(join(workspaceBackupPath, untitledFile.scheme), { recursive: true });
mkdirSync(join(workspaceBackupPath, customFile.scheme), { recursive: true });
writeFileSync(fooBackupPath, `${fooFile.toString()} ${JSON.stringify({ foo: 'bar' })}\ntest file`);
writeFileSync(untitledBackupPath, `${untitledFile.toString()} ${JSON.stringify({ foo: 'bar' })}\ntest untitled`);
writeFileSync(customFileBackupPath, `${customFile.toString()} ${JSON.stringify({ foo: 'bar' })}\ntest custom`);
service.reinitialize(URI.file(workspaceBackupPath));
const backups = await service.getBackups();
assert.strictEqual(backups.length, 3);
assert.ok(backups.some(backup => isEqual(backup.resource, fooFile)));
assert.ok(backups.some(backup => isEqual(backup.resource, untitledFile)));
assert.ok(backups.some(backup => isEqual(backup.resource, customFile)));
assert.ok(backups.every(backup => backup.typeId === ''));
});
});
}); | the_stack |
export type URLProtocol = 'http' | 'https' | 'ftp' | string;
export type UUIDVersion = 1 | 2 | 3 | 4 | 5 | '1' | '2' | '3' | '4' | '5' | 'all';
export type IPVersion = 4 | 6;
export type AlphaLocale =
| 'ar'
| 'ar-AE'
| 'ar-BH'
| 'ar-DZ'
| 'ar-EG'
| 'ar-IQ'
| 'ar-JO'
| 'ar-KW'
| 'ar-LB'
| 'ar-LY'
| 'ar-MA'
| 'ar-QA'
| 'ar-QM'
| 'ar-SA'
| 'ar-SD'
| 'ar-SY'
| 'ar-TN'
| 'ar-YE'
| 'az-AZ'
| 'bg-BG'
| 'cs-CZ'
| 'da-DK'
| 'de-DE'
| 'el-GR'
| 'en-AU'
| 'en-GB'
| 'en-HK'
| 'en-IN'
| 'en-NZ'
| 'en-US'
| 'en-ZA'
| 'en-ZM'
| 'es-ES'
| 'fa-AF'
| 'fa-IR'
| 'fi-FI'
| 'fr-FR'
| 'he'
| 'hi-IN'
| 'hu-HU'
| 'id-ID'
| 'it-IT'
| 'ku-IQ'
| 'nb-NO'
| 'nl-NL'
| 'nn-NO'
| 'pl-PL'
| 'pt-BR'
| 'pt-PT'
| 'ru-RU'
| 'sk-SK'
| 'sl-SI'
| 'sr-RS'
| 'sr-RS@latin'
| 'sv-SE'
| 'th-TH'
| 'tr-TR'
| 'uk-UA'
| 'vi-VN';
export type AlphanumericLocale =
| 'ar'
| 'ar-AE'
| 'ar-BH'
| 'ar-DZ'
| 'ar-EG'
| 'ar-IQ'
| 'ar-JO'
| 'ar-KW'
| 'ar-LB'
| 'ar-LY'
| 'ar-MA'
| 'ar-QA'
| 'ar-QM'
| 'ar-SA'
| 'ar-SD'
| 'ar-SY'
| 'ar-TN'
| 'ar-YE'
| 'az-AZ'
| 'bg-BG'
| 'cs-CZ'
| 'da-DK'
| 'de-DE'
| 'el-GR'
| 'en-AU'
| 'en-GB'
| 'en-HK'
| 'en-IN'
| 'en-NZ'
| 'en-US'
| 'en-ZA'
| 'en-ZM'
| 'es-ES'
| 'fa-AF'
| 'fa-IR'
| 'fi-FI'
| 'fr-FR'
| 'fr-BE'
| 'he'
| 'hi-IN'
| 'hu-HU'
| 'it-IT'
| 'id-ID'
| 'ku-IQ'
| 'nb-NO'
| 'nl-BE'
| 'nl-NL'
| 'nn-NO'
| 'pl-PL'
| 'pt-BR'
| 'pt-PT'
| 'ru-RU'
| 'sk-SK'
| 'sl-SI'
| 'sr-RS'
| 'sr-RS@latin'
| 'sv-SE'
| 'th-TH'
| 'tr-TR'
| 'uk-UA'
| 'vi-VN';
export type MobilePhoneLocale =
| 'any'
| 'am-AM'
| 'ar-AE'
| 'ar-BH'
| 'ar-DZ'
| 'ar-EG'
| 'ar-IQ'
| 'ar-JO'
| 'ar-KW'
| 'ar-LB'
| 'ar-LY'
| 'ar-MA'
| 'ar-OM'
| 'ar-PS'
| 'ar-SA'
| 'ar-SY'
| 'ar-TN'
| 'az-AZ'
| 'be-BY'
| 'bg-BG'
| 'bn-BD'
| 'bs-BA'
| 'cs-CZ'
| 'de-AT'
| 'de-CH'
| 'de-DE'
| 'de-LU'
| 'da-DK'
| 'dz-BT'
| 'el-GR'
| 'en-AU'
| 'en-BM'
| 'en-BW'
| 'en-CA'
| 'en-GB'
| 'en-GG'
| 'en-GH'
| 'en-GY'
| 'en-HK'
| 'en-HN'
| 'en-IE'
| 'en-IN'
| 'en-KE'
| 'en-KI'
| 'en-MT'
| 'en-MU'
| 'en-NA'
| 'en-NG'
| 'en-NZ'
| 'en-PH'
| 'en-PK'
| 'en-RW'
| 'en-SG'
| 'en-SL'
| 'en-TZ'
| 'en-UG'
| 'en-US'
| 'en-ZA'
| 'en-ZM'
| 'en-ZW'
| 'es-AR'
| 'es-BO'
| 'es-CL'
| 'es-CO'
| 'es-CR'
| 'es-CU'
| 'es-DO'
| 'es-EC'
| 'es-ES'
| 'es-MX'
| 'es-PA'
| 'es-PE'
| 'es-PY'
| 'es-SV'
| 'es-UY'
| 'es-VE'
| 'et-EE'
| 'fa-IR'
| 'fi-FI'
| 'fj-FJ'
| 'fo-FO'
| 'fr-BE'
| 'fr-BF'
| 'fr-CH'
| 'fr-CM'
| 'fr-FR'
| 'fr-GF'
| 'fr-GP'
| 'fr-MQ'
| 'fr-PF'
| 'fr-RE'
| 'ga-IE'
| 'he-IL'
| 'hu-HU'
| 'id-ID'
| 'it-CH'
| 'it-IT'
| 'it-SM'
| 'ja-JP'
| 'ka-GE'
| 'kk-KZ'
| 'kl-GL'
| 'lt-LT'
| 'lv-LV'
| 'ms-MY'
| 'mz-MZ'
| 'nb-NO'
| 'nl-BE'
| 'nl-NL'
| 'ne-NP'
| 'nn-NO'
| 'pl-PL'
| 'pt-AO'
| 'pt-BR'
| 'pt-PT'
| 'ro-RO'
| 'ru-RU'
| 'si-LK'
| 'sk-SK'
| 'sl-SI'
| 'sq-AL'
| 'sr-RS'
| 'sv-SE'
| 'tg-TJ'
| 'th-TH'
| 'tk-TM'
| 'tr-TR'
| 'uk-UA'
| 'uz-Uz'
| 'vi-VN'
| 'zh-CN'
| 'zh-HK'
| 'zh-TW';
export type PostalCodeLocale =
| 'any'
| 'AD'
| 'AT'
| 'AU'
| 'AZ'
| 'BE'
| 'BG'
| 'BR'
| 'BY'
| 'CA'
| 'CH'
| 'CN'
| 'CZ'
| 'DE'
| 'DK'
| 'DO'
| 'DZ'
| 'EE'
| 'ES'
| 'FI'
| 'FR'
| 'GB'
| 'GR'
| 'HR'
| 'HT'
| 'HU'
| 'ID'
| 'IL'
| 'IN'
| 'IR'
| 'IS'
| 'IT'
| 'JP'
| 'KE'
| 'KR'
| 'LI'
| 'LK'
| 'LT'
| 'LU'
| 'LV'
| 'MT'
| 'MX'
| 'MY'
| 'NL'
| 'NO'
| 'NP'
| 'NZ'
| 'PL'
| 'PR'
| 'PT'
| 'RO'
| 'RU'
| 'SA'
| 'SE'
| 'SG'
| 'SI'
| 'SK'
| 'TH'
| 'TN'
| 'TW'
| 'UA'
| 'US'
| 'ZA'
| 'ZM';
export type HashAlgorithm =
| 'md4'
| 'md5'
| 'sha1'
| 'sha256'
| 'sha384'
| 'sha512'
| 'ripemd128'
| 'ripemd160'
| 'tiger128'
| 'tiger160'
| 'tiger192'
| 'crc32'
| 'crc32b';
export type IdentityCardLocale =
| 'any'
| 'ar-LY'
| 'ar-TN'
| 'ES'
| 'FI'
| 'he-IL'
| 'IN'
| 'IT'
| 'IR'
| 'MZ'
| 'NO'
| 'PL'
| 'TH'
| 'zh-CN'
| 'zh-TW';
export type PassportCountryCode =
| 'AM'
| 'AR'
| 'AT'
| 'AU'
| 'BE'
| 'BG'
| 'BY'
| 'BR'
| 'CA'
| 'CH'
| 'CN'
| 'CY'
| 'CZ'
| 'DE'
| 'DK'
| 'DZ'
| 'EE'
| 'ES'
| 'FI'
| 'FR'
| 'GB'
| 'GR'
| 'HR'
| 'HU'
| 'ID'
| 'IE'
| 'IN'
| 'IR'
| 'IS'
| 'IT'
| 'JP'
| 'KR'
| 'LT'
| 'LU'
| 'LV'
| 'LY'
| 'MT'
| 'MY'
| 'MZ'
| 'NL'
| 'PL'
| 'PO'
| 'PT'
| 'RO'
| 'RU'
| 'SE'
| 'SL'
| 'SK'
| 'TR'
| 'UA'
| 'US';
export type IsLicensePlateLocale =
| 'cs-CZ'
| 'de-DE'
| 'de-LI'
| 'fi-FI'
| 'pt-BR'
| 'pt-PT'
| 'sq-AL'
| 'any';
export type TaxIDLocale =
| 'bg-BG'
| 'cs-CZ'
| 'de-AT'
| 'de-DE'
| 'dk-DK'
| 'el-CY'
| 'el-GR'
| 'en-GB'
| 'en-IE'
| 'en-US'
| 'es-ES'
| 'et-EE'
| 'fi-FI'
| 'fr-BE'
| 'fr-FR'
| 'fr-LU'
| 'hr-HR'
| 'hu-HU'
| 'it-IT'
| 'lb-LU'
| 'lt-LT'
| 'lv-LV'
| 'mt-MT'
| 'nl-BE'
| 'nl-NL'
| 'pl-PL'
| 'pt-BR'
| 'pt-PT'
| 'ro-RO'
| 'sk-SK'
| 'sl-SI'
| 'sv-SE';
export type VATCountryCode = 'GB' | 'IT' | 'NL';
export interface MinMaxOptions {
min?: number;
max?: number;
}
export interface MinMaxExtendedOptions extends MinMaxOptions {
lt?: number;
gt?: number;
}
/**
* defaults to
* {
* ignoreCase: false,
* minOccurrences: 1
* }
*/
export interface ContainsOptions {
ignoreCase?: boolean;
minOccurrences?: number;
}
export interface IsAlphaOptions {
// TODO(v7): remove string[] support
ignore?: string | string[] | RegExp;
}
export interface IsAlphanumericOptions {
ignore?: string | RegExp;
}
/**
* defaults to
* {
* urlSafe: false
* }
*/
export interface IsBase64Options {
urlSafe?: boolean;
}
/**
* defaults to
* {
* strict: false
* loose: false
* }
*/
export interface IsBooleanOptions {
strict?: boolean;
loose?: boolean;
}
/**
* defaults to
* {
* symbol: '$',
* require_symbol: false,
* allow_space_after_symbol: false,
* symbol_after_digits: false,
* allow_negatives: true,
* parens_for_negatives: false,
* negative_sign_before_digits: false,
* negative_sign_after_digits: false,
* allow_negative_sign_placeholder: false,
* thousands_separator: ',',
* decimal_separator: '.',
* allow_space_after_digits: false
* }
*/
export interface IsCurrencyOptions {
symbol?: string;
require_symbol?: boolean;
allow_space_after_symbol?: boolean;
symbol_after_digits?: boolean;
allow_negatives?: boolean;
parens_for_negatives?: boolean;
negative_sign_before_digits?: boolean;
negative_sign_after_digits?: boolean;
allow_negative_sign_placeholder?: boolean;
thousands_separator?: string;
decimal_separator?: string;
allow_decimal?: boolean;
require_decimal?: boolean;
digits_after_decimal?: number[];
allow_space_after_digits?: boolean;
}
/**
* defaults to
* {
* format: 'YYYY/MM/DD',
* delimiters: ['/', '-'],
* strictMode: false
* }
*/
export interface IsDateOptions {
format?: string;
delimiters?: string[];
strictMode?: boolean;
}
export interface IsDecimalOptions {
decimal_digits?: string;
force_decimal?: boolean;
locale?: AlphanumericLocale;
blacklisted_chars?: string;
}
export interface IsEmailOptions {
allow_display_name?: boolean;
allow_utf8_local_part?: boolean;
require_tld?: boolean;
ignore_max_length?: boolean;
allow_ip_domain?: boolean;
domain_specific_validation?: boolean;
blacklisted_chars?: string;
host_blacklist?: string[];
}
/**
* defaults to
* {
* ignore_whitespace: false
* }
*/
export interface IsEmptyOptions {
ignore_whitespace: boolean;
}
export interface IsFloatOptions extends MinMaxExtendedOptions {
locale?: AlphanumericLocale;
}
/**
* defaults to
* {
* require_tld: true,
* allow_underscores: false,
* allow_trailing_dot: false,
* allow_numeric_tld: false,
* allow_wildcard?: false
* }
*/
export interface IsFQDNOptions {
require_tld?: boolean;
allow_underscores?: boolean;
allow_trailing_dot?: boolean;
allow_numeric_tld?: boolean;
allow_wildcard?: boolean;
}
export interface IsIntOptions extends MinMaxExtendedOptions {
allow_leading_zeroes?: boolean;
}
/**
* defaults to
* {
* allow_primitives: false
* }
*/
export interface IsJSONOptions {
allow_primitives?: boolean;
}
/**
* defaults to
* {
* checkDMS: false
* }
*/
export interface IsLatLongOptions {
checkDMS?: boolean;
}
/**
* defaults to
* {
* allow_hyphens: false
* }
*/
export interface IsIMEIOptions {
allow_hyphens?: boolean;
}
/**
* defaults to
* {
* strict: false,
* strictSeparator: false
* }
*/
export interface IsISO8601Options {
strict?: boolean;
strictSeparator?: boolean;
}
/**
* defaults to
* {
* case_sensitive: false,
* require_hyphen: false
* }
*/
export interface IsISSNOptions {
case_sensitive?: boolean;
require_hyphen?: boolean;
}
/**
* defaults to
* ```js
* {
* no_separators: false
* }
* ```
*/
export interface IsMACAddressOptions {
// no_separators replaces no_colons.
// Since it is a bool we don't require any particular logic to support both of them together.
// See https://github.com/validatorjs/validator.js/pull/1616
no_separators?: boolean;
/**
* @deprecated use `no_separators` instead
*/
// TODO(v7): remove no_colons
no_colons?: boolean;
}
export interface IsMobilePhoneOptions {
strictMode?: boolean;
}
/**
* defaults to
* {
* no_symbols: false
* }
*/
export interface IsNumericOptions {
no_symbols: boolean;
locale?: AlphanumericLocale;
}
/**
* defaults to
* {
* minLength: 8,
* minLowercase: 1,
* minUppercase: 1,
* minNumbers: 1,
* minSymbols: 1,
* returnScore: false,
* pointsPerUnique: 1,
* pointsPerRepeat: 0.5,
* pointsForContainingLower: 10,
* pointsForContainingUpper: 10,
* pointsForContainingNumber: 10,
* pointsForContainingSymbol: 10
* }
*/
export interface IsStrongPasswordOptions {
minLength?: number;
minLowercase?: number;
minUppercase?: number;
minNumbers?: number;
minSymbols?: number;
returnScore?: boolean;
pointsPerUnique?: number;
pointsPerRepeat?: number;
pointsForContainingLower?: number;
pointsForContainingUpper?: number;
pointsForContainingNumber?: number;
pointsForContainingSymbol?: number;
}
/**
* defaults to
* {
* protocols: ['http','https','ftp'],
* require_tld: true,
* require_protocol: false,
* require_host: true,
* require_port: false;
* require_valid_protocol: true,
* allow_underscores: false,
* host_whitelist: false,
* host_blacklist: false,
* allow_trailing_dot: false,
* allow_protocol_relative_urls: false,
* validate_length: true,
* allow_fragments: true,
* allow_query_components: true
* }
*/
export interface IsURLOptions {
protocols?: URLProtocol[];
require_tld?: boolean;
require_protocol?: boolean;
require_host?: boolean;
require_port?: boolean;
require_valid_protocol?: boolean;
allow_underscores?: boolean;
host_whitelist?: (string | RegExp)[];
host_blacklist?: (string | RegExp)[];
allow_trailing_dot?: boolean;
allow_protocol_relative_urls?: boolean;
disallow_auth?: boolean;
validate_length?: boolean;
allow_fragments?: boolean;
allow_query_components?: boolean;
}
export interface NormalizeEmailOptions {
all_lowercase?: boolean;
gmail_lowercase?: boolean;
gmail_remove_dots?: boolean;
gmail_remove_subaddress?: boolean;
gmail_convert_googlemaildotcom?: boolean;
outlookdotcom_lowercase?: boolean;
outlookdotcom_remove_subaddress?: boolean;
yahoo_lowercase?: boolean;
yahoo_remove_subaddress?: boolean;
icloud_lowercase?: boolean;
icloud_remove_subaddress?: boolean;
} | the_stack |
import { URI, UriComponents } from 'vs/base/common/uri';
import { MainContext, IMainContext, ExtHostFileSystemShape, MainThreadFileSystemShape, IFileChangeDto } from './extHost.protocol';
import type * as vscode from 'vscode';
import * as files from 'vs/platform/files/common/files';
import { IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { FileChangeType } from 'vs/workbench/api/common/extHostTypes';
import * as typeConverter from 'vs/workbench/api/common/extHostTypeConverters';
import { ExtHostLanguageFeatures } from 'vs/workbench/api/common/extHostLanguageFeatures';
import { State, StateMachine, LinkComputer, Edge } from 'vs/editor/common/modes/linkComputer';
import { commonPrefixLength } from 'vs/base/common/strings';
import { CharCode } from 'vs/base/common/charCode';
import { VSBuffer } from 'vs/base/common/buffer';
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
class FsLinkProvider {
private _schemes: string[] = [];
private _stateMachine?: StateMachine;
add(scheme: string): void {
this._stateMachine = undefined;
this._schemes.push(scheme);
}
delete(scheme: string): void {
const idx = this._schemes.indexOf(scheme);
if (idx >= 0) {
this._schemes.splice(idx, 1);
this._stateMachine = undefined;
}
}
private _initStateMachine(): void {
if (!this._stateMachine) {
// sort and compute common prefix with previous scheme
// then build state transitions based on the data
const schemes = this._schemes.sort();
const edges: Edge[] = [];
let prevScheme: string | undefined;
let prevState: State;
let lastState = State.LastKnownState;
let nextState = State.LastKnownState;
for (const scheme of schemes) {
// skip the common prefix of the prev scheme
// and continue with its last state
let pos = !prevScheme ? 0 : commonPrefixLength(prevScheme, scheme);
if (pos === 0) {
prevState = State.Start;
} else {
prevState = nextState;
}
for (; pos < scheme.length; pos++) {
// keep creating new (next) states until the
// end (and the BeforeColon-state) is reached
if (pos + 1 === scheme.length) {
// Save the last state here, because we need to continue for the next scheme
lastState = nextState;
nextState = State.BeforeColon;
} else {
nextState += 1;
}
edges.push([prevState, scheme.toUpperCase().charCodeAt(pos), nextState]);
edges.push([prevState, scheme.toLowerCase().charCodeAt(pos), nextState]);
prevState = nextState;
}
prevScheme = scheme;
// Restore the last state
nextState = lastState;
}
// all link must match this pattern `<scheme>:/<more>`
edges.push([State.BeforeColon, CharCode.Colon, State.AfterColon]);
edges.push([State.AfterColon, CharCode.Slash, State.End]);
this._stateMachine = new StateMachine(edges);
}
}
provideDocumentLinks(document: vscode.TextDocument): vscode.ProviderResult<vscode.DocumentLink[]> {
this._initStateMachine();
const result: vscode.DocumentLink[] = [];
const links = LinkComputer.computeLinks({
getLineContent(lineNumber: number): string {
return document.lineAt(lineNumber - 1).text;
},
getLineCount(): number {
return document.lineCount;
}
}, this._stateMachine);
for (const link of links) {
const docLink = typeConverter.DocumentLink.to(link);
if (docLink.target) {
result.push(docLink);
}
}
return result;
}
}
export class ExtHostFileSystem implements ExtHostFileSystemShape {
private readonly _proxy: MainThreadFileSystemShape;
private readonly _linkProvider = new FsLinkProvider();
private readonly _fsProvider = new Map<number, vscode.FileSystemProvider>();
private readonly _registeredSchemes = new Set<string>();
private readonly _watches = new Map<number, IDisposable>();
private _linkProviderRegistration?: IDisposable;
private _handlePool: number = 0;
constructor(mainContext: IMainContext, private _extHostLanguageFeatures: ExtHostLanguageFeatures) {
this._proxy = mainContext.getProxy(MainContext.MainThreadFileSystem);
}
dispose(): void {
this._linkProviderRegistration?.dispose();
}
private _registerLinkProviderIfNotYetRegistered(): void {
if (!this._linkProviderRegistration) {
this._linkProviderRegistration = this._extHostLanguageFeatures.registerDocumentLinkProvider(undefined, '*', this._linkProvider);
}
}
registerFileSystemProvider(extension: ExtensionIdentifier, scheme: string, provider: vscode.FileSystemProvider, options: { isCaseSensitive?: boolean, isReadonly?: boolean } = {}) {
if (this._registeredSchemes.has(scheme)) {
throw new Error(`a provider for the scheme '${scheme}' is already registered`);
}
//
this._registerLinkProviderIfNotYetRegistered();
const handle = this._handlePool++;
this._linkProvider.add(scheme);
this._registeredSchemes.add(scheme);
this._fsProvider.set(handle, provider);
let capabilities = files.FileSystemProviderCapabilities.FileReadWrite;
if (options.isCaseSensitive) {
capabilities += files.FileSystemProviderCapabilities.PathCaseSensitive;
}
if (options.isReadonly) {
capabilities += files.FileSystemProviderCapabilities.Readonly;
}
if (typeof provider.copy === 'function') {
capabilities += files.FileSystemProviderCapabilities.FileFolderCopy;
}
if (typeof provider.open === 'function' && typeof provider.close === 'function'
&& typeof provider.read === 'function' && typeof provider.write === 'function'
) {
capabilities += files.FileSystemProviderCapabilities.FileOpenReadWriteClose;
}
this._proxy.$registerFileSystemProvider(handle, scheme, capabilities).catch(err => {
console.error(`FAILED to register filesystem provider of ${extension.value}-extension for the scheme ${scheme}`);
console.error(err);
});
const subscription = provider.onDidChangeFile(event => {
const mapped: IFileChangeDto[] = [];
for (const e of event) {
let { uri: resource, type } = e;
if (resource.scheme !== scheme) {
// dropping events for wrong scheme
continue;
}
let newType: files.FileChangeType | undefined;
switch (type) {
case FileChangeType.Changed:
newType = files.FileChangeType.UPDATED;
break;
case FileChangeType.Created:
newType = files.FileChangeType.ADDED;
break;
case FileChangeType.Deleted:
newType = files.FileChangeType.DELETED;
break;
default:
throw new Error('Unknown FileChangeType');
}
mapped.push({ resource, type: newType });
}
this._proxy.$onFileSystemChange(handle, mapped);
});
return toDisposable(() => {
subscription.dispose();
this._linkProvider.delete(scheme);
this._registeredSchemes.delete(scheme);
this._fsProvider.delete(handle);
this._proxy.$unregisterProvider(handle);
});
}
private static _asIStat(stat: vscode.FileStat): files.IStat {
const { type, ctime, mtime, size, permissions } = stat;
return { type, ctime, mtime, size, permissions };
}
$stat(handle: number, resource: UriComponents): Promise<files.IStat> {
return Promise.resolve(this._getFsProvider(handle).stat(URI.revive(resource))).then(stat => ExtHostFileSystem._asIStat(stat));
}
$readdir(handle: number, resource: UriComponents): Promise<[string, files.FileType][]> {
return Promise.resolve(this._getFsProvider(handle).readDirectory(URI.revive(resource)));
}
$readFile(handle: number, resource: UriComponents): Promise<VSBuffer> {
return Promise.resolve(this._getFsProvider(handle).readFile(URI.revive(resource))).then(data => VSBuffer.wrap(data));
}
$writeFile(handle: number, resource: UriComponents, content: VSBuffer, opts: files.FileWriteOptions): Promise<void> {
return Promise.resolve(this._getFsProvider(handle).writeFile(URI.revive(resource), content.buffer, opts));
}
$delete(handle: number, resource: UriComponents, opts: files.FileDeleteOptions): Promise<void> {
return Promise.resolve(this._getFsProvider(handle).delete(URI.revive(resource), opts));
}
$rename(handle: number, oldUri: UriComponents, newUri: UriComponents, opts: files.FileOverwriteOptions): Promise<void> {
return Promise.resolve(this._getFsProvider(handle).rename(URI.revive(oldUri), URI.revive(newUri), opts));
}
$copy(handle: number, oldUri: UriComponents, newUri: UriComponents, opts: files.FileOverwriteOptions): Promise<void> {
const provider = this._getFsProvider(handle);
if (!provider.copy) {
throw new Error('FileSystemProvider does not implement "copy"');
}
return Promise.resolve(provider.copy(URI.revive(oldUri), URI.revive(newUri), opts));
}
$mkdir(handle: number, resource: UriComponents): Promise<void> {
return Promise.resolve(this._getFsProvider(handle).createDirectory(URI.revive(resource)));
}
$watch(handle: number, session: number, resource: UriComponents, opts: files.IWatchOptions): void {
const subscription = this._getFsProvider(handle).watch(URI.revive(resource), opts);
this._watches.set(session, subscription);
}
$unwatch(_handle: number, session: number): void {
const subscription = this._watches.get(session);
if (subscription) {
subscription.dispose();
this._watches.delete(session);
}
}
$open(handle: number, resource: UriComponents, opts: files.FileOpenOptions): Promise<number> {
const provider = this._getFsProvider(handle);
if (!provider.open) {
throw new Error('FileSystemProvider does not implement "open"');
}
return Promise.resolve(provider.open(URI.revive(resource), opts));
}
$close(handle: number, fd: number): Promise<void> {
const provider = this._getFsProvider(handle);
if (!provider.close) {
throw new Error('FileSystemProvider does not implement "close"');
}
return Promise.resolve(provider.close(fd));
}
$read(handle: number, fd: number, pos: number, length: number): Promise<VSBuffer> {
const provider = this._getFsProvider(handle);
if (!provider.read) {
throw new Error('FileSystemProvider does not implement "read"');
}
const data = VSBuffer.alloc(length);
return Promise.resolve(provider.read(fd, pos, data.buffer, 0, length)).then(read => {
return data.slice(0, read); // don't send zeros
});
}
$write(handle: number, fd: number, pos: number, data: VSBuffer): Promise<number> {
const provider = this._getFsProvider(handle);
if (!provider.write) {
throw new Error('FileSystemProvider does not implement "write"');
}
return Promise.resolve(provider.write(fd, pos, data.buffer, 0, data.byteLength));
}
private _getFsProvider(handle: number): vscode.FileSystemProvider {
const provider = this._fsProvider.get(handle);
if (!provider) {
const err = new Error();
err.name = 'ENOPRO';
err.message = `no provider`;
throw err;
}
return provider;
}
} | the_stack |
import * as React from 'react';
import {
AnimatePropTypeInterface,
CategoryPropType,
Data,
DataGetterPropType,
EventCallbackInterface,
EventPropTypeInterface,
Helpers,
NumberOrCallback,
OriginType,
PaddingProps,
SliceNumberOrCallback,
SortOrderPropType,
StringOrNumberOrCallback,
StringOrNumberOrList,
VictoryStyleInterface
} from 'victory-core';
import { SliceProps, VictoryPie } from 'victory-pie';
import hoistNonReactStatics from 'hoist-non-react-statics';
import { ChartContainer } from '../ChartContainer';
import { ChartDonut, ChartDonutProps } from '../ChartDonut';
import { ChartDonutStyles, ChartThemeDefinition } from '../ChartTheme';
import { getDonutThresholdDynamicTheme, getDonutThresholdStaticTheme, getPaddingForSide } from '../ChartUtils';
export enum ChartDonutThresholdDonutOrientation {
left = 'left',
right = 'right',
top = 'top'
}
export enum ChartDonutThresholdLabelOrientation {
horizontal = 'horizontal',
vertical = 'vertical'
}
export enum ChartDonutThresholdLabelPosition {
centroid = 'centroid',
endAngle = 'endAngle',
startAngle = 'startAngle'
}
export enum ChartDonutThresholdSortOrder {
ascending = 'ascending',
descending = 'descending'
}
export enum ChartDonutThresholdSubTitlePosition {
bottom = 'bottom',
center = 'center',
right = 'right'
}
/**
* See https://github.com/FormidableLabs/victory/blob/master/packages/victory-core/src/index.d.ts
* and https://github.com/FormidableLabs/victory/blob/master/packages/victory-pie/src/index.d.ts
*/
export interface ChartDonutThresholdProps extends ChartDonutProps {
/**
* Specifies the tooltip capability of the container component. A value of true allows the chart to add a
* ChartTooltip component to the labelComponent property. This is a shortcut to display tooltips when the labels
* property is also provided.
*/
allowTooltip?: boolean;
/**
* The animate prop specifies props for VictoryAnimation to use.
* The animate prop should also be used to specify enter and exit
* transition configurations with the `onExit` and `onEnter` namespaces respectively.
*
* @propType boolean | object
* @example
* {duration: 500, onExit: () => {}, onEnter: {duration: 500, before: () => ({y: 0})})}
*/
animate?: boolean | AnimatePropTypeInterface;
/**
* The ariaDesc prop specifies the description of the chart/SVG to assist with
* accessibility for screen readers.
*
* Note: Overridden by the desc prop of containerComponent
*/
ariaDesc?: string;
/**
* The ariaTitle prop specifies the title to be applied to the SVG to assist
* accessibility for screen readers.
*
* Note: Overridden by the title prop of containerComponent
*/
ariaTitle?: string;
/**
* The categories prop specifies how categorical data for a chart should be ordered.
* This prop should be given as an array of string values, or an object with
* these arrays of values specified for x and y. If this prop is not set,
* categorical data will be plotted in the order it was given in the data array
*
* @propType string[] | { x: string[], y: string[] }
* @example ["dogs", "cats", "mice"]
*/
categories?: CategoryPropType;
/**
* The utilization donut chart to render with the threshold donut chart
*
* Note: This prop should not be set manually.
*
* @hide
*/
children?: React.ReactElement<any>;
/**
* The colorScale prop is an optional prop that defines the color scale the pie
* will be created on. This prop should be given as an array of CSS colors, or as a string
* corresponding to one of the built in color scales. ChartDonutThreshold will automatically assign
* values from this color scale to the pie slices unless colors are explicitly provided in the
* data object
*/
colorScale?: string[];
/**
* The constrainToVisibleArea prop determines whether to coerce tooltips so that they fit within the visible area of
* the chart. When this prop is set to true, tooltip pointers will still point to the correct data point, but the
* center of the tooltip will be shifted to fit within the overall width and height of the svg Victory renders.
*/
constrainToVisibleArea?: boolean;
/**
* The containerComponent prop takes an entire component which will be used to
* create a container element for standalone charts.
* The new element created from the passed containerComponent wil be provided with
* these props from ChartDonutThreshold: height, width, children
* (the chart itself) and style. Props that are not provided by the
* child chart component include title and desc, both of which
* are intended to add accessibility to Victory components. The more descriptive these props
* are, the more accessible your data will be for people using screen readers.
* Any of these props may be overridden by passing in props to the supplied component,
* or modified or ignored within the custom component itself. If a dataComponent is
* not provided, ChartDonutThreshold will use the default ChartContainer component.
*
* @example <ChartContainer title="Chart of Dog Breeds" desc="This chart shows ..." />
*/
containerComponent?: React.ReactElement<any>;
/**
* Set the cornerRadius for every dataComponent (Slice by default) within ChartDonutThreshold
*
* @propType number | Function
*/
cornerRadius?: SliceNumberOrCallback<SliceProps, 'cornerRadius'>;
/**
* The data prop specifies the data to be plotted,
* where data X-value is the slice label (string or number),
* and Y-value is the corresponding number value represented by the slice
* Data should be in the form of a single data point.
* The data point may be any format you wish (depending on the `x` and `y` accessor props),
* but by default, an object with x and y properties is expected.
*
* Note: The Y-value is expected to represent a percentage
*
* @example data={[{ x: 'Warning at 60%', y: 60 }, { x: 'Danger at 90%', y: 90 }]}
*/
data?: any[];
/**
* The dataComponent prop takes an entire, HTML-complete data component which will be used to
* create slices for each datum in the pie chart. The new element created from the passed
* dataComponent will have the property datum set by the pie chart for the point it renders;
* properties style and pathFunction calculated by ChartDonutThreshold; an index property set
* corresponding to the location of the datum in the data provided to the pie; events bound to
* the ChartDonutThreshold; and the d3 compatible slice object.
* If a dataComponent is not provided, ChartDonutThreshold's Slice component will be used.
*/
dataComponent?: React.ReactElement<any>;
/**
* The desc prop specifies the description of the chart/SVG to assist with
* accessibility for screen readers. The more info about the chart provided in
* the description, the more usable it will be for people using screen readers.
* This prop defaults to an empty string.
*
* Note: Overridden by containerComponent
*
* @example "Golden retreivers make up 30%, Labs make up 25%, and other dog breeds are
* not represented above 5% each."
*/
desc?: string;
/**
* The overall end angle of the pie in degrees. This prop is used in conjunction with
* startAngle to create a pie that spans only a segment of a circle.
*/
endAngle?: number;
/**
* Similar to data accessor props `x` and `y`, this prop may be used to functionally
* assign eventKeys to data
*
* @propType number | string | Function
*/
eventKey?: StringOrNumberOrCallback;
/**
* The event prop takes an array of event objects. Event objects are composed of
* a target, an eventKey, and eventHandlers. Targets may be any valid style namespace
* for a given component, so "data" and "labels" are all valid targets for ChartDonutThreshold
* events. The eventKey may optionally be used to select a single element by index rather than
* an entire set. The eventHandlers object should be given as an object whose keys are standard
* event names (i.e. onClick) and whose values are event callbacks. The return value
* of an event handler is used to modify elemnts. The return value should be given
* as an object or an array of objects with optional target and eventKey keys,
* and a mutation key whose value is a function. The target and eventKey keys
* will default to those corresponding to the element the event handler was attached to.
* The mutation function will be called with the calculated props for the individual selected
* element (i.e. a single bar), and the object returned from the mutation function
* will override the props of the selected element via object assignment.
*
* @propType object[]
* @example
* events={[
* {
* target: "data",
* eventKey: 1,
* eventHandlers: {
* onClick: () => {
* return [
* {
* eventKey: 2,
* mutation: (props) => {
* return {style: merge({}, props.style, {fill: "orange"})};
* }
* }, {
* eventKey: 2,
* target: "labels",
* mutation: () => {
* return {text: "hey"};
* }
* }
* ];
* }
* }
* }
* ]}
*/
events?: EventPropTypeInterface<'data' | 'labels' | 'parent', StringOrNumberOrCallback | string[] | number[]>[];
/**
* ChartDonutThreshold uses the standard externalEventMutations prop.
*
* @propType object[]
*/
externalEventMutations?: EventCallbackInterface<string | string[], StringOrNumberOrList>[];
/**
* The groupComponent prop takes an entire component which will be used to
* create group elements for use within container elements. This prop defaults
* to a <g> tag on web, and a react-native-svg <G> tag on mobile
*/
groupComponent?: React.ReactElement<any>;
/**
* Specifies the height the svg viewBox of the chart container. This value should be given as a number of pixels.
*
* Because Victory renders responsive containers, the width and height props do not determine the width and
* height of the chart in number of pixels, but instead define an aspect ratio for the chart. The exact number of
* pixels will depend on the size of the container the chart is rendered into. Typically, the parent container is set
* to the same height in order to maintain the aspect ratio.
*/
height?: number;
/**
* When creating a donut chart, this prop determines the number of pixels between
* the center of the chart and the inner edge.
*
* @propType number | Function
*/
innerRadius?: NumberOrCallback;
/**
* Invert the threshold color scale used to represent warnings, errors, etc.
*/
invert?: boolean;
/**
* The labelRadius prop defines the radius of the arc that will be used for positioning each slice label.
* If this prop is not set, the label radius will default to the radius of the pie + label padding.
*
* @propType number | Function
*/
labelRadius?: number | ((props: SliceProps) => number);
/**
* The labels prop defines labels that will appear above each bar in your chart.
* This prop should be given as an array of values or as a function of data.
* If given as an array, the number of elements in the array should be equal to
* the length of the data array. Labels may also be added directly to the data object
* like data={[{x: 1, y: 1, label: "first"}]}.
*
* @example ["spring", "summer", "fall", "winter"], (datum) => datum.title
*/
labels?: string[] | number[] | ((data: any) => string | number | null);
/**
* The name prop is used to reference a component instance when defining shared events.
*/
name?: string;
/**
* Victory components will pass an origin prop is to define the center point in svg coordinates for polar charts.
*
* Note: It will not typically be necessary to set an origin prop manually
*
* @propType { x: number, y: number }
*/
origin?: OriginType;
/**
* The padAngle prop determines the amount of separation between adjacent data slices
* in number of degrees
*
* @propType number | Function
*/
padAngle?: NumberOrCallback;
/**
* The padding props specifies the amount of padding in number of pixels between
* the edge of the chart and any rendered child components. This prop can be given
* as a number or as an object with padding specified for top, bottom, left
* and right.
*
* @propType number | { top: number, bottom: number, left: number, right: number }
*/
padding?: PaddingProps;
/**
* Specifies the radius of the chart. If this property is not provided it is computed
* from width, height, and padding props
*
* @propType number | Function
*/
radius?: NumberOrCallback;
/**
* The sharedEvents prop is used internally to coordinate events between components.
*
* Note: This prop should not be set manually.
*
* @hide
*/
sharedEvents?: { events: any[]; getEventState: Function };
/**
* This will show the static, unused portion of the donut chart
*/
showStatic?: boolean;
/**
* Use the sortKey prop to indicate how data should be sorted. This prop
* is given directly to the lodash sortBy function to be executed on the
* final dataset.
*
* @propType number | string | Function | string[]
*/
sortKey?: DataGetterPropType;
/**
* The sortOrder prop specifies whether sorted data should be returned in 'ascending' or 'descending' order.
*
* @propType string
*/
sortOrder?: SortOrderPropType;
/**
* The standalone prop determines whether the component will render a standalone svg
* or a <g> tag that will be included in an external svg. Set standalone to false to
* compose ChartDonutThreshold with other components within an enclosing <svg> tag.
*/
standalone?: boolean;
/**
* The overall start angle of the pie in degrees. This prop is used in conjunction with
* endAngle to create a pie that spans only a segment of a circle.
*/
startAngle?: number;
/**
* The style prop specifies styles for your pie. ChartDonutThreshold relies on Radium,
* so valid Radium style objects should work for this prop. Height, width, and
* padding should be specified via the height, width, and padding props.
*
* @propType { parent: object, data: object, labels: object }
* @example {data: {stroke: "black"}, label: {fontSize: 10}}
*/
style?: VictoryStyleInterface;
/**
* The subtitle for the donut chart
*/
subTitle?: string;
/**
* The orientation of the subtitle position. Valid values are 'bottom', 'center', and 'right'
*/
subTitlePosition?: 'bottom' | 'center' | 'right';
/**
* The theme prop takes a style object with nested data, labels, and parent objects.
* You can create this object yourself, or you can use a theme provided by
* When using ChartDonutThreshold as a solo component, implement the theme directly on
* ChartDonutThreshold. If you are wrapping ChartDonutThreshold in ChartChart or ChartGroup,
* please call the theme on the outermost wrapper component instead.
*
* @propType object
*/
theme?: ChartThemeDefinition;
/**
* Specifies the theme color. Valid values are 'blue', 'green', 'multi', etc.
*
* Note: Not compatible with theme prop
*
* @example themeColor={ChartThemeColor.blue}
*/
themeColor?: string;
/**
* Specifies the theme variant. Valid values are 'dark' or 'light'
*
* Note: Not compatible with theme prop
*
* @example themeVariant={ChartThemeVariant.light}
*/
themeVariant?: string;
/**
* The title for the donut chart
*/
title?: string;
/**
* Specifies the width of the svg viewBox of the chart container. This value should be given as a number of pixels.
*
* Because Victory renders responsive containers, the width and height props do not determine the width and
* height of the chart in number of pixels, but instead define an aspect ratio for the chart. The exact number of
* pixels will depend on the size of the container the chart is rendered into. Typically, the parent container is set
* to the same width in order to maintain the aspect ratio.
*/
width?: number;
/**
* The x prop specifies how to access the X value of each data point.
* If given as a function, it will be run on each data point, and returned value will be used.
* If given as an integer, it will be used as an array index for array-type data points.
* If given as a string, it will be used as a property key for object-type data points.
* If given as an array of strings, or a string containing dots or brackets,
* it will be used as a nested object property path (for details see Lodash docs for _.get).
* If `null` or `undefined`, the data value will be used as is (identity function/pass-through).
*
* @propType number | string | Function | string[]
* @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d)
*/
x?: DataGetterPropType;
/**
* The y prop specifies how to access the Y value of each data point.
* If given as a function, it will be run on each data point, and returned value will be used.
* If given as an integer, it will be used as an array index for array-type data points.
* If given as a string, it will be used as a property key for object-type data points.
* If given as an array of strings, or a string containing dots or brackets,
* it will be used as a nested object property path (for details see Lodash docs for _.get).
* If `null` or `undefined`, the data value will be used as is (identity function/pass-through).
*
* @propType number | string | Function | string[]
* @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d)
*/
y?: DataGetterPropType;
}
export const ChartDonutThreshold: React.FunctionComponent<ChartDonutThresholdProps> = ({
allowTooltip = true,
ariaDesc,
ariaTitle,
children,
constrainToVisibleArea = false,
containerComponent = <ChartContainer />,
data = [],
invert = false,
labels = [], // Don't show any tooltip labels by default, let consumer override if needed
padding,
radius,
standalone = true,
subTitlePosition = ChartDonutStyles.label.subTitlePosition as ChartDonutThresholdSubTitlePosition,
themeColor,
themeVariant,
x,
y,
// destructure last
theme = getDonutThresholdStaticTheme(themeColor, themeVariant, invert),
height = theme.pie.height,
width = theme.pie.width,
...rest
}: ChartDonutThresholdProps) => {
const defaultPadding = {
bottom: getPaddingForSide('bottom', padding, theme.pie.padding),
left: getPaddingForSide('left', padding, theme.pie.padding),
right: getPaddingForSide('right', padding, theme.pie.padding),
top: getPaddingForSide('top', padding, theme.pie.padding)
};
const chartRadius =
radius ||
Helpers.getRadius({
height,
width,
padding: defaultPadding
});
// Returns computed data representing pie chart slices
const getComputedData = () => {
// Format and sort data. Sorting ensures thresholds are displayed in the correct order and simplifies calculations.
const datum = Data.formatData(data, { x, y, ...rest }, ['x', 'y']).sort((a: any, b: any) => a._y - b._y);
// Data must be offset so that the sum of all data point y-values (including the final slice) == 100.
const [prev, computedData] = datum.reduce(
(acc: [number, any], dataPoint: { _x: number | string; _y: number }) => [
dataPoint._y, // Set the previous value to current y value
[
...acc[1],
{
x: dataPoint._x, // Conditionally add x property only if it is in the original data object
y: dataPoint._y - acc[0] // Must be offset by previous value
}
]
],
[0, []]
);
return [
...computedData,
{
y: prev ? 100 - prev : 0
}
];
};
// Render dynamic utilization donut cart
const renderChildren = () =>
React.Children.toArray(children).map((child, index) => {
if (React.isValidElement(child)) {
const { data: childData, ...childProps } = child.props;
const datum = Data.formatData([childData], childProps, ['x', 'y']); // Format child data independently of this component's props
const dynamicTheme =
childProps.theme ||
getDonutThresholdDynamicTheme(childProps.themeColor || themeColor, childProps.themeVariant || themeVariant);
return React.cloneElement(child, {
constrainToVisibleArea,
data: childData,
endAngle: 360 * (datum[0]._y ? datum[0]._y / 100 : 0),
height,
invert,
key: `pf-chart-donut-threshold-child-${index}`,
padding: defaultPadding,
radius: chartRadius - 14, // Donut utilization radius is threshold radius minus 14px spacing
showStatic: false,
standalone: false,
subTitlePosition: childProps.subTitlePosition || subTitlePosition,
theme: dynamicTheme,
width,
...childProps
});
}
return child;
});
// Static threshold donut chart
const chart = (
<ChartDonut
allowTooltip={allowTooltip}
constrainToVisibleArea={constrainToVisibleArea}
data={getComputedData()}
height={height}
key="pf-chart-donut-threshold"
labels={labels}
padding={defaultPadding}
standalone={false}
theme={theme}
width={width}
{...rest}
/>
);
// Clone so users can override container props
const container = React.cloneElement(
containerComponent,
{
desc: ariaDesc,
height,
title: ariaTitle,
width,
theme,
...containerComponent.props
},
[chart, renderChildren()]
);
return standalone ? (
<React.Fragment>{container}</React.Fragment>
) : (
<React.Fragment>
{chart}
{renderChildren()}
</React.Fragment>
);
};
ChartDonutThreshold.displayName = 'ChartDonutThreshold';
// Note: VictoryPie.role must be hoisted
hoistNonReactStatics(ChartDonutThreshold, VictoryPie); | the_stack |
declare module '@stripe/stripe-js' {
// Polyfill for TypeScript < 3.5 compatibility
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
type CreatePaymentMethodData =
| CreatePaymentMethodAcssDebitData
| CreatePaymentMethodAffirmData
| CreatePaymentMethodAfterpayClearpayData
| CreatePaymentMethodAlipayData
| CreatePaymentMethodAuBecsDebitData
| CreatePaymentMethodBancontactData
| CreatePaymentMethodBoletoData
| CreatePaymentMethodCardData
| CreatePaymentMethodCustomerBalanceData
| CreatePaymentMethodEpsData
| CreatePaymentMethodGiropayData
| CreatePaymentMethodGrabPayData
| CreatePaymentMethodIdealData
| CreatePaymentMethodKlarnaData
| CreatePaymentMethodP24Data
| CreatePaymentMethodPayNowData
| CreatePaymentMethodPromptPayData
| CreatePaymentMethodFpxData
| CreatePaymentMethodSepaDebitData
| CreatePaymentMethodSofortData
| CreatePaymentMethodWechatPayData;
interface CreatePaymentMethodAlipayData extends PaymentMethodCreateParams {
type: 'alipay';
}
interface CreatePaymentMethodWechatPayData extends PaymentMethodCreateParams {
/**
* Requires beta access:
* Contact [Stripe support](https://support.stripe.com/) for more information.
*/
type: 'wechat_pay';
}
interface CreatePaymentMethodAffirmData extends PaymentMethodCreateParams {
type: 'affirm';
/**
* Can be omitted as there are no Affirm-specific fields.
*/
affirm?: {}; // eslint-disable-line @typescript-eslint/ban-types
}
interface CreatePaymentMethodAfterpayClearpayData
extends PaymentMethodCreateParams {
type: 'afterpay_clearpay';
/**
* Can be omitted as there are no AfterpayClearpay-specific fields.
*/
afterpay_clearpay?: {}; // eslint-disable-line @typescript-eslint/ban-types
}
interface CreatePaymentMethodBancontactData
extends PaymentMethodCreateParams {
type: 'bancontact';
/**
* The customer's billing details.
* `name` is required.
*
* @docs https://stripe.com/docs/api/payment_methods/create#create_payment_method-billing_details
*/
billing_details: PaymentMethodCreateParams.BillingDetails & {
name: string;
};
}
interface CreatePaymentMethodBoletoData extends PaymentMethodCreateParams {
type: 'boleto';
/**
* The customer's billing details.
* `name`, `email`, and full `address` is required.
*
* @docs https://stripe.com/docs/api/payment_methods/create#create_payment_method-billing_details
*/
billing_details: PaymentMethodCreateParams.BillingDetails & {
email: string;
name: string;
address: PaymentMethodCreateParams.BillingDetails.Address & {
line1: string;
city: string;
postal_code: string;
state: string;
country: string;
};
};
boleto: {
tax_id: string;
};
}
interface CreatePaymentMethodCardData extends PaymentMethodCreateParams {
type: 'card';
card: StripeCardElement | StripeCardNumberElement | {token: string};
}
interface CreatePaymentMethodCustomerBalanceData
extends PaymentMethodCreateParams {
/**
* Requires beta access:
* Contact [Stripe support](https://support.stripe.com/) for more information.
*/
customer_balance: Record<string, never>;
}
interface CreatePaymentMethodEpsData extends PaymentMethodCreateParams {
type: 'eps';
/**
* The customer's billing details.
* `name` is required.
*
* @docs https://stripe.com/docs/api/payment_methods/create#create_payment_method-billing_details
*/
billing_details: PaymentMethodCreateParams.BillingDetails & {
name: string;
};
eps:
| StripeEpsBankElement
| {
/**
* The customer's bank
*/
bank?: string;
};
}
interface CreatePaymentMethodFpxData extends PaymentMethodCreateParams {
type: 'fpx';
fpx:
| StripeFpxBankElement
| {
/**
* The customer's bank.
*/
bank: string;
};
}
interface CreatePaymentMethodGiropayData extends PaymentMethodCreateParams {
type: 'giropay';
/**
* The customer's billing details.
* `name` is required.
*
* @docs https://stripe.com/docs/api/payment_methods/create#create_payment_method-billing_details
*/
billing_details: PaymentMethodCreateParams.BillingDetails & {
name: string;
};
}
interface CreatePaymentMethodGrabPayData extends PaymentMethodCreateParams {
type: 'grabpay';
/**
* Can be omitted as there are no GrabPay-specific fields.
*/
grabpay?: {}; // eslint-disable-line @typescript-eslint/ban-types
}
interface CreatePaymentMethodIdealData extends PaymentMethodCreateParams {
type: 'ideal';
ideal:
| StripeIdealBankElement
| {
/**
* The customer's bank.
*/
bank?: string;
};
}
interface CreatePaymentMethodKlarnaData extends PaymentMethodCreateParams {
/**
* Requires beta access:
* Contact [Stripe support](https://support.stripe.com/) for more information.
*/
type: 'klarna';
/**
* The customer's billing details.
* `address.country` is required.
*
* @docs https://stripe.com/docs/api/payment_methods/create#create_payment_method-billing_details
*/
billing_details: PaymentMethodCreateParams.BillingDetails & {
address: PaymentMethodCreateParams.BillingDetails.Address & {
country: string;
};
};
}
interface CreatePaymentMethodOxxoData extends PaymentMethodCreateParams {
type: 'oxxo';
/**
* The customer's billing details.
* `email` and `name` are required.
*
* @docs https://stripe.com/docs/api/payment_methods/create#create_payment_method-billing_details
*/
billing_details: PaymentMethodCreateParams.BillingDetails & {
email: string;
name: string;
};
}
interface CreatePaymentMethodP24Data extends PaymentMethodCreateParams {
type: 'p24';
/**
* The customer's billing details.
* `email` is required.
*
* @docs https://stripe.com/docs/api/payment_methods/create#create_payment_method-billing_details
*/
billing_details: PaymentMethodCreateParams.BillingDetails & {
email: string;
};
p24?:
| StripeP24BankElement
| {
/**
* The customer's bank.
*/
bank?: string;
};
}
interface CreatePaymentMethodPayNowData extends PaymentMethodCreateParams {
type: 'paynow';
}
interface CreatePaymentMethodPayPalData extends PaymentMethodCreateParams {
type: 'paypal';
}
interface CreatePaymentMethodPromptPayData extends PaymentMethodCreateParams {
type: 'promptpay';
}
interface CreatePaymentMethodSepaDebitData extends PaymentMethodCreateParams {
type: 'sepa_debit';
sepa_debit:
| StripeIbanElement
| {
/**
* An IBAN account number.
*/
iban: string;
};
/**
* The customer's billing details.
* `name` and `email` are required.
*
* @docs https://stripe.com/docs/api/payment_methods/create#create_payment_method-billing_details
*/
billing_details: PaymentMethodCreateParams.BillingDetails & {
name: string;
email: string;
};
}
interface CreatePaymentMethodSofortData extends PaymentMethodCreateParams {
type: 'sofort';
sofort: {
/**
* The country code where customer's bank is located.
*/
country: string;
};
/**
* The customer's billing details.
* Required when `setup_future_usage` is set to `off_session`.
*
* @docs https://stripe.com/docs/api/payment_methods/create#create_payment_method-billing_details
*/
billing_details?: PaymentMethodCreateParams.BillingDetails;
}
interface CreatePaymentMethodAuBecsDebitData
extends PaymentMethodCreateParams {
/**
* Requires beta access:
* Contact [Stripe support](https://support.stripe.com/) for more information.
*/
type: 'au_becs_debit';
/**
* Requires beta access:
* Contact [Stripe support](https://support.stripe.com/) for more information.
*/
au_becs_debit:
| StripeAuBankAccountElement
| {
/**
* A BSB number.
*/
bsb_number: string;
/**
* An account number.
*/
account_number: string;
};
/**
* The customer's billing details.
* `name` and `email` are required.
*
* @docs https://stripe.com/docs/api/payment_methods/create#create_payment_method-billing_details
*/
billing_details: PaymentMethodCreateParams.BillingDetails & {
name: string;
email: string;
};
}
interface CreatePaymentMethodBacsDebitData extends PaymentMethodCreateParams {
type: 'bacs_debit';
bacs_debit: {
/**
* A sort code.
*/
sort_code: string;
/**
* An account number.
*/
account_number: string;
};
/**
* The customer's billing details.
* `name`, `email`, and `address` are required.
*
* @docs https://stripe.com/docs/api/payment_methods/create#create_payment_method-billing_details
*/
billing_details: PaymentMethodCreateParams.BillingDetails & {
name: string;
email: string;
address: PaymentMethodCreateParams.BillingDetails.Address & {
line1: string;
city: string;
country: string;
postal_code: string;
};
};
}
interface CreatePaymentMethodAcssDebitData extends PaymentMethodCreateParams {
type: 'acss_debit';
/**
* Can be omitted as Stripe will help to collect bank account details and verification.
* Refer to our [integration guide](https://stripe.com/docs/payments/acss-debit/accept-a-payment) for more details.
*/
acss_debit?: {
/**
* Customer’s bank account number.
*/
account_number: string;
/**
* Institution number of the customer’s bank.
*/
institution_number: string;
/**
* Transit number of the customer’s bank.
*/
transit_number: string;
};
/**
* The customer's billing details.
* `name`, `email`, and `address` are required.
*
* @docs https://stripe.com/docs/api/payment_methods/create#create_payment_method-billing_details
*/
billing_details: PaymentMethodCreateParams.BillingDetails;
}
/**
* Data to be sent with a `stripe.confirmBancontactPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmBancontactPaymentData extends PaymentIntentConfirmParams {
/**
* Either the `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a `PaymentMethod` with.
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent`.
*
* @recommended
*/
payment_method?: string | Omit<CreatePaymentMethodBancontactData, 'type'>;
/**
* The url your customer will be directed to after they complete authentication.
*
* @recommended
*/
return_url?: string;
}
/**
* Data to be sent with a `stripe.confirmBoletoPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmBoletoPaymentData extends PaymentIntentConfirmParams {
/**
* Either the `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a `PaymentMethod` with.
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent`.
*
* @recommended
*/
payment_method?: string | Omit<CreatePaymentMethodBoletoData, 'type'>;
}
/**
* An options object to control the behavior of `stripe.confirmBoletoPayment`.
*/
interface ConfirmBoletoPaymentOptions {
/**
* Set this to `false` if you want to handle next actions yourself. Please refer to our [Stripe Boleto integration guide](https://stripe.com/docs/payments/boleto) for more info. Default is `true`.
*/
handleActions?: boolean;
}
/**
* Data to be sent with a `stripe.confirmAlipayPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmAlipayPaymentData extends PaymentIntentConfirmParams {
/**
* The `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods).
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent` or a new `PaymentMethod` will be created.
*
* @recommended
*/
payment_method?: string | Omit<CreatePaymentMethodAlipayData, 'type'>;
/**
* The url your customer will be directed to after they complete authentication.
*
* @recommended
*/
return_url?: string;
}
/**
* An options object to control the behavior of `stripe.confirmAlipayPayment`.
*/
interface ConfirmAlipayPaymentOptions {
/**
* Set this to `false` if you want to [manually handle the authorization redirect](https://stripe.com/docs/payments/alipay/accept-a-payment#handle-redirect).
* Default is `true`.
*/
handleActions?: boolean;
}
/**
* An options object to control the behavior of `stripe.confirmBancontactPayment`.
*/
interface ConfirmBancontactPaymentOptions {
/**
* Set this to `false` if you want to [manually handle the authorization redirect](https://stripe.com/docs/payments/bancontact#handle-redirect).
* Default is `true`.
*/
handleActions?: boolean;
}
/**
* Data to be sent with a `stripe.confirmCardPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmCardPaymentData extends PaymentIntentConfirmParams {
/**
* Either the `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a `PaymentMethod` with.
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent`.
*
* @recommended
*/
payment_method?: string | Omit<CreatePaymentMethodCardData, 'type'>;
/**
* An object containing payment-method-specific configuration to confirm the [PaymentIntent](https://stripe.com/docs/api/payment_intents) with.
*/
payment_method_options?: {
/**
* Configuration for this card payment.
*/
card: {
/**
* Use the provided `CardCvcElement` when confirming the PaymentIntent with an existing PaymentMethod.
*/
cvc?: StripeCardCvcElement;
/**
* Selected network to process this PaymentIntent on. Depends on the available networks of the card attached to the PaymentIntent.
*/
network?: string;
};
};
}
/**
* An options object to control the behavior of `stripe.confirmCardPayment`.
*/
interface ConfirmCardPaymentOptions {
/**
* Set this to `false` if you want to [handle next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), or if you want to defer next action handling until later (e.g. for use in the [PaymentRequest API](https://stripe.com/docs/stripe-js/elements/payment-request-button#complete-payment-intents)).
* Default is `true`.
*/
handleActions?: boolean;
}
/**
* Data to be sent with a `stripe.confirmCustomerBalancePayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmCustomerBalancePaymentData
extends PaymentIntentConfirmParams {
/**
* An object specifying the `customer_balance` type.
*/
payment_method: CreatePaymentMethodCustomerBalanceData;
payment_method_options?: {
customer_balance?: {
funding_type?: 'bank_transfer';
bank_transfer?: {
type:
| 'us_bank_account'
| 'eu_bank_account'
| 'id_bank_account'
| 'gb_bank_account'
| 'jp_bank_account'
| 'mx_bank_account';
eu_bank_account?: {
country: 'ES' | 'FR' | 'IE' | 'NL';
};
id_bank_account?: {
bank: 'bni' | 'bca';
};
requested_address_types?: Array<
| 'aba'
| 'swift'
| 'sort_code'
| 'zengin'
| 'iban'
| 'spei'
| 'id_bban'
| 'sepa'
>;
};
};
};
}
/**
* An options object to control the behavior of `stripe.confirmCustomerBalancePayment`.
*/
interface ConfirmCustomerBalancePaymentOptions {
/**
* This must be set to `false`.
* The Customer Balance does not handle the next actions for you automatically (e.g. displaying bank transfer details).
* To make future upgrades easier, this option is required to always be sent.
* Please refer to our [Stripe Customer Balance integration guide](https://stripe.com/docs/payments/bank-transfers) for more info.
*/
handleActions: false;
}
/**
* Data to be sent with a `stripe.confirmEpsPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmEpsPaymentData extends PaymentIntentConfirmParams {
/**
* Either the `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a `PaymentMethod` with.
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent`.
*
* @recommended
*/
payment_method?: string | Omit<CreatePaymentMethodEpsData, 'type'>;
/**
* The url your customer will be directed to after they complete authentication.
*
* @recommended
*/
return_url?: string;
}
/**
* An options object to control the behavior of `stripe.confirmEpsPayment`.
*/
interface ConfirmEpsPaymentOptions {
/**
* Set this to `false` if you want to [manually handle the authorization redirect](https://stripe.com/docs/payments/eps#handle-redirect).
* Default is `true`.
*/
handleActions?: boolean;
}
/**
* Data to be sent with a `stripe.confirmSepaDebitPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmSepaDebitPaymentData extends PaymentIntentConfirmParams {
/**
* Either the `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a `PaymentMethod` with.
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent`.
*
* @recommended
*/
payment_method?: string | Omit<CreatePaymentMethodSepaDebitData, 'type'>;
/**
* To save the SEPA Direct Debit account for reuse, set this parameter to `off_session`.
* SEPA Direct Debit only accepts an `off_session` value for this parameter.
*/
setup_future_usage?: 'off_session';
}
/**
* Data to be sent with a `stripe.confirmFpxPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmFpxPaymentData extends PaymentIntentConfirmParams {
/**
* Either the `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a `PaymentMethod` with.
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent`.
*
* @recommended
*/
payment_method?: string | Omit<CreatePaymentMethodFpxData, 'type'>;
/**
* The url your customer will be directed to after they complete authentication.
*
* @recommended
*/
return_url?: string;
}
/**
* An options object to control the behavior of `stripe.confirmFpxPayment`.
*/
interface ConfirmFpxPaymentOptions {
/**
* Set this to `false` if you want to [manually handle the authorization redirect](https://stripe.com/docs/payments/fpx#handle-redirect).
* Default is `true`.
*/
handleActions?: boolean;
}
/**
* Data to be sent with a `stripe.confirmGiropayPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmGiropayPaymentData extends PaymentIntentConfirmParams {
/**
* Either the `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a `PaymentMethod` with.
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent`.
*
* @recommended
*/
payment_method?: string | Omit<CreatePaymentMethodGiropayData, 'type'>;
/**
* The url your customer will be directed to after they complete authentication.
*
* @recommended
*/
return_url?: string;
}
/**
* An options object to control the behavior of `stripe.confirmGiropayPayment`.
*/
interface ConfirmGiropayPaymentOptions {
/**
* Set this to `false` if you want to [manually handle the authorization redirect](https://stripe.com/docs/payments/giropay#handle-redirect).
* Default is `true`.
*/
handleActions?: boolean;
}
/**
* Data to be sent with a `stripe.confirmGrabPayPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmGrabPayPaymentData extends PaymentIntentConfirmParams {
/**
* Either the `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a `PaymentMethod` with.
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent`.
*
* @recommended
*/
payment_method?: string | Omit<CreatePaymentMethodGrabPayData, 'type'>;
/**
* The url your customer will be directed to after they complete authentication.
*
* @recommended
*/
return_url?: string;
}
/**
* An options object to control the behavior of `stripe.confirmGrabPayPayment`.
*/
interface ConfirmGrabPayPaymentOptions {
/**
* Set this to `false` if you want to handle next actions yourself. Please refer to our [Stripe GrabPay integration guide](https://stripe.com/docs/payments/grabpay/accept-a-payment)
* for more info. Default is `true`.
*/
handleActions?: boolean;
}
/**
* Data to be sent with a `stripe.confirmIdealPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmIdealPaymentData extends PaymentIntentConfirmParams {
/**
* Either the `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a `PaymentMethod` with.
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent`.
*
* @recommended
*/
payment_method?: string | Omit<CreatePaymentMethodIdealData, 'type'>;
/**
* The url your customer will be directed to after they complete authentication.
*
* @recommended
*/
return_url?: string;
}
/**
* An options object to control the behavior of `stripe.confirmIdealPayment`.
*/
interface ConfirmIdealPaymentOptions {
/**
* Set this to `false` if you want to [manually handle the authorization redirect](https://stripe.com/docs/payments/ideal#handle-redirect).
* Default is `true`.
*/
handleActions?: boolean;
}
/**
* Data to be sent with a `stripe.confirmKlarnaPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmKlarnaPaymentData extends PaymentIntentConfirmParams {
/**
* Either the `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a `PaymentMethod` with.
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent`.
*
* @recommended
*/
payment_method?: string | Omit<CreatePaymentMethodKlarnaData, 'type'>;
/**
* The url your customer will be directed to after they complete authentication.
*
* @recommended
*/
return_url?: string;
}
/**
* An options object to control the behavior of `stripe.confirmKlarnaPayment`.
*/
interface ConfirmKlarnaPaymentOptions {
/**
* Set this to `false` if you want to [manually handle the authorization redirect](https://stripe.com/docs/payments/klarna#handle-redirect).
* Default is `true`.
*/
handleActions?: boolean;
}
/**
* Data to be sent with a `stripe.confirmOxxoPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmOxxoPaymentData extends PaymentIntentConfirmParams {
/**
* Either the `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a `PaymentMethod` with.
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent`.
*
* @recommended
*/
payment_method?: string | Omit<CreatePaymentMethodOxxoData, 'type'>;
}
/**
* An options object to control the behavior of `stripe.confirmOxxoPayment`.
*/
interface ConfirmOxxoPaymentOptions {
/**
* Set this to `false` if you want to handle next actions yourself. Please refer to our [Stripe OXXO integration guide](https://stripe.com/docs/payments/oxxo) for more info. Default is `true`.
*/
handleActions?: boolean;
}
/**
* Data to be sent with a `stripe.confirmP24Payment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmP24PaymentData extends PaymentIntentConfirmParams {
/**
* Either the `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a `PaymentMethod` with.
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent`.
*
* @recommended
*/
payment_method?: string | Omit<CreatePaymentMethodP24Data, 'type'>;
payment_method_options?: {
/**
* Configuration for this Przelewy24 payment.
*/
p24: {
/**
* Specify that payer has agreed to the Przelewy24 Terms of Service
*/
tos_shown_and_accepted?: boolean;
};
};
/**
* The url your customer will be directed to after they complete authentication.
*
* @recommended
*/
return_url?: string;
}
/**
* Data to be sent with a `stripe.confirmPayNowPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmPayNowPaymentData extends PaymentIntentConfirmParams {
/**
* The `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods).
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent` or a new `PaymentMethod` will be created.
*
* @recommended
*/
payment_method?: string | Omit<CreatePaymentMethodPayNowData, 'type'>;
}
/**
* An options object to control the behavior of `stripe.confirmPayNowPayment`.
*/
interface ConfirmPayNowPaymentOptions {
/**
* Set this to `false` if you want to [manually handle the authorization redirect](https://stripe.com/docs/payments/p24#handle-redirect).
* Default is `true`.
*/
handleActions?: boolean;
}
/**
* Data to be sent with a `stripe.confirmPayPalPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmPayPalPaymentData extends PaymentIntentConfirmParams {
/**
* Either the `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a `PaymentMethod` with.
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent`.
*
* @recommended
*/
payment_method?: string | Omit<CreatePaymentMethodPayPalData, 'type'>;
/**
* The required url your customer will be directed to after they complete authentication.
*/
return_url: string;
}
/**
* An options object to control the behavior of `stripe.confirmP24Payment`.
*/
interface ConfirmP24PaymentOptions {
/**
* Set this to `false` if you want to [manually handle the authorization redirect](https://stripe.com/docs/payments/p24#handle-redirect).
* Default is `true`.
*/
handleActions?: boolean;
}
/**
* Data to be sent with a `stripe.confirmPayNowPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmPromptPayPaymentData extends PaymentIntentConfirmParams {
/**
* The `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods).
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent` or a new `PaymentMethod` will be created.
*
* @recommended
*/
payment_method?: string | Omit<CreatePaymentMethodPromptPayData, 'type'>;
}
/**
* An options object to control the behavior of `stripe.confirmPayNowPayment`.
*/
interface ConfirmPromptPayPaymentOptions {
/**
* Set this to `false` if you want to [manually handle the authorization redirect](https://stripe.com/docs/payments/p24#handle-redirect).
* Default is `true`.
*/
handleActions?: boolean;
}
/**
* Data to be sent with a `stripe.confirmSofortPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmSofortPaymentData extends PaymentIntentConfirmParams {
/**
* Either the `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a `PaymentMethod` with.
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent`.
*
* @recommended
*/
payment_method?: string | Omit<CreatePaymentMethodSofortData, 'type'>;
/**
* The url your customer will be directed to after they complete authentication.
*
* @recommended
*/
return_url?: string;
/**
* To set up a SEPA Direct Debit payment method using the bank details from this SOFORT payment, set this parameter to `off_session`.
* When using this parameter, a `customer` will need to be set on the [PaymentIntent](https://stripe.com/docs/api/payment_intents).
* The newly created SEPA Direct Debit [PaymentMethod](https://stripe.com/docs/api/payment_methods) will be attached to this customer.
*/
setup_future_usage?: 'off_session';
}
/**
* Data to be sent with a `stripe.confirmWechatPayPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmWechatPayPaymentData extends PaymentIntentConfirmParams {
/**
* The `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods).
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent` or a new `PaymentMethod` will be created.
*
* @recommended
*/
payment_method?: string | Omit<CreatePaymentMethodWechatPayData, 'type'>;
/**
* An object containing payment-method-specific configuration to confirm the [PaymentIntent](https://stripe.com/docs/api/payment_intents) with.
*/
payment_method_options?: {
/**
* Configuration for this wechat payment.
*/
wechat_pay: {
client?: 'web';
};
};
}
/**
* An options object to control the behavior of `stripe.confirmWechatPayPayment`.
*/
interface ConfirmWechatPayPaymentOptions {
/**
* This must be set to false, and you are responsible for handling the next_action after confirming the PaymentIntent.
*/
handleActions: boolean;
}
/**
* Data to be sent with a `stripe.confirmAuBecsDebitPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmAuBecsDebitPaymentData extends PaymentIntentConfirmParams {
/**
* Either the `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a `PaymentMethod` with.
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent`.
*
* @recommended
*/
payment_method?: string | Omit<CreatePaymentMethodAuBecsDebitData, 'type'>;
/**
* To save the BECS Direct Debit account for reuse, set this parameter to `off_session`.
* BECS Direct Debit only accepts an `off_session` value for this parameter.
*/
setup_future_usage?: 'off_session';
}
/**
* Data to be sent with a `stripe.confirmAffirmPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmAffirmPaymentData extends PaymentIntentConfirmParams {
/**
* Either the `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a `PaymentMethod` with.
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent`.
*
* @recommended
*/
payment_method?: string | Omit<CreatePaymentMethodAffirmData, 'type'>;
/**
* The url your customer will be directed to after they complete authentication.
*/
return_url?: string;
}
/**
* An options object to control the behavior of `stripe.confirmAffirmPayment`.
*/
interface ConfirmAffirmPaymentOptions {
/**
* Set this to `false` if you want to handle next actions yourself. Please refer to our [Stripe Affirm integration guide](https://stripe.com/docs/payments/affirm/accept-a-payment)
* for more info. Default is `true`.
*/
handleActions?: boolean;
}
/**
* Data to be sent with a `stripe.confirmAfterpayClearpayPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmAfterpayClearpayPaymentData
extends PaymentIntentConfirmParams {
/**
* Either the `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a `PaymentMethod` with.
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent`.
*
* @recommended
*/
payment_method?:
| string
| Omit<CreatePaymentMethodAfterpayClearpayData, 'type'>;
/**
* The url your customer will be directed to after they complete authentication.
*/
return_url?: string;
}
/**
* An options object to control the behavior of `stripe.confirmAfterpayClearpayPayment`.
*/
interface ConfirmAfterpayClearpayPaymentOptions {
/**
* Set this to `false` if you want to handle next actions yourself. Please refer to our [Stripe Afterpay / Clearpay integration guide](https://stripe.com/docs/payments/afterpay-clearpay/accept-a-payment#handle-redirect)
* for more info. Default is `true`.
*/
handleActions?: boolean;
}
/**
* Data to be sent with a `stripe.confirmAcssDebitPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmAcssDebitPaymentData extends PaymentIntentConfirmParams {
/**
* Either the `id` of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a `PaymentMethod` with.
* This field is optional if a `PaymentMethod` has already been attached to this `PaymentIntent`.
*
* @recommended
*/
payment_method?: string | Omit<CreatePaymentMethodAcssDebitData, 'type'>;
}
/**
* An options object to control the behavior of `stripe.confirmAcssDebitPayment`.
*/
interface ConfirmAcssDebitPaymentOptions {
/**
* Set `skipMandate` to `true` if you want to skip displaying the mandate confirmation screen.
*/
skipMandate?: boolean;
}
/**
* Data to be sent with a `stripe.confirmPayment` request.
* Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.
*/
interface ConfirmPaymentData extends PaymentIntentConfirmParams {
/**
* The url your customer will be directed to after they complete payment.
*/
return_url: string;
/**
* An object to attach additional billing_details to the PaymentMethod created via Elements.
*
* @docs https://stripe.com/docs/api/payment_intents/create#create_payment_intent-payment_method_data
*/
payment_method_data?: {
/**
* The customer's billing details. Details collected by Elements will override values passed here.
* Billing fields that are omitted in the Payment Element via the `fields` option required.
*
* @docs https://stripe.com/docs/api/payment_intents/create#create_payment_intent-payment_method_data-billing_details
*/
billing_details?: PaymentMethodCreateParams.BillingDetails;
};
}
/**
* Data to be sent with a `stripe.verifyMicrodepositsForPayment` request.
*/
interface VerifyMicrodepositsForPaymentData {
/**
* An array of two positive integers, in cents, equal to the values of the microdeposits sent to the bank account.
*/
amounts?: Array<number>;
}
} | the_stack |
// IMPORTANT
// This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually.
// In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator
// Generated from: https://dataproc.googleapis.com/$discovery/rest?version=v1
/// <reference types="gapi.client" />
declare namespace gapi.client {
/** Load Google Cloud Dataproc API v1 */
function load(name: "dataproc", version: "v1"): PromiseLike<void>;
function load(name: "dataproc", version: "v1", callback: () => any): void;
const projects: dataproc.ProjectsResource;
namespace dataproc {
interface AcceleratorConfig {
/** The number of the accelerator cards of this type exposed to this instance. */
acceleratorCount?: number;
/**
* Full URL, partial URI, or short name of the accelerator type resource to expose to this instance. See Google Compute Engine AcceleratorTypes(
* /compute/docs/reference/beta/acceleratorTypes)Examples *
* https://www.googleapis.com/compute/beta/projects/[project_id]/zones/us-east1-a/acceleratorTypes/nvidia-tesla-k80 *
* projects/[project_id]/zones/us-east1-a/acceleratorTypes/nvidia-tesla-k80 * nvidia-tesla-k80
*/
acceleratorTypeUri?: string;
}
interface Cluster {
/** Required. The cluster name. Cluster names within a project must be unique. Names of deleted clusters can be reused. */
clusterName?: string;
/** Output-only. A cluster UUID (Unique Universal Identifier). Cloud Dataproc generates this value when it creates the cluster. */
clusterUuid?: string;
/** Required. The cluster config. Note that Cloud Dataproc may set default values, and values may change when clusters are updated. */
config?: ClusterConfig;
/**
* Optional. The labels to associate with this cluster. Label keys must contain 1 to 63 characters, and must conform to RFC 1035
* (https://www.ietf.org/rfc/rfc1035.txt). Label values may be empty, but, if present, must contain 1 to 63 characters, and must conform to RFC 1035
* (https://www.ietf.org/rfc/rfc1035.txt). No more than 32 labels can be associated with a cluster.
*/
labels?: Record<string, string>;
/**
* Contains cluster daemon metrics such as HDFS and YARN stats.Beta Feature: This report is available for testing purposes only. It may be changed before
* final release.
*/
metrics?: ClusterMetrics;
/** Required. The Google Cloud Platform project ID that the cluster belongs to. */
projectId?: string;
/** Output-only. Cluster status. */
status?: ClusterStatus;
/** Output-only. The previous cluster status. */
statusHistory?: ClusterStatus[];
}
interface ClusterConfig {
/**
* Optional. A Google Cloud Storage staging bucket used for sharing generated SSH keys and config. If you do not specify a staging bucket, Cloud Dataproc
* will determine an appropriate Cloud Storage location (US, ASIA, or EU) for your cluster's staging bucket according to the Google Compute Engine zone
* where your cluster is deployed, and then it will create and manage this project-level, per-location bucket for you.
*/
configBucket?: string;
/** Required. The shared Google Compute Engine config settings for all instances in a cluster. */
gceClusterConfig?: GceClusterConfig;
/**
* Optional. Commands to execute on each node after config is completed. By default, executables are run on master and all worker nodes. You can test a
* node's role metadata to run an executable on a master or worker node, as shown below using curl (you can also use wget):
* ROLE=$(curl -H Metadata-Flavor:Google http://metadata/computeMetadata/v1/instance/attributes/dataproc-role)
* if [[ "${ROLE}" == 'Master' ]]; then
* ... master specific actions ...
* else
* ... worker specific actions ...
* fi
*/
initializationActions?: NodeInitializationAction[];
/** Optional. The Google Compute Engine config settings for the master instance in a cluster. */
masterConfig?: InstanceGroupConfig;
/** Optional. The Google Compute Engine config settings for additional worker instances in a cluster. */
secondaryWorkerConfig?: InstanceGroupConfig;
/** Optional. The config settings for software inside the cluster. */
softwareConfig?: SoftwareConfig;
/** Optional. The Google Compute Engine config settings for worker instances in a cluster. */
workerConfig?: InstanceGroupConfig;
}
interface ClusterMetrics {
/** The HDFS metrics. */
hdfsMetrics?: Record<string, string>;
/** The YARN metrics. */
yarnMetrics?: Record<string, string>;
}
interface ClusterOperationMetadata {
/** Output-only. Name of the cluster for the operation. */
clusterName?: string;
/** Output-only. Cluster UUID for the operation. */
clusterUuid?: string;
/** Output-only. Short description of operation. */
description?: string;
/** Output-only. Labels associated with the operation */
labels?: Record<string, string>;
/** Output-only. The operation type. */
operationType?: string;
/** Output-only. Current operation status. */
status?: ClusterOperationStatus;
/** Output-only. The previous operation status. */
statusHistory?: ClusterOperationStatus[];
/** Output-only. Errors encountered during operation execution. */
warnings?: string[];
}
interface ClusterOperationStatus {
/** Output-only.A message containing any operation metadata details. */
details?: string;
/** Output-only. A message containing the detailed operation state. */
innerState?: string;
/** Output-only. A message containing the operation state. */
state?: string;
/** Output-only. The time this state was entered. */
stateStartTime?: string;
}
interface ClusterStatus {
/** Output-only. Optional details of cluster's state. */
detail?: string;
/** Output-only. The cluster's state. */
state?: string;
/** Output-only. Time when this state was entered. */
stateStartTime?: string;
/** Output-only. Additional state information that includes status reported by the agent. */
substate?: string;
}
interface DiagnoseClusterResults {
/** Output-only. The Google Cloud Storage URI of the diagnostic output. The output report is a plain text file with a summary of collected diagnostics. */
outputUri?: string;
}
interface DiskConfig {
/** Optional. Size in GB of the boot disk (default is 500GB). */
bootDiskSizeGb?: number;
/**
* Optional. Number of attached SSDs, from 0 to 4 (default is 0). If SSDs are not attached, the boot disk is used to store runtime logs and HDFS
* (https://hadoop.apache.org/docs/r1.2.1/hdfs_user_guide.html) data. If one or more SSDs are attached, this runtime bulk data is spread across them, and
* the boot disk contains only basic config and installed binaries.
*/
numLocalSsds?: number;
}
interface GceClusterConfig {
/**
* Optional. If true, all instances in the cluster will only have internal IP addresses. By default, clusters are not restricted to internal IP addresses,
* and will have ephemeral external IP addresses assigned to each instance. This internal_ip_only restriction can only be enabled for subnetwork enabled
* networks, and all off-cluster dependencies must be configured to be accessible without external IP addresses.
*/
internalIpOnly?: boolean;
/**
* The Google Compute Engine metadata entries to add to all instances (see Project and instance metadata
* (https://cloud.google.com/compute/docs/storing-retrieving-metadata#project_and_instance_metadata)).
*/
metadata?: Record<string, string>;
/**
* Optional. The Google Compute Engine network to be used for machine communications. Cannot be specified with subnetwork_uri. If neither network_uri nor
* subnetwork_uri is specified, the "default" network of the project is used, if it exists. Cannot be a "Custom Subnet Network" (see Using Subnetworks for
* more information).A full URL, partial URI, or short name are valid. Examples:
* https://www.googleapis.com/compute/v1/projects/[project_id]/regions/global/default
* projects/[project_id]/regions/global/default
* default
*/
networkUri?: string;
/**
* Optional. The service account of the instances. Defaults to the default Google Compute Engine service account. Custom service accounts need permissions
* equivalent to the folloing IAM roles:
* roles/logging.logWriter
* roles/storage.objectAdmin(see https://cloud.google.com/compute/docs/access/service-accounts#custom_service_accounts for more information). Example:
* [account_id]@[project_id].iam.gserviceaccount.com
*/
serviceAccount?: string;
/**
* Optional. The URIs of service account scopes to be included in Google Compute Engine instances. The following base set of scopes is always included:
* https://www.googleapis.com/auth/cloud.useraccounts.readonly
* https://www.googleapis.com/auth/devstorage.read_write
* https://www.googleapis.com/auth/logging.writeIf no scopes are specified, the following defaults are also provided:
* https://www.googleapis.com/auth/bigquery
* https://www.googleapis.com/auth/bigtable.admin.table
* https://www.googleapis.com/auth/bigtable.data
* https://www.googleapis.com/auth/devstorage.full_control
*/
serviceAccountScopes?: string[];
/**
* Optional. The Google Compute Engine subnetwork to be used for machine communications. Cannot be specified with network_uri.A full URL, partial URI, or
* short name are valid. Examples:
* https://www.googleapis.com/compute/v1/projects/[project_id]/regions/us-east1/sub0
* projects/[project_id]/regions/us-east1/sub0
* sub0
*/
subnetworkUri?: string;
/** The Google Compute Engine tags to add to all instances (see Tagging instances). */
tags?: string[];
/**
* Optional. The zone where the Google Compute Engine cluster will be located. On a create request, it is required in the "global" region. If omitted in a
* non-global Cloud Dataproc region, the service will pick a zone in the corresponding Compute Engine region. On a get request, zone will always be
* present.A full URL, partial URI, or short name are valid. Examples:
* https://www.googleapis.com/compute/v1/projects/[project_id]/zones/[zone]
* projects/[project_id]/zones/[zone]
* us-central1-f
*/
zoneUri?: string;
}
interface HadoopJob {
/**
* Optional. HCFS URIs of archives to be extracted in the working directory of Hadoop drivers and tasks. Supported file types: .jar, .tar, .tar.gz, .tgz,
* or .zip.
*/
archiveUris?: string[];
/**
* Optional. The arguments to pass to the driver. Do not include arguments, such as -libjars or -Dfoo=bar, that can be set as job properties, since a
* collision may occur that causes an incorrect job submission.
*/
args?: string[];
/**
* Optional. HCFS (Hadoop Compatible Filesystem) URIs of files to be copied to the working directory of Hadoop drivers and distributed tasks. Useful for
* naively parallel tasks.
*/
fileUris?: string[];
/** Optional. Jar file URIs to add to the CLASSPATHs of the Hadoop driver and tasks. */
jarFileUris?: string[];
/** Optional. The runtime log config for job execution. */
loggingConfig?: LoggingConfig;
/** The name of the driver's main class. The jar file containing the class must be in the default CLASSPATH or specified in jar_file_uris. */
mainClass?: string;
/**
* The HCFS URI of the jar file containing the main class. Examples: 'gs://foo-bucket/analytics-binaries/extract-useful-metrics-mr.jar'
* 'hdfs:/tmp/test-samples/custom-wordcount.jar' 'file:///home/usr/lib/hadoop-mapreduce/hadoop-mapreduce-examples.jar'
*/
mainJarFileUri?: string;
/**
* Optional. A mapping of property names to values, used to configure Hadoop. Properties that conflict with values set by the Cloud Dataproc API may be
* overwritten. Can include properties set in /etc/hadoop/conf/*-site and classes in user code.
*/
properties?: Record<string, string>;
}
interface HiveJob {
/**
* Optional. Whether to continue executing queries if a query fails. The default value is false. Setting to true can be useful when executing independent
* parallel queries.
*/
continueOnFailure?: boolean;
/** Optional. HCFS URIs of jar files to add to the CLASSPATH of the Hive server and Hadoop MapReduce (MR) tasks. Can contain Hive SerDes and UDFs. */
jarFileUris?: string[];
/**
* Optional. A mapping of property names and values, used to configure Hive. Properties that conflict with values set by the Cloud Dataproc API may be
* overwritten. Can include properties set in /etc/hadoop/conf/*-site.xml, /etc/hive/conf/hive-site.xml, and classes in user code.
*/
properties?: Record<string, string>;
/** The HCFS URI of the script that contains Hive queries. */
queryFileUri?: string;
/** A list of queries. */
queryList?: QueryList;
/** Optional. Mapping of query variable names to values (equivalent to the Hive command: SET name="value";). */
scriptVariables?: Record<string, string>;
}
interface InstanceGroupConfig {
/**
* Optional. The Google Compute Engine accelerator configuration for these instances.Beta Feature: This feature is still under development. It may be
* changed before final release.
*/
accelerators?: AcceleratorConfig[];
/** Optional. Disk option config settings. */
diskConfig?: DiskConfig;
/** Output-only. The Google Compute Engine image resource used for cluster instances. Inferred from SoftwareConfig.image_version. */
imageUri?: string;
/**
* Optional. The list of instance names. Cloud Dataproc derives the names from cluster_name, num_instances, and the instance group if not set by user
* (recommended practice is to let Cloud Dataproc derive the name).
*/
instanceNames?: string[];
/** Optional. Specifies that this instance group contains preemptible instances. */
isPreemptible?: boolean;
/**
* Optional. The Google Compute Engine machine type used for cluster instances.A full URL, partial URI, or short name are valid. Examples:
* https://www.googleapis.com/compute/v1/projects/[project_id]/zones/us-east1-a/machineTypes/n1-standard-2
* projects/[project_id]/zones/us-east1-a/machineTypes/n1-standard-2
* n1-standard-2
*/
machineTypeUri?: string;
/** Output-only. The config for Google Compute Engine Instance Group Manager that manages this group. This is only used for preemptible instance groups. */
managedGroupConfig?: ManagedGroupConfig;
/** Optional. The number of VM instances in the instance group. For master instance groups, must be set to 1. */
numInstances?: number;
}
interface Job {
/**
* Output-only. If present, the location of miscellaneous control files which may be used as part of job setup and handling. If not present, control files
* may be placed in the same location as driver_output_uri.
*/
driverControlFilesUri?: string;
/** Output-only. A URI pointing to the location of the stdout of the job's driver program. */
driverOutputResourceUri?: string;
/** Job is a Hadoop job. */
hadoopJob?: HadoopJob;
/** Job is a Hive job. */
hiveJob?: HiveJob;
/**
* Optional. The labels to associate with this job. Label keys must contain 1 to 63 characters, and must conform to RFC 1035
* (https://www.ietf.org/rfc/rfc1035.txt). Label values may be empty, but, if present, must contain 1 to 63 characters, and must conform to RFC 1035
* (https://www.ietf.org/rfc/rfc1035.txt). No more than 32 labels can be associated with a job.
*/
labels?: Record<string, string>;
/** Job is a Pig job. */
pigJob?: PigJob;
/** Required. Job information, including how, when, and where to run the job. */
placement?: JobPlacement;
/** Job is a Pyspark job. */
pysparkJob?: PySparkJob;
/**
* Optional. The fully qualified reference to the job, which can be used to obtain the equivalent REST path of the job resource. If this property is not
* specified when a job is created, the server generates a <code>job_id</code>.
*/
reference?: JobReference;
/** Optional. Job scheduling configuration. */
scheduling?: JobScheduling;
/** Job is a Spark job. */
sparkJob?: SparkJob;
/** Job is a SparkSql job. */
sparkSqlJob?: SparkSqlJob;
/**
* Output-only. The job status. Additional application-specific status information may be contained in the <code>type_job</code> and
* <code>yarn_applications</code> fields.
*/
status?: JobStatus;
/** Output-only. The previous job status. */
statusHistory?: JobStatus[];
/**
* Output-only. The collection of YARN applications spun up by this job.Beta Feature: This report is available for testing purposes only. It may be
* changed before final release.
*/
yarnApplications?: YarnApplication[];
}
interface JobPlacement {
/** Required. The name of the cluster where the job will be submitted. */
clusterName?: string;
/** Output-only. A cluster UUID generated by the Cloud Dataproc service when the job is submitted. */
clusterUuid?: string;
}
interface JobReference {
/**
* Optional. The job ID, which must be unique within the project. The job ID is generated by the server upon job submission or provided by the user as a
* means to perform retries without creating duplicate jobs. The ID must contain only letters (a-z, A-Z), numbers (0-9), underscores (_), or hyphens (-).
* The maximum length is 100 characters.
*/
jobId?: string;
/** Required. The ID of the Google Cloud Platform project that the job belongs to. */
projectId?: string;
}
interface JobScheduling {
/**
* Optional. Maximum number of times per hour a driver may be restarted as a result of driver terminating with non-zero code before job is reported
* failed.A job may be reported as thrashing if driver exits with non-zero code 4 times within 10 minute window.Maximum value is 10.
*/
maxFailuresPerHour?: number;
}
interface JobStatus {
/** Output-only. Optional job state details, such as an error description if the state is <code>ERROR</code>. */
details?: string;
/** Output-only. A state message specifying the overall job state. */
state?: string;
/** Output-only. The time when this state was entered. */
stateStartTime?: string;
/** Output-only. Additional state information, which includes status reported by the agent. */
substate?: string;
}
interface ListClustersResponse {
/** Output-only. The clusters in the project. */
clusters?: Cluster[];
/**
* Output-only. This token is included in the response if there are more results to fetch. To fetch additional results, provide this value as the
* page_token in a subsequent ListClustersRequest.
*/
nextPageToken?: string;
}
interface ListJobsResponse {
/** Output-only. Jobs list. */
jobs?: Job[];
/**
* Optional. This token is included in the response if there are more results to fetch. To fetch additional results, provide this value as the page_token
* in a subsequent <code>ListJobsRequest</code>.
*/
nextPageToken?: string;
}
interface ListOperationsResponse {
/** The standard List next-page token. */
nextPageToken?: string;
/** A list of operations that matches the specified filter in the request. */
operations?: Operation[];
}
interface LoggingConfig {
/**
* The per-package log levels for the driver. This may include "root" package name to configure rootLogger. Examples: 'com.google = FATAL', 'root =
* INFO', 'org.apache = DEBUG'
*/
driverLogLevels?: Record<string, string>;
}
interface ManagedGroupConfig {
/** Output-only. The name of the Instance Group Manager for this group. */
instanceGroupManagerName?: string;
/** Output-only. The name of the Instance Template used for the Managed Instance Group. */
instanceTemplateName?: string;
}
interface NodeInitializationAction {
/** Required. Google Cloud Storage URI of executable file. */
executableFile?: string;
/**
* Optional. Amount of time executable has to complete. Default is 10 minutes. Cluster creation fails with an explanatory error message (the name of the
* executable that caused the error and the exceeded timeout period) if the executable is not completed at end of the timeout period.
*/
executionTimeout?: string;
}
interface Operation {
/** If the value is false, it means the operation is still in progress. If true, the operation is completed, and either error or response is available. */
done?: boolean;
/** The error result of the operation in case of failure or cancellation. */
error?: Status;
/**
* Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some
* services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.
*/
metadata?: Record<string, any>;
/**
* The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the name should
* have the format of operations/some/unique/name.
*/
name?: string;
/**
* The normal response of the operation in case of success. If the original method returns no data on success, such as Delete, the response is
* google.protobuf.Empty. If the original method is standard Get/Create/Update, the response should be the resource. For other methods, the response
* should have the type XxxResponse, where Xxx is the original method name. For example, if the original method name is TakeSnapshot(), the inferred
* response type is TakeSnapshotResponse.
*/
response?: Record<string, any>;
}
interface PigJob {
/**
* Optional. Whether to continue executing queries if a query fails. The default value is false. Setting to true can be useful when executing independent
* parallel queries.
*/
continueOnFailure?: boolean;
/** Optional. HCFS URIs of jar files to add to the CLASSPATH of the Pig Client and Hadoop MapReduce (MR) tasks. Can contain Pig UDFs. */
jarFileUris?: string[];
/** Optional. The runtime log config for job execution. */
loggingConfig?: LoggingConfig;
/**
* Optional. A mapping of property names to values, used to configure Pig. Properties that conflict with values set by the Cloud Dataproc API may be
* overwritten. Can include properties set in /etc/hadoop/conf/*-site.xml, /etc/pig/conf/pig.properties, and classes in user code.
*/
properties?: Record<string, string>;
/** The HCFS URI of the script that contains the Pig queries. */
queryFileUri?: string;
/** A list of queries. */
queryList?: QueryList;
/** Optional. Mapping of query variable names to values (equivalent to the Pig command: name=[value]). */
scriptVariables?: Record<string, string>;
}
interface PySparkJob {
/** Optional. HCFS URIs of archives to be extracted in the working directory of .jar, .tar, .tar.gz, .tgz, and .zip. */
archiveUris?: string[];
/**
* Optional. The arguments to pass to the driver. Do not include arguments, such as --conf, that can be set as job properties, since a collision may occur
* that causes an incorrect job submission.
*/
args?: string[];
/** Optional. HCFS URIs of files to be copied to the working directory of Python drivers and distributed tasks. Useful for naively parallel tasks. */
fileUris?: string[];
/** Optional. HCFS URIs of jar files to add to the CLASSPATHs of the Python driver and tasks. */
jarFileUris?: string[];
/** Optional. The runtime log config for job execution. */
loggingConfig?: LoggingConfig;
/** Required. The HCFS URI of the main Python file to use as the driver. Must be a .py file. */
mainPythonFileUri?: string;
/**
* Optional. A mapping of property names to values, used to configure PySpark. Properties that conflict with values set by the Cloud Dataproc API may be
* overwritten. Can include properties set in /etc/spark/conf/spark-defaults.conf and classes in user code.
*/
properties?: Record<string, string>;
/** Optional. HCFS file URIs of Python files to pass to the PySpark framework. Supported file types: .py, .egg, and .zip. */
pythonFileUris?: string[];
}
interface QueryList {
/**
* Required. The queries to execute. You do not need to terminate a query with a semicolon. Multiple queries can be specified in one string by separating
* each with a semicolon. Here is an example of an Cloud Dataproc API snippet that uses a QueryList to specify a HiveJob:
* "hiveJob": {
* "queryList": {
* "queries": [
* "query1",
* "query2",
* "query3;query4",
* ]
* }
* }
*/
queries?: string[];
}
interface SoftwareConfig {
/**
* Optional. The version of software inside the cluster. It must match the regular expression [0-9]+\.[0-9]+. If unspecified, it defaults to the latest
* version (see Cloud Dataproc Versioning).
*/
imageVersion?: string;
/**
* Optional. The properties to set on daemon config files.Property keys are specified in prefix:property format, such as core:fs.defaultFS. The following
* are supported prefixes and their mappings:
* capacity-scheduler: capacity-scheduler.xml
* core: core-site.xml
* distcp: distcp-default.xml
* hdfs: hdfs-site.xml
* hive: hive-site.xml
* mapred: mapred-site.xml
* pig: pig.properties
* spark: spark-defaults.conf
* yarn: yarn-site.xmlFor more information, see Cluster properties.
*/
properties?: Record<string, string>;
}
interface SparkJob {
/**
* Optional. HCFS URIs of archives to be extracted in the working directory of Spark drivers and tasks. Supported file types: .jar, .tar, .tar.gz, .tgz,
* and .zip.
*/
archiveUris?: string[];
/**
* Optional. The arguments to pass to the driver. Do not include arguments, such as --conf, that can be set as job properties, since a collision may occur
* that causes an incorrect job submission.
*/
args?: string[];
/** Optional. HCFS URIs of files to be copied to the working directory of Spark drivers and distributed tasks. Useful for naively parallel tasks. */
fileUris?: string[];
/** Optional. HCFS URIs of jar files to add to the CLASSPATHs of the Spark driver and tasks. */
jarFileUris?: string[];
/** Optional. The runtime log config for job execution. */
loggingConfig?: LoggingConfig;
/** The name of the driver's main class. The jar file that contains the class must be in the default CLASSPATH or specified in jar_file_uris. */
mainClass?: string;
/** The HCFS URI of the jar file that contains the main class. */
mainJarFileUri?: string;
/**
* Optional. A mapping of property names to values, used to configure Spark. Properties that conflict with values set by the Cloud Dataproc API may be
* overwritten. Can include properties set in /etc/spark/conf/spark-defaults.conf and classes in user code.
*/
properties?: Record<string, string>;
}
interface SparkSqlJob {
/** Optional. HCFS URIs of jar files to be added to the Spark CLASSPATH. */
jarFileUris?: string[];
/** Optional. The runtime log config for job execution. */
loggingConfig?: LoggingConfig;
/**
* Optional. A mapping of property names to values, used to configure Spark SQL's SparkConf. Properties that conflict with values set by the Cloud
* Dataproc API may be overwritten.
*/
properties?: Record<string, string>;
/** The HCFS URI of the script that contains SQL queries. */
queryFileUri?: string;
/** A list of queries. */
queryList?: QueryList;
/** Optional. Mapping of query variable names to values (equivalent to the Spark SQL command: SET name="value";). */
scriptVariables?: Record<string, string>;
}
interface Status {
/** The status code, which should be an enum value of google.rpc.Code. */
code?: number;
/** A list of messages that carry the error details. There is a common set of message types for APIs to use. */
details?: Array<Record<string, any>>;
/**
* A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the
* google.rpc.Status.details field, or localized by the client.
*/
message?: string;
}
interface SubmitJobRequest {
/** Required. The job resource. */
job?: Job;
}
interface YarnApplication {
/** Required. The application name. */
name?: string;
/** Required. The numerical progress of the application, from 1 to 100. */
progress?: number;
/** Required. The application state. */
state?: string;
/**
* Optional. The HTTP URL of the ApplicationMaster, HistoryServer, or TimelineServer that provides application-specific information. The URL uses the
* internal hostname, and requires a proxy server for resolution and, possibly, access.
*/
trackingUrl?: string;
}
interface ClustersResource {
/** Creates a cluster in a project. */
create(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Required. The ID of the Google Cloud Platform project that the cluster belongs to. */
projectId: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Required. The Cloud Dataproc region in which to handle the request. */
region: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Operation>;
/** Deletes a cluster in a project. */
delete(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Required. The cluster name. */
clusterName: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Required. The ID of the Google Cloud Platform project that the cluster belongs to. */
projectId: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Required. The Cloud Dataproc region in which to handle the request. */
region: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Operation>;
/** Gets cluster diagnostic information. After the operation completes, the Operation.response field contains DiagnoseClusterOutputLocation. */
diagnose(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Required. The cluster name. */
clusterName: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Required. The ID of the Google Cloud Platform project that the cluster belongs to. */
projectId: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Required. The Cloud Dataproc region in which to handle the request. */
region: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Operation>;
/** Gets the resource representation for a cluster in a project. */
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Required. The cluster name. */
clusterName: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Required. The ID of the Google Cloud Platform project that the cluster belongs to. */
projectId: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Required. The Cloud Dataproc region in which to handle the request. */
region: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Cluster>;
/** Lists all regions/{region}/clusters in a project. */
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* Optional. A filter constraining the clusters to list. Filters are case-sensitive and have the following syntax:field = value AND field = value ...where
* field is one of status.state, clusterName, or labels.[KEY], and [KEY] is a label key. value can be * to match all values. status.state can be one of
* the following: ACTIVE, INACTIVE, CREATING, RUNNING, ERROR, DELETING, or UPDATING. ACTIVE contains the CREATING, UPDATING, and RUNNING states. INACTIVE
* contains the DELETING and ERROR states. clusterName is the name of the cluster provided at creation time. Only the logical AND operator is supported;
* space-separated items are treated as having an implicit AND operator.Example filter:status.state = ACTIVE AND clusterName = mycluster AND labels.env =
* staging AND labels.starred = *
*/
filter?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Optional. The standard List page size. */
pageSize?: number;
/** Optional. The standard List page token. */
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Required. The ID of the Google Cloud Platform project that the cluster belongs to. */
projectId: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Required. The Cloud Dataproc region in which to handle the request. */
region: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListClustersResponse>;
/** Updates a cluster in a project. */
patch(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Required. The cluster name. */
clusterName: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Required. The ID of the Google Cloud Platform project the cluster belongs to. */
projectId: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Required. The Cloud Dataproc region in which to handle the request. */
region: string;
/**
* Required. Specifies the path, relative to Cluster, of the field to update. For example, to change the number of workers in a cluster to 5, the
* update_mask parameter would be specified as config.worker_config.num_instances, and the PATCH request body would specify the new value, as follows:
* {
* "config":{
* "workerConfig":{
* "numInstances":"5"
* }
* }
* }
* Similarly, to change the number of preemptible workers in a cluster to 5, the update_mask parameter would be
* config.secondary_worker_config.num_instances, and the PATCH request body would be set as follows:
* {
* "config":{
* "secondaryWorkerConfig":{
* "numInstances":"5"
* }
* }
* }
* <strong>Note:</strong> Currently, only the following fields can be updated:<table> <tbody> <tr> <td><strong>Mask</strong></td>
* <td><strong>Purpose</strong></td> </tr> <tr> <td><strong><em>labels</em></strong></td> <td>Update labels</td> </tr> <tr>
* <td><strong><em>config.worker_config.num_instances</em></strong></td> <td>Resize primary worker group</td> </tr> <tr>
* <td><strong><em>config.secondary_worker_config.num_instances</em></strong></td> <td>Resize secondary worker group</td> </tr> </tbody> </table>
*/
updateMask?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Operation>;
}
interface JobsResource {
/** Starts a job cancellation request. To access the job resource after cancellation, call regions/{region}/jobs.list or regions/{region}/jobs.get. */
cancel(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** Required. The job ID. */
jobId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Required. The ID of the Google Cloud Platform project that the job belongs to. */
projectId: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Required. The Cloud Dataproc region in which to handle the request. */
region: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Job>;
/** Deletes the job from the project. If the job is active, the delete fails, and the response returns FAILED_PRECONDITION. */
delete(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** Required. The job ID. */
jobId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Required. The ID of the Google Cloud Platform project that the job belongs to. */
projectId: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Required. The Cloud Dataproc region in which to handle the request. */
region: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/** Gets the resource representation for a job in a project. */
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** Required. The job ID. */
jobId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Required. The ID of the Google Cloud Platform project that the job belongs to. */
projectId: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Required. The Cloud Dataproc region in which to handle the request. */
region: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Job>;
/** Lists regions/{region}/jobs in a project. */
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Optional. If set, the returned jobs list includes only jobs that were submitted to the named cluster. */
clusterName?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* Optional. A filter constraining the jobs to list. Filters are case-sensitive and have the following syntax:field = value AND field = value ...where
* field is status.state or labels.[KEY], and [KEY] is a label key. value can be * to match all values. status.state can be either ACTIVE or INACTIVE.
* Only the logical AND operator is supported; space-separated items are treated as having an implicit AND operator.Example filter:status.state = ACTIVE
* AND labels.env = staging AND labels.starred = *
*/
filter?: string;
/** Optional. Specifies enumerated categories of jobs to list (default = match ALL jobs). */
jobStateMatcher?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Optional. The number of results to return in each response. */
pageSize?: number;
/** Optional. The page token, returned by a previous call, to request the next page of results. */
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Required. The ID of the Google Cloud Platform project that the job belongs to. */
projectId: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Required. The Cloud Dataproc region in which to handle the request. */
region: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListJobsResponse>;
/** Updates a job in a project. */
patch(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** Required. The job ID. */
jobId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Required. The ID of the Google Cloud Platform project that the job belongs to. */
projectId: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Required. The Cloud Dataproc region in which to handle the request. */
region: string;
/**
* Required. Specifies the path, relative to <code>Job</code>, of the field to update. For example, to update the labels of a Job the
* <code>update_mask</code> parameter would be specified as <code>labels</code>, and the PATCH request body would specify the new value.
* <strong>Note:</strong> Currently, <code>labels</code> is the only field that can be updated.
*/
updateMask?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Job>;
/** Submits a job to a cluster. */
submit(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Required. The ID of the Google Cloud Platform project that the job belongs to. */
projectId: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Required. The Cloud Dataproc region in which to handle the request. */
region: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Job>;
}
interface OperationsResource {
/**
* Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If
* the server doesn't support this method, it returns google.rpc.Code.UNIMPLEMENTED. Clients can use Operations.GetOperation or other methods to check
* whether the cancellation succeeded or whether the operation completed despite cancellation. On successful cancellation, the operation is not deleted;
* instead, it becomes an operation with an Operation.error value with a google.rpc.Status.code of 1, corresponding to Code.CANCELLED.
*/
cancel(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the operation resource to be cancelled. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/**
* Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the
* operation. If the server doesn't support this method, it returns google.rpc.Code.UNIMPLEMENTED.
*/
delete(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the operation resource to be deleted. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/**
* Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API
* service.
*/
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the operation resource. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Operation>;
/**
* Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns UNIMPLEMENTED.NOTE: the name
* binding allows API services to override the binding to use different resource name schemes, such as users/*/operations. To override the binding, API
* services can add a binding such as "/v1/{name=users/*}/operations" to their service configuration. For backwards compatibility, the default name
* includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection
* id.
*/
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** The standard list filter. */
filter?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the operation's parent resource. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The standard list page size. */
pageSize?: number;
/** The standard list page token. */
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListOperationsResponse>;
}
interface RegionsResource {
clusters: ClustersResource;
jobs: JobsResource;
operations: OperationsResource;
}
interface ProjectsResource {
regions: RegionsResource;
}
}
} | the_stack |
import { PdfAnnotationBaseModel, PdfFormFieldBaseModel } from './pdf-annotation-model';
import { DrawingElement, TextElement, PointModel, Point, BaseAttributes, rotateMatrix, identityMatrix, transformPointByMatrix, Matrix } from '@syncfusion/ej2-drawings';
import { Transforms } from './drawing';
import { getValue } from '@syncfusion/ej2-base';
/**
* @param {PdfAnnotationBaseModel} obj - Specified the shape annotation object.
* @hidden
* @returns {void}
*/
export function isLineShapes(obj: PdfAnnotationBaseModel): boolean {
if (obj.shapeAnnotationType === 'Line' || obj.shapeAnnotationType === 'LineWidthArrowHead'
|| obj.shapeAnnotationType === 'Distance' || obj.shapeAnnotationType === 'Polygon') {
return true;
}
return false;
}
/**
* @param {PdfAnnotationBaseModel | PdfFormFieldBaseModel} obj - Specified the annotation or form fields object.
* @param {DrawingElement} element - Specified the annotation drawing element.
* @returns {void}
* @hidden
*/
export function setElementStype(obj: PdfAnnotationBaseModel | PdfFormFieldBaseModel, element: DrawingElement): void {
if (obj && element) {
if ((obj as PdfFormFieldBaseModel).formFieldAnnotationType) {
if (obj.id.indexOf('diagram_helper') !== -1) {
element.style.fill = 'transparent';
element.style.strokeWidth = 1;
element.style.strokeDashArray = (obj as PdfAnnotationBaseModel).borderDashArray;
} else {
element.style.fill = 'transparent';
element.style.strokeWidth = 0;
}
} else {
const fillColor: string = ((obj as PdfAnnotationBaseModel).fillColor === '#ffffff00' ? 'transparent' : (obj as PdfAnnotationBaseModel).fillColor);
element.style.fill = fillColor ? fillColor : 'white';
// eslint-disable-next-line max-len
element.style.strokeColor = (obj as PdfAnnotationBaseModel).strokeColor ? (obj as PdfAnnotationBaseModel).strokeColor : (obj as PdfFormFieldBaseModel).borderColor;
// eslint-disable-next-line max-len
(element as TextElement).style.color = (obj as PdfAnnotationBaseModel).strokeColor ? (obj as PdfAnnotationBaseModel).strokeColor : (obj as PdfFormFieldBaseModel).borderColor;
element.style.strokeWidth = obj.thickness;
if ((obj as PdfAnnotationBaseModel).shapeAnnotationType === 'Image' || (obj as PdfAnnotationBaseModel).shapeAnnotationType === 'SignatureText' || (obj as PdfAnnotationBaseModel).shapeAnnotationType === 'SignatureImage' ) {
element.style.strokeWidth = 0;
}
element.style.strokeDashArray = (obj as PdfAnnotationBaseModel).borderDashArray;
element.style.opacity = obj.opacity;
}
}
}
/**
* @param {PointModel[]} points - Specified the annotation points value.
* @hidden
* @returns {number} - Returns the points length.
*/
export function findPointsLength(points: PointModel[]): number {
let length: number = 0;
for (let i: number = 0; i < points.length - 1; i++) {
length += Point.findLength(points[i], points[i + 1]);
}
return length;
}
/**
* @param {PointModel[]} points - Specified the annotation points value.
* @hidden
* @returns {number} - Returns the points length.
*/
export function findPerimeterLength(points: PointModel[]): number {
const length: number = Point.getLengthFromListOfPoints(points);
return length;
}
/**
* @private
* @param {DrawingElement} element - Specified the drawing element.
* @param {Transforms} transform - Specified the transform value.
* @returns {BaseAttributes} - Returns the base attributes value.
*/
export function getBaseShapeAttributes(element: DrawingElement, transform?: Transforms): BaseAttributes {
const baseShapeAttributes: BaseAttributes = {
width: element.actualSize.width, height: element.actualSize.height,
x: element.offsetX - element.actualSize.width * element.pivot.x + 0.5,
y: element.offsetY - element.actualSize.height * element.pivot.y + 0.5,
angle: element.rotateAngle + element.parentTransform, fill: element.style.fill, stroke: element.style.strokeColor,
pivotX: element.pivot.x, pivotY: element.pivot.y, strokeWidth: 1,
opacity: element.style.opacity, dashArray: element.style.strokeDashArray || '',
visible: element.visible, id: element.id
};
if (transform) {
baseShapeAttributes.x += transform.tx;
baseShapeAttributes.y += transform.ty;
}
return baseShapeAttributes;
}
/**
* Get function
*
* @private
* @param {Function | string} value - Type of the function.
* @returns {Function} - Returns the function.
*/
export function getFunction(value: Function | string): Function {
if (value !== undefined) {
if (typeof value === 'string') {
value = getValue(value, window);
}
}
return value as Function;
}
/**
* @private
* @param {any} obj - Specified the annotation object.
* @param {Function | string} additionalProp - Specified the annotation additional properties.
* @param {string} key - Specified the annotation key value.
* @returns {Object} - Returns the cloned object.
*/
// eslint-disable-next-line
export function cloneObject(obj: any, additionalProp?: Function | string, key?: string): Object {
// eslint-disable-next-line
let newObject: any = {};
const keys: string = 'properties';
const prop: string = 'propName';
if (obj) {
key = obj[prop];
const sourceObject: Object = obj[keys] || obj;
let properties: string[] = [];
properties = properties.concat(Object.keys(sourceObject));
let customProperties: string[] = [];
properties.push('version');
if (key) {
const propAdditional: Function = getFunction(additionalProp);
if (propAdditional) {
customProperties = propAdditional(key);
} else {
customProperties = [];
}
properties = properties.concat(customProperties);
}
const internalProp: string[] = getInternalProperties(key);
properties = properties.concat(internalProp);
for (const property of properties) {
if (property !== 'historyManager') {
if (property !== 'wrapper') {
// eslint-disable-next-line
const isEventEmmitter: boolean = obj[property] && (obj as any).hasOwnProperty('observers') ? true : false;
if (!isEventEmmitter) {
if (obj[property] instanceof Array) {
newObject[property] = cloneArray(
(internalProp.indexOf(property) === -1 && obj[keys]) ? obj[keys][property] : obj[property],
additionalProp, property);
} else if (obj[property] instanceof Array === false && obj[property] instanceof HTMLElement) {
newObject[property] = obj[property].cloneNode(true).innerHtml;
} else if (obj[property] instanceof Array === false && obj[property] instanceof Object) {
newObject[property] = cloneObject(
(internalProp.indexOf(property) === -1 && obj[keys]) ? obj[keys][property] : obj[property]);
} else {
newObject[property] = obj[property];
}
}
} else {
if (obj[property]) {
newObject[property] = {
actualSize: {
width: obj[property].actualSize.width, height: obj[property].actualSize.height
}, offsetX: obj[property].offsetX, offsetY: obj[property].offsetY
};
}
}
}
}
}
return newObject;
}
/**
* @private
* @param {Object[]} sourceArray - Specified the annotation source collections.
* @param {Function | string} additionalProp - Specified the annotation additional properties.
* @param {string} key - Specified the annotation key value.
* @returns {Object[]} - Returns the cloned object array.
*/
export function cloneArray(sourceArray: Object[], additionalProp?: Function | string, key?: string): Object[] {
let clonedArray: Object[];
if (sourceArray) {
clonedArray = [];
for (let i: number = 0; i < sourceArray.length; i++) {
if (sourceArray[i] instanceof Array) {
clonedArray.push(sourceArray[i]);
} else if (sourceArray[i] instanceof Object) {
clonedArray.push(cloneObject(sourceArray[i], additionalProp, key));
} else {
clonedArray.push(sourceArray[i]);
}
}
}
return clonedArray;
}
/**
* @private
* @param {string} propName - Specified the annotation property name.
* @returns {string[]} - Returns the internal properties.
*/
export function getInternalProperties(propName: string): string[] {
switch (propName) {
case 'nodes':
case 'children':
return ['inEdges', 'outEdges', 'parentId', 'processId', 'nodeId', 'umlIndex', 'isPhase', 'isLane'];
case 'connectors':
return ['parentId'];
case 'annotation':
return ['nodeId'];
case 'annotations':
return ['nodeId'];
case 'shape':
return ['hasHeader'];
}
return [];
}
/**
* @param {PdfAnnotationBaseModel} obj - Specified the annotation object.
* @param {string} position - Specified the annotation position.
* @hidden
* @returns {Leader} - Returns the leader value.
*/
export function isLeader(obj: PdfAnnotationBaseModel, position: string): Leader {
let rotatedPoint: PointModel;
if (obj.shapeAnnotationType === 'Distance') {
let leaderCount: number = 0;
let newPoint1: PointModel;
for (let i: number = 0; i < obj.wrapper.children.length; i++) {
const angle: number = Point.findAngle(obj.sourcePoint, obj.targetPoint);
// eslint-disable-next-line
let segment: any = obj.wrapper.children[i];
if (segment.id.indexOf('leader') > -1) {
let center: PointModel = obj.wrapper.children[0].bounds.center;
if (leaderCount === 0) {
newPoint1 = { x: obj.sourcePoint.x, y: obj.sourcePoint.y - obj.leaderHeight };
center = obj.sourcePoint;
} else {
newPoint1 = { x: obj.targetPoint.x, y: obj.targetPoint.y - obj.leaderHeight };
center = obj.targetPoint;
}
const matrix: Matrix = identityMatrix();
rotateMatrix(matrix, angle, center.x, center.y);
rotatedPoint = transformPointByMatrix(matrix, { x: newPoint1.x, y: newPoint1.y });
if (position === 'Leader' + leaderCount) {
return { leader: 'leader' + leaderCount, point: rotatedPoint };
}
leaderCount++;
}
}
}
return { leader: '', point: rotatedPoint };
}
/**
* @hidden
*/
export interface Leader {
leader: string
point: PointModel
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.