type
stringclasses
7 values
content
stringlengths
4
9.55k
repo
stringlengths
7
96
path
stringlengths
4
178
language
stringclasses
1 value
ArrowFunction
name => { if (!ruleNames[name]) { throw new Error(`found undefined reference ${name}`); } }
74th/ls-ebnf-parser
src/ruleparser.ts
TypeScript
ClassDeclaration
class parseError extends Error { public fragmentSize: number; constructor(message: string, fragmentSize: number) { super(message); this.fragmentSize = fragmentSize; } }
74th/ls-ebnf-parser
src/ruleparser.ts
TypeScript
MethodDeclaration
public Parse(rulesDoc: string): Rules { const referencedNames = [] as string[]; let fragment = rulesDoc; const rules = [] as Rule[]; try { for (;;) { const r = this.parseRule(fragment, referencedNames); if (r) { rules.push(r.rule); fragment = r.fragment; continue; } break; } } catch (e) { if (e instanceof parseError) { const lineNumber = rulesDoc .substr(0, rulesDoc.length - e.fragmentSize) .split('\n').length; throw new Error(`${e.message} lineNumber:${lineNumber}`); } throw e; } this.checkReferences(rules, referencedNames); return { rules: rules, rootRule: rules[0].name, reservedWords: [], tokenExcludeRules: [], }; }
74th/ls-ebnf-parser
src/ruleparser.ts
TypeScript
MethodDeclaration
private parseRule( inputFragment: string, referenceNames: string[] ): {rule: Rule; fragment: string} | null { let fragment = inputFragment.trimStart(); for (;;) { if (fragment.length == 0) { return null; } if (fragment.match(/^[(][*]/)) { // comment const n = fragment.substr(2).search(/[*][)]/); fragment = fragment.substr(2 + n + 2); continue; } break; } const match = fragment.match(/^([\w]+)\s*=/); if (!match) { throw new parseError('can not parse document', fragment.length); } const name = match[1].trimStart(); fragment = fragment.substr(match[0].length); const r = this.parseAlternationNode(fragment, ';', referenceNames); return { rule: { name: name, root: r.node, }, fragment: r.fragment, }; }
74th/ls-ebnf-parser
src/ruleparser.ts
TypeScript
MethodDeclaration
private parseAlternationNode( inputFragment: string, closeBracket: string, referenceNames: string[] ): {node: RuleNode; fragment: string} { const alternations = [[]] as RuleNode[][]; let nodes = alternations[0] as RuleNode[]; let fragment = inputFragment; for (;;) { fragment = fragment.trimStart(); if (!fragment) { break; } if (fragment.match(/^["']/)) { // string const r = this.parseStringNode(fragment); fragment = r.fragment; nodes.push(r.node); continue; } if (fragment.match(/^\//)) { // regex const r = this.parseRegexNode(fragment); fragment = r.fragment; nodes.push(r.node); continue; } if (fragment.match(/^\w/)) { // reference const r = this.parseReferenceNode(fragment, referenceNames); fragment = r.fragment; nodes.push(r.node); continue; } if (fragment.match(/^,/)) { // concatenation fragment = fragment.substr(1); continue; } if (fragment.match(/^[|]/)) { // alternation nodes = []; alternations.push(nodes); fragment = fragment.substr(1); continue; } if (fragment.match(/^[(][*]/)) { // comment const n = fragment.substr(2).search(/[*][)]/); fragment = fragment.substr(2 + n + 2); continue; } if (fragment.match(/^[(]/)) { // alternation or group const r = this.parseAlternationNode( fragment.substr(1), ')', [] ); nodes.push(r.node); fragment = r.fragment; continue; } if (fragment.match(/^[/[]/)) { // option const r = this.parseAlternationNode( fragment.substr(1), ']', [] ); nodes.push({ type: 'option', node: r.node, }); fragment = r.fragment; continue; } if (fragment.match(/^[{]/)) { // repeat const r = this.parseAlternationNode( fragment.substr(1), '}', [] ); nodes.push({ type: 'repeat', node: r.node, }); fragment = r.fragment; continue; } if (fragment.match(/^[)\]};]/)) { // close group Node if (!closeBracket) { throw new parseError('cannot parse', fragment.length); } if (fragment[0] != closeBracket) { throw new parseError('cannot parse', fragment.length); } fragment = fragment.substr(1); break; } } if (alternations.length == 1) { if (nodes.length == 0) { throw new parseError('cannot parse', fragment.length); } if (nodes.length == 1) { return { node: nodes[0], fragment, }; } return { node: { type: 'group', nodes, }, fragment, }; } else { const alternationNodes = alternations.map( (nodes): RuleNode => { if (nodes.length == 0) { throw new parseError('cannot parse', fragment.length); } if (nodes.length == 1) { return nodes[0]; } return { type: 'group', nodes, }; } ); return { node: { type: 'alternation', nodes: alternationNodes, }, fragment, }; } }
74th/ls-ebnf-parser
src/ruleparser.ts
TypeScript
MethodDeclaration
private parseStringNode( fragment: string ): {node: RuleNode; fragment: string} { let escaped = false; let text = ''; const quote = fragment[0]; for (let i = 1; i < fragment.length; i++) { if (escaped) { escaped = false; switch (fragment[i]) { case 'n': case 'r': text += '\n'; break; default: text += fragment[i]; } } else { switch (fragment[i]) { case quote: return { node: { type: 'string', text, }, fragment: fragment.substr(i + 1), }; case '\\': escaped = true; break; default: text += fragment[i]; } } } throw new parseError('parse error', fragment.length); }
74th/ls-ebnf-parser
src/ruleparser.ts
TypeScript
MethodDeclaration
private parseRegexNode( fragment: string ): {node: RuleNode; fragment: string} { let text = ''; for (let i = 1; i < fragment.length; i++) { switch (fragment[i]) { case '/': return { node: { type: 'regex', regex: text, }, fragment: fragment.substr(i + 1), }; default: text += fragment[i]; } } throw new parseError('parse error', fragment.length); }
74th/ls-ebnf-parser
src/ruleparser.ts
TypeScript
MethodDeclaration
private parseReferenceNode( fragment: string, referencedNames: string[] ): {node: RuleNode; fragment: string} { const name = fragment.match(/^\w+/); if (!name) { throw new Error('implemented error'); } referencedNames.push(name[0]); return { node: { type: 'reference', name: name[0], }, fragment: fragment.substr(name[0].length), }; }
74th/ls-ebnf-parser
src/ruleparser.ts
TypeScript
MethodDeclaration
private checkReferences(rules: Rule[], referencedNames: string[]) { const ruleNames = {} as {[index: string]: boolean}; rules.forEach(rule => { ruleNames[rule.name] = true; }); referencedNames.forEach(name => { if (!ruleNames[name]) { throw new Error(`found undefined reference ${name}`); } }); }
74th/ls-ebnf-parser
src/ruleparser.ts
TypeScript
ArrowFunction
() => { it ('getParsedStatement should return null when no operation match', () => { const matcher = new StatementMatcher( 'select', /^[^\S]*?select\b[\s\S]+?\bfrom[\s\n\r\[\(]+([^\]\s\n\r,)(;]*)/gim ); const res = matcher.getParsedStatement('update user set age=1;'); expect(res).to.be.null; }); }
MichaelMULLER/pandora
packages/component-auto-patching/test/StatementMatcher.test.ts
TypeScript
ArrowFunction
() => { const matcher = new StatementMatcher( 'select', /^[^\S]*?select\b[\s\S]+?\bfrom[\s\n\r\[\(]+([^\]\s\n\r,)(;]*)/gim ); const res = matcher.getParsedStatement('update user set age=1;'); expect(res).to.be.null; }
MichaelMULLER/pandora
packages/component-auto-patching/test/StatementMatcher.test.ts
TypeScript
ArrowFunction
(event) => { if (!event.data || (event.data !== 'ok' && !event.data.error)) { return; } const eventSourceWindow = event.source as Window; const childRunner = ChildRunner.get(eventSourceWindow); if (!childRunner) { return; } childRunner.ready(); // The name of the suite as exposed to the user. const reporter = childRunner.parentScope.WCT._reporter; const title = reporter.suiteTitle(eventSourceWindow.location); reporter.emitOutOfBandTest( 'page-wide tests via global done()', event.data.error, title, true); childRunner.done(); }
Acidburn0zzz/learn-reader
packages/wct-mocha/src/environment/compatability.ts
TypeScript
ArrowFunction
(_event: BeforeUnloadEvent) => { // Mocha's hook queue is asynchronous; but we want synchronous behavior if // we've gotten to the point of unloading the document. Mocha.Runner['immediately'] = (callback: () => void) => { callback(); }; }
Acidburn0zzz/learn-reader
packages/wct-mocha/src/environment/compatability.ts
TypeScript
ArrowFunction
(callback: () => void) => { callback(); }
Acidburn0zzz/learn-reader
packages/wct-mocha/src/environment/compatability.ts
TypeScript
ArrowFunction
async (configService: ConfigService) => { console.log('MONGO_URI=', process.env.MONGO_URI); return ({ uri: process.env.MONGO_URI || configService.get('MONGO_URI'), useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, }); }
ethiers/quote-server
src/app.module.ts
TypeScript
ClassDeclaration
@Module({ imports: [MongooseModule.forRootAsync({ imports: [ConfigModule], useFactory: async (configService: ConfigService) => { console.log('MONGO_URI=', process.env.MONGO_URI); return ({ uri: process.env.MONGO_URI || configService.get('MONGO_URI'), useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, }); }, inject: [ConfigService], }), QuotesModule, ConfigModule], controllers: [AppController], providers: [AppService], }) export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer): any { consumer.apply(LoggerMiddleware).forRoutes('quotes'); } }
ethiers/quote-server
src/app.module.ts
TypeScript
MethodDeclaration
configure(consumer: MiddlewareConsumer): any { consumer.apply(LoggerMiddleware).forRoutes('quotes'); }
ethiers/quote-server
src/app.module.ts
TypeScript
ArrowFunction
() => { let componentWrapper: RenderResult; let componentProps: React.ComponentProps<typeof GestionPedido> & { listarPedido: SinonStub; finalizarPedido: SinonStub; eliminarProductoSolicitado: SinonStub; }; beforeEach(() => { componentProps = { pedido: { id: 1, numeroPedido: '123456789', direccion: '', cliente: '', estado: '', costo: 10000, tiempo: 30, productosSolicitados:[] }, listarPedido: stub(), finalizarPedido: stub(), eliminarProductoSolicitado: stub(), }; componentWrapper = render(<GestionPedido {...componentProps} />); }); it('should match snapshot', () => { expect(componentWrapper.container).toMatchSnapshot(); }); }
davidecb/adn-ceiba-front
src/app/feature/Pedido/containers/GestionPedido/GestionPedido.spec.tsx
TypeScript
ArrowFunction
() => { componentProps = { pedido: { id: 1, numeroPedido: '123456789', direccion: '', cliente: '', estado: '', costo: 10000, tiempo: 30, productosSolicitados:[] }, listarPedido: stub(), finalizarPedido: stub(), eliminarProductoSolicitado: stub(), }; componentWrapper = render(<GestionPedido {...componentProps} />); }
davidecb/adn-ceiba-front
src/app/feature/Pedido/containers/GestionPedido/GestionPedido.spec.tsx
TypeScript
ArrowFunction
() => { expect(componentWrapper.container).toMatchSnapshot(); }
davidecb/adn-ceiba-front
src/app/feature/Pedido/containers/GestionPedido/GestionPedido.spec.tsx
TypeScript
FunctionDeclaration
/** * deploy the given contract * * @param {String} from - sender address * @param {String} data - data to send with the transaction ( return of txFormat.buildData(...) ). * @param {String} value - decimal representation of value. * @param {String} gasLimit - decimal representation of gas limit. * @param {Object} txRunner - TxRunner.js instance * @param {Object} callbacks - { confirmationCb, gasEstimationForceSend, promptCb } * [validate transaction] confirmationCb (network, tx, gasEstimation, continueTxExecution, cancelCb) * [transaction failed, force send] gasEstimationForceSend (error, continueTxExecution, cancelCb) * [personal mode enabled, need password to continue] promptCb (okCb, cancelCb) * @param {Function} finalCallback - last callback. */ export function createContract (from, data, value, gasLimit, txRunner, callbacks, finalCallback) { if (!callbacks.confirmationCb || !callbacks.gasEstimationForceSend || !callbacks.promptCb) { return finalCallback('all the callbacks must have been defined') } const tx = { from: from, to: null, data: data, useCall: false, value: value, gasLimit: gasLimit } txRunner.rawRun(tx, callbacks.confirmationCb, callbacks.gasEstimationForceSend, callbacks.promptCb, (error, txResult) => { // see universaldapp.js line 660 => 700 to check possible values of txResult (error case) finalCallback(error, txResult) }) }
KenMan79/remix-project
libs/remix-lib/src/execution/txExecution.ts
TypeScript
FunctionDeclaration
/** * call the current given contract ! that will create a transaction ! * * @param {String} from - sender address * @param {String} to - recipient address * @param {String} data - data to send with the transaction ( return of txFormat.buildData(...) ). * @param {String} value - decimal representation of value. * @param {String} gasLimit - decimal representation of gas limit. * @param {Object} txRunner - TxRunner.js instance * @param {Object} callbacks - { confirmationCb, gasEstimationForceSend, promptCb } * [validate transaction] confirmationCb (network, tx, gasEstimation, continueTxExecution, cancelCb) * [transaction failed, force send] gasEstimationForceSend (error, continueTxExecution, cancelCb) * [personal mode enabled, need password to continue] promptCb (okCb, cancelCb) * @param {Function} finalCallback - last callback. */ export function callFunction (from, to, data, value, gasLimit, funAbi, txRunner, callbacks, finalCallback) { const useCall = funAbi.stateMutability === 'view' || funAbi.stateMutability === 'pure' || funAbi.constant const tx = { from, to, data, useCall, value, gasLimit } txRunner.rawRun(tx, callbacks.confirmationCb, callbacks.gasEstimationForceSend, callbacks.promptCb, (error, txResult) => { // see universaldapp.js line 660 => 700 to check possible values of txResult (error case) finalCallback(error, txResult) }) }
KenMan79/remix-project
libs/remix-lib/src/execution/txExecution.ts
TypeScript
FunctionDeclaration
/** * check if the vm has errored * * @param {Object} execResult - execution result given by the VM * @return {Object} - { error: true/false, message: DOMNode } */ export function checkVMError (execResult, abi, contract) { const errorCode = { OUT_OF_GAS: 'out of gas', STACK_UNDERFLOW: 'stack underflow', STACK_OVERFLOW: 'stack overflow', INVALID_JUMP: 'invalid JUMP', INVALID_OPCODE: 'invalid opcode', REVERT: 'revert', STATIC_STATE_CHANGE: 'static state change', INTERNAL_ERROR: 'internal error', CREATE_COLLISION: 'create collision', STOP: 'stop', REFUND_EXHAUSTED: 'refund exhausted' } const ret = { error: false, message: '' } if (!execResult.exceptionError) { return ret } const exceptionError = execResult.exceptionError.error || '' const error = `VM error: ${exceptionError}.\n` let msg if (exceptionError === errorCode.INVALID_OPCODE) { msg = '\t\n\tThe execution might have thrown.\n' ret.error = true } else if (exceptionError === errorCode.OUT_OF_GAS) { msg = '\tThe transaction ran out of gas. Please increase the Gas Limit.\n' ret.error = true } else if (exceptionError === errorCode.REVERT) { const returnData = execResult.returnValue const returnDataHex = returnData.slice(0, 4).toString('hex') let customError if (abi) { let decodedCustomErrorInputsClean for (const item of abi) { if (item.type === 'error') { // ethers doesn't crash anymore if "error" type is specified, but it doesn't extract the errors. see: // https://github.com/ethers-io/ethers.js/commit/bd05aed070ac9e1421a3e2bff2ceea150bedf9b7 // we need here to fake the type, so the "getSighash" function works properly const fn = getFunctionFragment({ ...item, type: 'function', stateMutability: 'nonpayable' }) if (!fn) continue const sign = fn.getSighash(item.name) if (!sign) continue if (returnDataHex === sign.replace('0x', '')) { customError = item.name const functionDesc = fn.getFunction(item.name) // decoding error parameters const decodedCustomErrorInputs = fn.decodeFunctionData(functionDesc, returnData) decodedCustomErrorInputsClean = {} let devdoc = {} // "contract" reprensents the compilation result containing the NATSPEC documentation if (contract && fn.functions && Object.keys(fn.functions).length) { const functionSignature = Object.keys(fn.functions)[0] // we check in the 'devdoc' if there's a developer documentation for this error devdoc = contract.object.devdoc.errors[functionSignature][0] || {} // we check in the 'userdoc' if there's an user documentation for this error const userdoc = contract.object.userdoc.errors[functionSignature][0] || {} if (userdoc) customError += ' : ' + (userdoc as any).notice // we append the user doc if any } for (const input of functionDesc.inputs) { const v = decodedCustomErrorInputs[input.name] decodedCustomErrorInputsClean[input.name] = { value: v.toString ? v.toString() : v, documentation: (devdoc as any).params[input.name] // we add the developer documentation for this input parameter if any } } break } } } if (decodedCustomErrorInputsClean) { msg = '\tThe transaction has been reverted to the initial state.\nError provided by the contract:' msg += `\n${customError}` msg += '\nParameters:' msg += `\n${JSON.stringify(decodedCustomErrorInputsClean, null, ' ')}` } } if (!customError) { // It is the hash of Error(string) if (returnData && (returnDataHex === '08c379a0')) { const abiCoder = new ethers.utils.AbiCoder() const reason = abiCoder.decode(['string'], returnData.slice(4))[0] msg = `\tThe transaction has been reverted to the initial state.\nReason provided by the contract: "${reason}".` } else { msg = '\tThe transaction has been reverted to the initial state.\nNote: The called function should be payable if you send value and the value you send should be less than your current balance.' } } ret.error = true } else if (exceptionError === errorCode.STATIC_STATE_CHANGE) { msg = '\tState changes is not allowed in Static Call context\n' ret.error = true } ret.message = `${error}\n${exceptionError}\n${msg}\nDebug the transaction to get more information.` return ret }
KenMan79/remix-project
libs/remix-lib/src/execution/txExecution.ts
TypeScript
ArrowFunction
(error, txResult) => { // see universaldapp.js line 660 => 700 to check possible values of txResult (error case) finalCallback(error, txResult) }
KenMan79/remix-project
libs/remix-lib/src/execution/txExecution.ts
TypeScript
MethodDeclaration
install(vue: Application): void { registerComponent(vue, SpAccountList) }
Siyris/vue
packages/vue/src/components/SpAccountList/index.ts
TypeScript
InterfaceDeclaration
export interface ThemeModel { themeID: number; libelle: string; ordre: number; questions: QuestionModel[]; }
ptrkvsky/nomad
src/isadom-models/questionnaire/front/ThemeModel.ts
TypeScript
ArrowFunction
params => { if (params['id'] != null) { this.fetchData(params['id']); this.isView = true; this.disabled = true; this.isReadOnly = true; } }
Hanan-Hussein/eCurfewFrontend
src/app/views/layout/master-data/police-station/add-police-station/add-police-station.component.ts
TypeScript
ArrowFunction
(response) => { if (response) { this.model.stationCode = response.stationCode; this.model.nameOfStation = response.nameOfStation; this.model.county = response.county; this.model.headOfStation = response.headOfStation; this.model.location = response.location; this.id = response.id; } else { inst.notify.showWarning(response.message); } }
Hanan-Hussein/eCurfewFrontend
src/app/views/layout/master-data/police-station/add-police-station/add-police-station.component.ts
TypeScript
ArrowFunction
(response) => { console.log(response); if (response) { inst.notify.showSuccess(response.message); this.router.navigate(['home/master-data/police-station']); } else { inst.notify.showWarning(response.message); } }
Hanan-Hussein/eCurfewFrontend
src/app/views/layout/master-data/police-station/add-police-station/add-police-station.component.ts
TypeScript
ArrowFunction
error => { console.log(error); inst.notify.showWarning(error.error.message); }
Hanan-Hussein/eCurfewFrontend
src/app/views/layout/master-data/police-station/add-police-station/add-police-station.component.ts
TypeScript
ArrowFunction
(response) => { console.log(response); if (response.code === 200) { inst.notify.showSuccess(response.message); this.router.navigate(['home/master-data/police-station']); } else { inst.notify.showWarning(response.message); } }
Hanan-Hussein/eCurfewFrontend
src/app/views/layout/master-data/police-station/add-police-station/add-police-station.component.ts
TypeScript
ClassDeclaration
@Component({ selector: 'app-add-police-station', templateUrl: './add-police-station.component.html', styleUrls: ['./add-police-station.component.scss'] }) export class AddPoliceStationComponent implements OnInit { model: PoliceStationModel; subscription: Subscription; isUpdate: boolean; isReadOnly = false; disabled = false; isView = false; @Output() id: string; constructor( private stewardService: StewardService<any, any>, private notify: Notify, protected router: Router, private route: ActivatedRoute) { this.model = new PoliceStationModel(); this.subscription = new Subscription(); } ngOnInit() { this.route.params.subscribe(params => { if (params['id'] != null) { this.fetchData(params['id']); this.isView = true; this.disabled = true; this.isReadOnly = true; } }); } private fetchData(id: number) { const inst = this; inst.subscription.add( this.stewardService.getMasterData('app/rest/v2/entities/ecurfew_PoliceStation/' + id).subscribe((response) => { if (response) { this.model.stationCode = response.stationCode; this.model.nameOfStation = response.nameOfStation; this.model.county = response.county; this.model.headOfStation = response.headOfStation; this.model.location = response.location; this.id = response.id; } else { inst.notify.showWarning(response.message); } }) ); } @HostListener('window:beforeunload') // tslint:disable-next-line: use-life-cycle-interface ngOnDestroy(): void { if (this.subscription) { this.subscription.unsubscribe(); } } enableUpdate() { this.isReadOnly = false; this.isUpdate = !this.isUpdate; } disableUpdate() { this.isReadOnly = true; this.isUpdate = !this.isUpdate; } onCreateForm(createForm: NgForm) { const params: Map<any, string> = new Map(); const inst = this; if (this.isUpdate) { this.stewardService.put('app/rest/v2/update/station/' + this.id, this.model).subscribe((response) => { console.log(response); if (response) { inst.notify.showSuccess(response.message); this.router.navigate(['home/master-data/police-station']); } else { inst.notify.showWarning(response.message); } }, error => { console.log(error); inst.notify.showWarning(error.error.message); }); } else { this.stewardService.post('app/rest/v2/services/ecurfew_CreateMasterDataService/createPoliceStation', {policeStation: this.model}).subscribe((response) => { console.log(response); if (response.code === 200) { inst.notify.showSuccess(response.message); this.router.navigate(['home/master-data/police-station']); } else { inst.notify.showWarning(response.message); } }, error => { console.log(error); inst.notify.showWarning(error.error.message); }); } } }
Hanan-Hussein/eCurfewFrontend
src/app/views/layout/master-data/police-station/add-police-station/add-police-station.component.ts
TypeScript
MethodDeclaration
ngOnInit() { this.route.params.subscribe(params => { if (params['id'] != null) { this.fetchData(params['id']); this.isView = true; this.disabled = true; this.isReadOnly = true; } }); }
Hanan-Hussein/eCurfewFrontend
src/app/views/layout/master-data/police-station/add-police-station/add-police-station.component.ts
TypeScript
MethodDeclaration
private fetchData(id: number) { const inst = this; inst.subscription.add( this.stewardService.getMasterData('app/rest/v2/entities/ecurfew_PoliceStation/' + id).subscribe((response) => { if (response) { this.model.stationCode = response.stationCode; this.model.nameOfStation = response.nameOfStation; this.model.county = response.county; this.model.headOfStation = response.headOfStation; this.model.location = response.location; this.id = response.id; } else { inst.notify.showWarning(response.message); } }) ); }
Hanan-Hussein/eCurfewFrontend
src/app/views/layout/master-data/police-station/add-police-station/add-police-station.component.ts
TypeScript
MethodDeclaration
@HostListener('window:beforeunload') // tslint:disable-next-line: use-life-cycle-interface ngOnDestroy(): void { if (this.subscription) { this.subscription.unsubscribe(); } }
Hanan-Hussein/eCurfewFrontend
src/app/views/layout/master-data/police-station/add-police-station/add-police-station.component.ts
TypeScript
MethodDeclaration
enableUpdate() { this.isReadOnly = false; this.isUpdate = !this.isUpdate; }
Hanan-Hussein/eCurfewFrontend
src/app/views/layout/master-data/police-station/add-police-station/add-police-station.component.ts
TypeScript
MethodDeclaration
disableUpdate() { this.isReadOnly = true; this.isUpdate = !this.isUpdate; }
Hanan-Hussein/eCurfewFrontend
src/app/views/layout/master-data/police-station/add-police-station/add-police-station.component.ts
TypeScript
MethodDeclaration
onCreateForm(createForm: NgForm) { const params: Map<any, string> = new Map(); const inst = this; if (this.isUpdate) { this.stewardService.put('app/rest/v2/update/station/' + this.id, this.model).subscribe((response) => { console.log(response); if (response) { inst.notify.showSuccess(response.message); this.router.navigate(['home/master-data/police-station']); } else { inst.notify.showWarning(response.message); } }, error => { console.log(error); inst.notify.showWarning(error.error.message); }); } else { this.stewardService.post('app/rest/v2/services/ecurfew_CreateMasterDataService/createPoliceStation', {policeStation: this.model}).subscribe((response) => { console.log(response); if (response.code === 200) { inst.notify.showSuccess(response.message); this.router.navigate(['home/master-data/police-station']); } else { inst.notify.showWarning(response.message); } }, error => { console.log(error); inst.notify.showWarning(error.error.message); }); } }
Hanan-Hussein/eCurfewFrontend
src/app/views/layout/master-data/police-station/add-police-station/add-police-station.component.ts
TypeScript
ArrowFunction
() => { let testServer: ApolloServer; const username: string = "jimmy"; const email: string = "[email protected]"; const password: string = "notHashed!"; beforeAll(async () => { testServer = await createTestServer(); }); describe("when the username is taken", () => { let result: GraphQLResponse; let duplicateUser: User; beforeAll(async () => { duplicateUser = await factory .for(User) .with({ username }) .create(); const { mutate } = createTestClient(testServer); result = await mutate({ mutation: registerMutation, variables: { formData: { username, email, password } } }); }); afterAll(async () => { await connection.manager.delete(User, duplicateUser.id); }); it("returns an error", () => { expect(result.errors![0]).toBeInstanceOf(GraphQLError); }); it("does not create the user record", async () => { const user = await connection.manager.findOne(User, { where: { email } }); expect(user).toBeUndefined(); }); it("does not send a confirmation email", () => { expect(sendMail).not.toHaveBeenCalled(); }); }); describe("when the email is taken", () => { let result: GraphQLResponse; let duplicateUser: User; beforeAll(async () => { duplicateUser = await factory .for(User) .with({ email }) .create(); const { mutate } = createTestClient(testServer); result = await mutate({ mutation: registerMutation, variables: { formData: { username, email, password } } }); }); afterAll(async () => { await connection.manager.delete(User, duplicateUser.id); }); it("returns an error", () => { expect(result.errors![0]).toBeInstanceOf(GraphQLError); }); it("does not create the user record", async () => { const user = await connection.manager.findOne(User, { where: { username } }); expect(user).toBeUndefined(); }); it("does not send a confirmation email", () => { expect(sendMail).not.toHaveBeenCalled(); }); }); describe("when the password is invalid", () => { let result: GraphQLResponse; beforeAll(async () => { const { mutate } = createTestClient(testServer); result = await mutate({ mutation: registerMutation, variables: { formData: { username, email, password: "weak" } } }); }); it("returns an error", () => { expect(result.errors![0]).toBeInstanceOf(GraphQLError); }); it("does not create the user record", async () => { const user = await connection.manager.findOne(User, { where: { username } }); expect(user).toBeUndefined(); }); it("does not send a confirmation email", () => { expect(sendMail).not.toHaveBeenCalled(); }); }); describe("when all fields are valid", () => { let result: GraphQLResponse; beforeAll(async () => { const { mutate } = createTestClient(testServer); result = await mutate({ mutation: registerMutation, variables: { formData: { username, email, password } } }); }); it("returns the user", () => { expect(result!.data!.register).toMatchObject({ username, email }); }); it("stores a hashed password", async () => { const user = await connection.manager.findOne(User, { where: { email } }); expect(user!.password).not.toEqual(password); }); it("sends a confirmation email", () => { expect(sendMail).toHaveBeenCalled(); }); }); }
yis4yimmy/typescript-graphql-node-server
src/authentication/Register.test.ts
TypeScript
ArrowFunction
async () => { testServer = await createTestServer(); }
yis4yimmy/typescript-graphql-node-server
src/authentication/Register.test.ts
TypeScript
ArrowFunction
() => { let result: GraphQLResponse; let duplicateUser: User; beforeAll(async () => { duplicateUser = await factory .for(User) .with({ username }) .create(); const { mutate } = createTestClient(testServer); result = await mutate({ mutation: registerMutation, variables: { formData: { username, email, password } } }); }); afterAll(async () => { await connection.manager.delete(User, duplicateUser.id); }); it("returns an error", () => { expect(result.errors![0]).toBeInstanceOf(GraphQLError); }); it("does not create the user record", async () => { const user = await connection.manager.findOne(User, { where: { email } }); expect(user).toBeUndefined(); }); it("does not send a confirmation email", () => { expect(sendMail).not.toHaveBeenCalled(); }); }
yis4yimmy/typescript-graphql-node-server
src/authentication/Register.test.ts
TypeScript
ArrowFunction
async () => { duplicateUser = await factory .for(User) .with({ username }) .create(); const { mutate } = createTestClient(testServer); result = await mutate({ mutation: registerMutation, variables: { formData: { username, email, password } } }); }
yis4yimmy/typescript-graphql-node-server
src/authentication/Register.test.ts
TypeScript
ArrowFunction
async () => { await connection.manager.delete(User, duplicateUser.id); }
yis4yimmy/typescript-graphql-node-server
src/authentication/Register.test.ts
TypeScript
ArrowFunction
() => { expect(result.errors![0]).toBeInstanceOf(GraphQLError); }
yis4yimmy/typescript-graphql-node-server
src/authentication/Register.test.ts
TypeScript
ArrowFunction
async () => { const user = await connection.manager.findOne(User, { where: { email } }); expect(user).toBeUndefined(); }
yis4yimmy/typescript-graphql-node-server
src/authentication/Register.test.ts
TypeScript
ArrowFunction
() => { expect(sendMail).not.toHaveBeenCalled(); }
yis4yimmy/typescript-graphql-node-server
src/authentication/Register.test.ts
TypeScript
ArrowFunction
() => { let result: GraphQLResponse; let duplicateUser: User; beforeAll(async () => { duplicateUser = await factory .for(User) .with({ email }) .create(); const { mutate } = createTestClient(testServer); result = await mutate({ mutation: registerMutation, variables: { formData: { username, email, password } } }); }); afterAll(async () => { await connection.manager.delete(User, duplicateUser.id); }); it("returns an error", () => { expect(result.errors![0]).toBeInstanceOf(GraphQLError); }); it("does not create the user record", async () => { const user = await connection.manager.findOne(User, { where: { username } }); expect(user).toBeUndefined(); }); it("does not send a confirmation email", () => { expect(sendMail).not.toHaveBeenCalled(); }); }
yis4yimmy/typescript-graphql-node-server
src/authentication/Register.test.ts
TypeScript
ArrowFunction
async () => { duplicateUser = await factory .for(User) .with({ email }) .create(); const { mutate } = createTestClient(testServer); result = await mutate({ mutation: registerMutation, variables: { formData: { username, email, password } } }); }
yis4yimmy/typescript-graphql-node-server
src/authentication/Register.test.ts
TypeScript
ArrowFunction
async () => { const user = await connection.manager.findOne(User, { where: { username } }); expect(user).toBeUndefined(); }
yis4yimmy/typescript-graphql-node-server
src/authentication/Register.test.ts
TypeScript
ArrowFunction
() => { let result: GraphQLResponse; beforeAll(async () => { const { mutate } = createTestClient(testServer); result = await mutate({ mutation: registerMutation, variables: { formData: { username, email, password: "weak" } } }); }); it("returns an error", () => { expect(result.errors![0]).toBeInstanceOf(GraphQLError); }); it("does not create the user record", async () => { const user = await connection.manager.findOne(User, { where: { username } }); expect(user).toBeUndefined(); }); it("does not send a confirmation email", () => { expect(sendMail).not.toHaveBeenCalled(); }); }
yis4yimmy/typescript-graphql-node-server
src/authentication/Register.test.ts
TypeScript
ArrowFunction
async () => { const { mutate } = createTestClient(testServer); result = await mutate({ mutation: registerMutation, variables: { formData: { username, email, password: "weak" } } }); }
yis4yimmy/typescript-graphql-node-server
src/authentication/Register.test.ts
TypeScript
ArrowFunction
() => { let result: GraphQLResponse; beforeAll(async () => { const { mutate } = createTestClient(testServer); result = await mutate({ mutation: registerMutation, variables: { formData: { username, email, password } } }); }); it("returns the user", () => { expect(result!.data!.register).toMatchObject({ username, email }); }); it("stores a hashed password", async () => { const user = await connection.manager.findOne(User, { where: { email } }); expect(user!.password).not.toEqual(password); }); it("sends a confirmation email", () => { expect(sendMail).toHaveBeenCalled(); }); }
yis4yimmy/typescript-graphql-node-server
src/authentication/Register.test.ts
TypeScript
ArrowFunction
async () => { const { mutate } = createTestClient(testServer); result = await mutate({ mutation: registerMutation, variables: { formData: { username, email, password } } }); }
yis4yimmy/typescript-graphql-node-server
src/authentication/Register.test.ts
TypeScript
ArrowFunction
() => { expect(result!.data!.register).toMatchObject({ username, email }); }
yis4yimmy/typescript-graphql-node-server
src/authentication/Register.test.ts
TypeScript
ArrowFunction
async () => { const user = await connection.manager.findOne(User, { where: { email } }); expect(user!.password).not.toEqual(password); }
yis4yimmy/typescript-graphql-node-server
src/authentication/Register.test.ts
TypeScript
ArrowFunction
() => { expect(sendMail).toHaveBeenCalled(); }
yis4yimmy/typescript-graphql-node-server
src/authentication/Register.test.ts
TypeScript
ArrowFunction
props => ( <svg width={19}
codesee-sandbox/ricos
packages/editor/web/src/RichContentEditor/Icons/UnderlineIcon.tsx
TypeScript
ArrowFunction
(theme: GrafanaTheme) => { const bgColor = selectThemeVariant({ light: theme.colors.gray7, dark: theme.colors.dark2 }, theme.type); return { hoverBackground: css` label: hoverBackground; background-color: ${bgColor}; `, logsRowLevelDetails: css` label: logs-row__level_details; &::after { top: -3px; } `, logDetailsDefaultCursor: css` label: logDetailsDefaultCursor; cursor: default; `, }; }
91jme/grafana
packages/grafana-ui/src/components/Logs/LogDetails.tsx
TypeScript
ArrowFunction
(rowEntry): FieldDef[] => { const parser = this.getParser(rowEntry); if (!parser) { return []; } // Use parser to highlight detected fields const parsedFields = parser.getFields(rowEntry); const fields = parsedFields.map(field => { const key = parser.getLabelFromField(field); const value = parser.getValueFromField(field); return { key, value }; }); return fields; }
91jme/grafana
packages/grafana-ui/src/components/Logs/LogDetails.tsx
TypeScript
ArrowFunction
field => { const key = parser.getLabelFromField(field); const value = parser.getValueFromField(field); return { key, value }; }
91jme/grafana
packages/grafana-ui/src/components/Logs/LogDetails.tsx
TypeScript
ArrowFunction
(row: LogRowModel): FieldDef[] => { return ( row.dataFrame.fields .map((field, index) => ({ ...field, index })) // Remove Id which we use for react key and entry field which we are showing as the log message. .filter((field, index) => 'id' !== field.name && row.entryFieldIndex !== index) // Filter out fields without values. For example in elastic the fields are parsed from the document which can // have different structure per row and so the dataframe is pretty sparse. .filter(field => { const value = field.values.get(row.rowIndex); // Not sure exactly what will be the empty value here. And we want to keep 0 as some values can be non // string. return value !== null && value !== undefined; }) .map(field => { const { getFieldLinks } = this.props; const links = getFieldLinks ? getFieldLinks(field, row.rowIndex) : []; return { key: field.name, value: field.values.get(row.rowIndex).toString(), links: links.map(link => link.href), fieldIndex: field.index, }; }) ); }
91jme/grafana
packages/grafana-ui/src/components/Logs/LogDetails.tsx
TypeScript
ArrowFunction
(field, index) => ({ ...field, index })
91jme/grafana
packages/grafana-ui/src/components/Logs/LogDetails.tsx
TypeScript
ArrowFunction
(field, index) => 'id' !== field.name && row.entryFieldIndex !== index
91jme/grafana
packages/grafana-ui/src/components/Logs/LogDetails.tsx
TypeScript
ArrowFunction
field => { const value = field.values.get(row.rowIndex); // Not sure exactly what will be the empty value here. And we want to keep 0 as some values can be non // string. return value !== null && value !== undefined; }
91jme/grafana
packages/grafana-ui/src/components/Logs/LogDetails.tsx
TypeScript
ArrowFunction
field => { const { getFieldLinks } = this.props; const links = getFieldLinks ? getFieldLinks(field, row.rowIndex) : []; return { key: field.name, value: field.values.get(row.rowIndex).toString(), links: links.map(link => link.href), fieldIndex: field.index, }; }
91jme/grafana
packages/grafana-ui/src/components/Logs/LogDetails.tsx
TypeScript
ArrowFunction
link => link.href
91jme/grafana
packages/grafana-ui/src/components/Logs/LogDetails.tsx
TypeScript
ArrowFunction
(row: LogRowModel) => { const fields = this.parseMessage(row.entry); const derivedFields = this.getDerivedFields(row); const fieldsMap = [...derivedFields, ...fields].reduce((acc, field) => { // Strip enclosing quotes for hashing. When values are parsed from log line the quotes are kept, but if same // value is in the dataFrame it will be without the quotes. We treat them here as the same value. const value = field.value.replace(/(^")|("$)/g, ''); const fieldHash = `${field.key}=${value}`; if (acc[fieldHash]) { acc[fieldHash].links = [...(acc[fieldHash].links || []), ...(field.links || [])]; } else { acc[fieldHash] = field; } return acc; }, {} as { [key: string]: FieldDef }); return Object.values(fieldsMap); }
91jme/grafana
packages/grafana-ui/src/components/Logs/LogDetails.tsx
TypeScript
ArrowFunction
(acc, field) => { // Strip enclosing quotes for hashing. When values are parsed from log line the quotes are kept, but if same // value is in the dataFrame it will be without the quotes. We treat them here as the same value. const value = field.value.replace(/(^")|("$)/g, ''); const fieldHash = `${field.key}=${value}`; if (acc[fieldHash]) { acc[fieldHash].links = [...(acc[fieldHash].links || []), ...(field.links || [])]; } else { acc[fieldHash] = field; } return acc; }
91jme/grafana
packages/grafana-ui/src/components/Logs/LogDetails.tsx
TypeScript
ArrowFunction
(key: string) => { const matcher = this.getParser(this.props.row.entry)!.buildMatcher(key); return calculateFieldStats(this.props.getRows(), matcher); }
91jme/grafana
packages/grafana-ui/src/components/Logs/LogDetails.tsx
TypeScript
ArrowFunction
key => { const value = labels[key]; return ( <LogDetailsRow key={`${key}=${value}`}
91jme/grafana
packages/grafana-ui/src/components/Logs/LogDetails.tsx
TypeScript
ArrowFunction
field => { const { key, value, links, fieldIndex } = field; return ( <LogDetailsRow key={`${key}=${value}`}
91jme/grafana
packages/grafana-ui/src/components/Logs/LogDetails.tsx
TypeScript
ClassDeclaration
class UnThemedLogDetails extends PureComponent<Props> { getParser = memoizeOne(getParser); parseMessage = memoizeOne((rowEntry): FieldDef[] => { const parser = this.getParser(rowEntry); if (!parser) { return []; } // Use parser to highlight detected fields const parsedFields = parser.getFields(rowEntry); const fields = parsedFields.map(field => { const key = parser.getLabelFromField(field); const value = parser.getValueFromField(field); return { key, value }; }); return fields; }); getDerivedFields = memoizeOne((row: LogRowModel): FieldDef[] => { return ( row.dataFrame.fields .map((field, index) => ({ ...field, index })) // Remove Id which we use for react key and entry field which we are showing as the log message. .filter((field, index) => 'id' !== field.name && row.entryFieldIndex !== index) // Filter out fields without values. For example in elastic the fields are parsed from the document which can // have different structure per row and so the dataframe is pretty sparse. .filter(field => { const value = field.values.get(row.rowIndex); // Not sure exactly what will be the empty value here. And we want to keep 0 as some values can be non // string. return value !== null && value !== undefined; }) .map(field => { const { getFieldLinks } = this.props; const links = getFieldLinks ? getFieldLinks(field, row.rowIndex) : []; return { key: field.name, value: field.values.get(row.rowIndex).toString(), links: links.map(link => link.href), fieldIndex: field.index, }; }) ); }); getAllFields = memoizeOne((row: LogRowModel) => { const fields = this.parseMessage(row.entry); const derivedFields = this.getDerivedFields(row); const fieldsMap = [...derivedFields, ...fields].reduce((acc, field) => { // Strip enclosing quotes for hashing. When values are parsed from log line the quotes are kept, but if same // value is in the dataFrame it will be without the quotes. We treat them here as the same value. const value = field.value.replace(/(^")|("$)/g, ''); const fieldHash = `${field.key}=${value}`; if (acc[fieldHash]) { acc[fieldHash].links = [...(acc[fieldHash].links || []), ...(field.links || [])]; } else { acc[fieldHash] = field; } return acc; }, {} as { [key: string]: FieldDef }); return Object.values(fieldsMap); }); getStatsForParsedField = (key: string) => { const matcher = this.getParser(this.props.row.entry)!.buildMatcher(key); return calculateFieldStats(this.props.getRows(), matcher); }; render() { const { row, theme, onClickFilterOutLabel, onClickFilterLabel, getRows, showDuplicates, className, onMouseEnter, onMouseLeave, } = this.props; const style = getLogRowStyles(theme, row.logLevel); const styles = getStyles(theme); const labels = row.labels ? row.labels : {}; const labelsAvailable = Object.keys(labels).length > 0; const fields = this.getAllFields(row); const parsedFieldsAvailable = fields && fields.length > 0; return ( <tr className={cx(className, styles.logDetailsDefaultCursor)} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} > {showDuplicates && <td />} <td className={cx(style.logsRowLevel, styles.logsRowLevelDetails)} /> <td colSpan={4}> <div className={style.logDetailsContainer}> <table className={style.logDetailsTable}> <tbody> {labelsAvailable && ( <tr> <td colSpan={5} className={style.logDetailsHeading} aria-label="Log Labels"> Log Labels: </td> </tr> )}
91jme/grafana
packages/grafana-ui/src/components/Logs/LogDetails.tsx
TypeScript
InterfaceDeclaration
export interface Props extends Themeable { row: LogRowModel; showDuplicates: boolean; getRows: () => LogRowModel[]; className?: string; onMouseEnter?: () => void; onMouseLeave?: () => void; onClickFilterLabel?: (key: string, value: string) => void; onClickFilterOutLabel?: (key: string, value: string) => void; getFieldLinks?: (field: Field, rowIndex: number) => Array<LinkModel<Field>>; }
91jme/grafana
packages/grafana-ui/src/components/Logs/LogDetails.tsx
TypeScript
TypeAliasDeclaration
type FieldDef = { key: string; value: string; links?: string[]; fieldIndex?: number; };
91jme/grafana
packages/grafana-ui/src/components/Logs/LogDetails.tsx
TypeScript
MethodDeclaration
render() { const { row, theme, onClickFilterOutLabel, onClickFilterLabel, getRows, showDuplicates, className, onMouseEnter, onMouseLeave, } = this.props; const style = getLogRowStyles(theme, row.logLevel); const styles = getStyles(theme); const labels = row.labels ? row.labels : {}; const labelsAvailable = Object.keys(labels).length > 0; const fields = this.getAllFields(row); const parsedFieldsAvailable = fields && fields.length > 0; return ( <tr className={cx(className, styles.logDetailsDefaultCursor)} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} > {showDuplicates && <td />} <td className={cx(style.logsRowLevel, styles.logsRowLevelDetails)} /> <td colSpan={4}> <div className={style.logDetailsContainer}> <table className={style.logDetailsTable}> <tbody> {labelsAvailable && ( <tr> <td colSpan={5} className={style.logDetailsHeading} aria-label="Log Labels"> Log Labels: </td> </tr> )}
91jme/grafana
packages/grafana-ui/src/components/Logs/LogDetails.tsx
TypeScript
MethodDeclaration
cx(className, styles
91jme/grafana
packages/grafana-ui/src/components/Logs/LogDetails.tsx
TypeScript
MethodDeclaration
cx(style
91jme/grafana
packages/grafana-ui/src/components/Logs/LogDetails.tsx
TypeScript
ArrowFunction
(s: string) => { const { lexer } = parser const variables = [] lexer.setInput(s) let token do { token = lexer.lex() if (token === parser.symbols_.ID) { variables.push(lexer.yytext) } } while (token !== false && token !== lexer.EOF) return variables.filter(v => v !== 'math_e') }
consbio/seedsource-ui
src/parser/index.ts
TypeScript
ArrowFunction
v => v !== 'math_e'
consbio/seedsource-ui
src/parser/index.ts
TypeScript
ArrowFunction
(expr: string, context: any = {}) => { parser.yy.context = { ...context, math_e: Math.E, } console.log('...') console.log('parser.yy.context', parser.yy.context) console.log('???') console.log('parser.parse(expr)', parser.parse(expr)) console.log('after parse') return parser.parse(expr) }
consbio/seedsource-ui
src/parser/index.ts
TypeScript
ArrowFunction
(style: string) => { result[style] = StyleRules.getLegendForStyle(style, this.nodeRules[style], itemsData); }
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript
ArrowFunction
(style: string) => { result[style] = StyleRules.getLegendForStyle(style, this.edgeRules[style], itemsData); }
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript
ArrowFunction
(d) => { return styleRule.canApplyTo(d); }
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript
ArrowFunction
(k, i) => { if (i > 0) { template += ' and '; } template += `${k} ${value[k]}`; }
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript
ArrowFunction
(data) => { const propValue = Tools.getIn(data, styleRule.style.color.input); if (Array.isArray(propValue)) { propValue.forEach((value) => { const label = styleRule.style.color.input.includes('properties') ? `${StyleRules.getTypeLabel(styleRule.itemType)}.${propertyKey} = ${value}` : `${StyleRules.getTypeLabel(value)}`; const color = ItemAttributes.autoColor(value, styleRule.style.color.ignoreCase); StyleRules.updateLegend(currentLegend, {label: label, value: color}); }); } else { const label = styleRule.style.color.input.includes('properties') ? `${StyleRules.getTypeLabel(styleRule.itemType)}.${propertyKey} = ${propValue}` : `${StyleRules.getTypeLabel(propValue)}`; const value = ItemAttributes.autoColor(propValue, styleRule.style.color.ignoreCase); StyleRules.updateLegend(currentLegend, {label: label, value: value}); } }
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript
ArrowFunction
(value) => { const label = styleRule.style.color.input.includes('properties') ? `${StyleRules.getTypeLabel(styleRule.itemType)}.${propertyKey} = ${value}` : `${StyleRules.getTypeLabel(value)}`; const color = ItemAttributes.autoColor(value, styleRule.style.color.ignoreCase); StyleRules.updateLegend(currentLegend, {label: label, value: color}); }
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript
ArrowFunction
(r) => r.label
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript
ArrowFunction
(style: IStyleRule<INodeStyle | IEdgeStyle>) => { switch (styleType) { case StyleType.COLOR: return style.style.color !== undefined; case StyleType.ICON: return 'icon' in style.style && style.style.icon !== undefined; case StyleType.IMAGE: return 'image' in style.style && style.style.image !== undefined; case StyleType.SHAPE: return style.style.shape !== undefined; case StyleType.SIZE: return 'size' in style.style && style.style.size !== undefined; case StyleType.WIDTH: return 'width' in style.style && style.style.width !== undefined; } }
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript
ArrowFunction
(style: IStyleRule<INodeStyle | IEdgeStyle>) => StyleRules.getRule(style, styleType)
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript
ArrowFunction
(s) => s.index
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript
ArrowFunction
(style) => { if (seenIndex.includes(style.index)) { style.index = maxIndex; maxIndex++; } else { seenIndex.push(style.index); } return style; }
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript
InterfaceDeclaration
export interface Legend { [key: string]: Array<{label: string; value: string | IStyleIcon | IStyleImage | number}>; }
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript
EnumDeclaration
export enum StyleType { COLOR = 'color', ICON = 'icon', SIZE = 'size', IMAGE = 'image', SHAPE = 'shape', WIDTH = 'width' }
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript
MethodDeclaration
/** * Generate a legend with an array of style rules and existing items in visualization */ public generateLegend(itemsData: Array<LkNodeData | LkEdgeData>): Legend { const result: Legend = {}; if (itemsData.length === 0) { return result; } if ('categories' in itemsData[0]) { Object.keys(this.nodeRules).forEach((style: string) => { result[style] = StyleRules.getLegendForStyle(style, this.nodeRules[style], itemsData); }); } else { Object.keys(this.edgeRules).forEach((style: string) => { result[style] = StyleRules.getLegendForStyle(style, this.edgeRules[style], itemsData); }); } return result; }
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript
MethodDeclaration
/** * Return the legend for a specific style type (color, icon, image...) */ public static getLegendForStyle( styleType: string, styles: Array<StyleRule>, itemsData: Array<LkNodeData | LkEdgeData> ): Array<{label: string; value: string | number | IStyleIcon | IStyleImage}> { const result: Array<{label: string; value: string | number | IStyleIcon | IStyleImage}> = []; const data = itemsData.filter((i) => i); for (let i = 0; i < styles.length; i++) { const styleRule = new StyleRule(styles[i]); const ruleExistsInViz = data.some((d) => { return styleRule.canApplyTo(d); }); if (ruleExistsInViz) { if (styleType === StyleType.COLOR && typeof styleRule.style.color === 'object') { StyleRules.addLegendAutoColors(data, styleRule, result); } else if (styleType === StyleType.ICON && 'image' in styleRule.style) { // style is a custom icon const label = Tools.isDefined(styleRule.input) ? `${StyleRules.getTypeLabel(styleRule.itemType)}.${ styleRule.input[1] } ${StyleRules.sanitizeValue(styleRule.type, styleRule.value)}` : `${StyleRules.getTypeLabel(styleRule.itemType)}`; const value = styleRule.style.image; StyleRules.updateLegend(result, {label: label, value: value}); } else { const label = Tools.isDefined(styleRule.input) ? `${StyleRules.getTypeLabel(styleRule.itemType)}.${ styleRule.input[1] } ${StyleRules.sanitizeValue(styleRule.type, styleRule.value)}` : `${StyleRules.getTypeLabel(styleRule.itemType)}`; const value = styleRule.style[styleType]; StyleRules.updateLegend(result, {label: label, value: value}); } } } return result; }
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript
MethodDeclaration
/** * Sanitize value for legend */ public static sanitizeValue(styleType: SelectorType, value: any): string { switch (styleType) { case SelectorType.NO_VALUE: return 'is undefined'; case SelectorType.NAN: return 'is not an number'; case SelectorType.RANGE: let template = ''; Object.keys(value).forEach((k, i) => { if (i > 0) { template += ' and '; } template += `${k} ${value[k]}`; }); return template; } return typeof value === 'object' ? `= ${JSON.stringify(value)}` : `= ${value}`; }
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript
MethodDeclaration
/** * Add items in legend for automatic coloring */ public static addLegendAutoColors( itemsData: Array<LkNodeData | LkEdgeData>, styleRule: StyleRule, currentLegend: Array<{label: string; value: string | number | IStyleIcon | IStyleImage}> ): void { const propertyKey: string = styleRule.style.color.input[1]; itemsData.forEach((data) => { const propValue = Tools.getIn(data, styleRule.style.color.input); if (Array.isArray(propValue)) { propValue.forEach((value) => { const label = styleRule.style.color.input.includes('properties') ? `${StyleRules.getTypeLabel(styleRule.itemType)}.${propertyKey} = ${value}` : `${StyleRules.getTypeLabel(value)}`; const color = ItemAttributes.autoColor(value, styleRule.style.color.ignoreCase); StyleRules.updateLegend(currentLegend, {label: label, value: color}); }); } else { const label = styleRule.style.color.input.includes('properties') ? `${StyleRules.getTypeLabel(styleRule.itemType)}.${propertyKey} = ${propValue}` : `${StyleRules.getTypeLabel(propValue)}`; const value = ItemAttributes.autoColor(propValue, styleRule.style.color.ignoreCase); StyleRules.updateLegend(currentLegend, {label: label, value: value}); } }); }
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript
MethodDeclaration
/** * Return the label of item type for a legend item */ public static getTypeLabel(type: string | undefined | null): string { return type === undefined ? 'All' : type === null ? 'Others' : type; }
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript
MethodDeclaration
/** * Check if a legend item already exists and overwrite it / push it */ public static updateLegend( legend: Array<{label: string; value: string | number | IStyleIcon | IStyleImage}>, {label, value}: {[key: string]: string} ): void { const indexOfLegendItem = legend.map((r) => r.label).indexOf(label); if (indexOfLegendItem < 0) { legend.push({label: label, value: value}); } else { legend[indexOfLegendItem] = {label: label, value: value}; } }
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript
MethodDeclaration
/** * return an array of StyleRule, containing only the desired style */ public static getBy( styleType: StyleType, rules: Array<IStyleRule<INodeStyle | IEdgeStyle>> ): Array<StyleRule> { return rules .filter((style: IStyleRule<INodeStyle | IEdgeStyle>) => { switch (styleType) { case StyleType.COLOR: return style.style.color !== undefined; case StyleType.ICON: return 'icon' in style.style && style.style.icon !== undefined; case StyleType.IMAGE: return 'image' in style.style && style.style.image !== undefined; case StyleType.SHAPE: return style.style.shape !== undefined; case StyleType.SIZE: return 'size' in style.style && style.style.size !== undefined; case StyleType.WIDTH: return 'width' in style.style && style.style.width !== undefined; } }) .map((style: IStyleRule<INodeStyle | IEdgeStyle>) => StyleRules.getRule(style, styleType)); }
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript