type
stringclasses
7 values
content
stringlengths
4
9.55k
repo
stringlengths
7
96
path
stringlengths
4
178
language
stringclasses
1 value
ArrowFunction
() => { const files = { app: { 'spec.ts': ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'my-component', template: \`<div class="foo" style="width:100px" [attr.class]="'round'" [attr.style]="'height:100px'"></div>\` }) export class MyComponent {} @NgModule({declarations: [MyComponent]}) export class MyModule {} ` } }; const template = ` const _c0 = ["foo",${InitialStylingFlags.VALUES_MODE},"foo",true]; const _c1 = ["width",${InitialStylingFlags.VALUES_MODE},"width","100px"]; … MyComponent.ngComponentDef = $r3$.ɵdefineComponent({ type: MyComponent, selectors:[["my-component"]], factory:function MyComponent_Factory(){ return new MyComponent(); }, features: [$r3$.ɵPublicFeature], template: function MyComponent_Template(rf, $ctx$) { if (rf & 1) { $r3$.ɵE(0, "div"); $r3$.ɵs(_c0, _c1); $r3$.ɵe(); } if (rf & 2) { $r3$.ɵa(0, "class", $r3$.ɵb("round")); $r3$.ɵa(0, "style", $r3$.ɵb("height:100px"), $r3$.ɵzs); } } }); `; const result = compile(files, angularFiles); expectEmit(result.source, template, 'Incorrect template'); }
DaveCheez/angular
packages/compiler-cli/test/compliance/r3_view_compiler_styling_spec.ts
TypeScript
ClassDeclaration
// #endregion @NgModule({ imports: [ CommonModule, FormsModule, RouterModule, ReactiveFormsModule, AlainThemeModule.forChild(), DelonACLModule, DelonFormModule, ...SHARED_DELON_MODULES, ...SHARED_ZORRO_MODULES, // third libs ...THIRDMODULES ], declarations: [ // your components ...COMPONENTS, ...DIRECTIVES ], exports: [ CommonModule, FormsModule, ReactiveFormsModule, RouterModule, AlainThemeModule, DelonACLModule, DelonFormModule, ...SHARED_DELON_MODULES, ...SHARED_ZORRO_MODULES, // third libs ...THIRDMODULES, // your components ...COMPONENTS, ...DIRECTIVES ] }) export class SharedModule {}
1312671314/ngTem
src/app/common/shared/shared.module.ts
TypeScript
ArrowFunction
(subscription) => subscription.remove()
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
ArrowFunction
(state) => { // Update UI state (toggle switch, changePace button) this.addEvent('State', new Date(), state); this.zone.run(() => { this.isMoving = state.isMoving; this.enabled = state.enabled; }); }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
ArrowFunction
() => { this.isMoving = state.isMoving; this.enabled = state.enabled; }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
ArrowFunction
(location) => { console.log('- getCurrentPosition: ', location); }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
ArrowFunction
(error) => { console.warn('- Location error: ', error); }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
ArrowFunction
() => { this.events.push({ name: name, timestamp: timestamp, object: event, content: JSON.stringify(event, null, 2) }); }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
ClassDeclaration
@Component({ selector: 'app-hello-world', templateUrl: './hello-world.page.html', styleUrls: ['./hello-world.page.scss'], }) export class HelloWorldPage implements OnInit, OnDestroy { // UI State enabled: boolean; isMoving: boolean; // ion-list datasource events: any; subscriptions: any; constructor(public navCtrl:NavController, public router:Router, private zone:NgZone) { this.events = []; this.subscriptions = []; } subscribe(subscription:Subscription) { this.subscriptions.push(subscription); } unsubscribe() { this.subscriptions.forEach((subscription) => subscription.remove() ); this.subscriptions = []; } ngAfterContentInit() { console.log('⚙️ ngAfterContentInit'); this.configureBackgroundGeolocation(); } ionViewWillEnter() { console.log('⚙️ ionViewWillEnter'); } ngOnInit() { } ngOnDestroy() { this.unsubscribe(); } async configureBackgroundGeolocation() { // Step 1: Listen to BackgroundGeolocation events. this.subscribe(BackgroundGeolocation.onEnabledChange(this.onEnabledChange.bind(this))); this.subscribe(BackgroundGeolocation.onLocation(this.onLocation.bind(this))); this.subscribe(BackgroundGeolocation.onMotionChange(this.onMotionChange.bind(this))); this.subscribe(BackgroundGeolocation.onGeofence(this.onGeofence.bind(this))); this.subscribe(BackgroundGeolocation.onActivityChange(this.onActivityChange.bind(this))); this.subscribe(BackgroundGeolocation.onHttp(this.onHttp.bind(this))); this.subscribe(BackgroundGeolocation.onProviderChange(this.onProviderChange.bind(this))); this.subscribe(BackgroundGeolocation.onPowerSaveChange(this.onPowerSaveChange.bind(this))); this.subscribe(BackgroundGeolocation.onConnectivityChange(this.onConnectivityChange.bind(this))); this.subscribe(BackgroundGeolocation.onAuthorization(this.onAuthorization.bind(this))); // Compose #url: tracker.transistorsoft.com/locations/{username} const orgname = (await Storage.get({key: 'orgname'})).value; const username = (await Storage.get({key: 'username'})).value; const token:TransistorAuthorizationToken = await BackgroundGeolocation.findOrCreateTransistorAuthorizationToken( orgname, username, environment.TRACKER_HOST ); // Step 2: Configure the plugin BackgroundGeolocation.ready({ reset: true, debug: true, logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE, distanceFilter: 10, stopTimeout: 1, stopOnTerminate: false, startOnBoot: true, url: environment.TRACKER_HOST + '/api/locations', // [Android] backgroundPermissionRationale for Always permission. backgroundPermissionRationale: { title: "Allow {applicationName} to access this device's location even when closed or not in use.", message: "This app collects location data to enable recording your trips to work and calculate distance-travelled.", positiveAction: 'Change to "{backgroundPermissionOptionLabel}"', negativeAction: 'Cancel' }, authorization: { // <-- JWT authorization for tracker.transistorsoft.com strategy: 'jwt', accessToken: token.accessToken, refreshToken: token.refreshToken, refreshUrl: environment.TRACKER_HOST + '/api/refresh_token', refreshPayload: { refresh_token: '{refreshToken}' }, expires: token.expires }, autoSync: true }).then((state) => { // Update UI state (toggle switch, changePace button) this.addEvent('State', new Date(), state); this.zone.run(() => { this.isMoving = state.isMoving; this.enabled = state.enabled; }); }); } // Return to Home screen (app switcher) onClickHome() { this.navCtrl.navigateBack('/home'); } // #start / #stop tracking onToggleEnabled() { if (this.enabled) { BackgroundGeolocation.start(); } else { BackgroundGeolocation.stop(); } } // Fetch the current position onClickGetCurrentPosition() { BackgroundGeolocation.getCurrentPosition({persist: true}, (location) => { console.log('- getCurrentPosition: ', location); }, (error) => { console.warn('- Location error: ', error); }); } // Change plugin state between stationary / tracking onClickChangePace() { this.isMoving = !this.isMoving; BackgroundGeolocation.changePace(this.isMoving); } // Clear the list of events from ion-list onClickClear() { this.events = []; } /// @event enabledchange onEnabledChange(enabled:boolean) { this.isMoving = false; this.addEvent('onEnabledChange', new Date(), {enabled: enabled}); } /// @event location onLocation(location:Location) { console.log('[event] location: ', location); this.addEvent('onLocation', new Date(location.timestamp), location); } /// @event motionchange onMotionChange(event:MotionChangeEvent) { console.log('[event] motionchange, isMoving: ', event.isMoving, ', location: ', event.location); this.addEvent('onMotionChange', new Date(event.location.timestamp), event); this.isMoving = event.isMoving; } /// @event activitychange onActivityChange(event:MotionActivityEvent) { console.log('[event] activitychange: ', event); this.addEvent('onActivityChange', new Date(), event); } /// @event geofence onGeofence(event:GeofenceEvent) { console.log('[event] geofence: ', event); this.addEvent('onGeofence', new Date(event.location.timestamp), event); } /// @event http onHttp(response:HttpEvent) { console.log('[event] http: ', response); this.addEvent('onHttp', new Date(), response); } /// @event providerchange onProviderChange(provider:ProviderChangeEvent) { console.log('[event] providerchange', provider); this.addEvent('onProviderChange', new Date(), provider); } /// @event powersavechange onPowerSaveChange(isPowerSaveEnabled:boolean) { console.log('[event] powersavechange', isPowerSaveEnabled); this.addEvent('onPowerSaveChange', new Date(), {isPowerSaveEnabled: isPowerSaveEnabled}); } /// @event connectivitychange onConnectivityChange(event:ConnectivityChangeEvent) { console.log('[event] connectivitychange connected? ', event.connected); this.addEvent('onConnectivityChange', new Date(), event); } /// @event authorization onAuthorization(event:AuthorizationEvent) { console.log('[event] authorization: ', event); } /// Add a record to ion-list private addEvent(name, date, event) { const timestamp = date.toLocaleDateString() + ' ' + date.toLocaleTimeString(); this.zone.run(() => { this.events.push({ name: name, timestamp: timestamp, object: event, content: JSON.stringify(event, null, 2) }); }) } }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
subscribe(subscription:Subscription) { this.subscriptions.push(subscription); }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
unsubscribe() { this.subscriptions.forEach((subscription) => subscription.remove() ); this.subscriptions = []; }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
ngAfterContentInit() { console.log('⚙️ ngAfterContentInit'); this.configureBackgroundGeolocation(); }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
ionViewWillEnter() { console.log('⚙️ ionViewWillEnter'); }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
ngOnDestroy() { this.unsubscribe(); }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
async configureBackgroundGeolocation() { // Step 1: Listen to BackgroundGeolocation events. this.subscribe(BackgroundGeolocation.onEnabledChange(this.onEnabledChange.bind(this))); this.subscribe(BackgroundGeolocation.onLocation(this.onLocation.bind(this))); this.subscribe(BackgroundGeolocation.onMotionChange(this.onMotionChange.bind(this))); this.subscribe(BackgroundGeolocation.onGeofence(this.onGeofence.bind(this))); this.subscribe(BackgroundGeolocation.onActivityChange(this.onActivityChange.bind(this))); this.subscribe(BackgroundGeolocation.onHttp(this.onHttp.bind(this))); this.subscribe(BackgroundGeolocation.onProviderChange(this.onProviderChange.bind(this))); this.subscribe(BackgroundGeolocation.onPowerSaveChange(this.onPowerSaveChange.bind(this))); this.subscribe(BackgroundGeolocation.onConnectivityChange(this.onConnectivityChange.bind(this))); this.subscribe(BackgroundGeolocation.onAuthorization(this.onAuthorization.bind(this))); // Compose #url: tracker.transistorsoft.com/locations/{username} const orgname = (await Storage.get({key: 'orgname'})).value; const username = (await Storage.get({key: 'username'})).value; const token:TransistorAuthorizationToken = await BackgroundGeolocation.findOrCreateTransistorAuthorizationToken( orgname, username, environment.TRACKER_HOST ); // Step 2: Configure the plugin BackgroundGeolocation.ready({ reset: true, debug: true, logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE, distanceFilter: 10, stopTimeout: 1, stopOnTerminate: false, startOnBoot: true, url: environment.TRACKER_HOST + '/api/locations', // [Android] backgroundPermissionRationale for Always permission. backgroundPermissionRationale: { title: "Allow {applicationName} to access this device's location even when closed or not in use.", message: "This app collects location data to enable recording your trips to work and calculate distance-travelled.", positiveAction: 'Change to "{backgroundPermissionOptionLabel}"', negativeAction: 'Cancel' }, authorization: { // <-- JWT authorization for tracker.transistorsoft.com strategy: 'jwt', accessToken: token.accessToken, refreshToken: token.refreshToken, refreshUrl: environment.TRACKER_HOST + '/api/refresh_token', refreshPayload: { refresh_token: '{refreshToken}' }, expires: token.expires }, autoSync: true }).then((state) => { // Update UI state (toggle switch, changePace button) this.addEvent('State', new Date(), state); this.zone.run(() => { this.isMoving = state.isMoving; this.enabled = state.enabled; }); }); }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
// Return to Home screen (app switcher) onClickHome() { this.navCtrl.navigateBack('/home'); }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
// #start / #stop tracking onToggleEnabled() { if (this.enabled) { BackgroundGeolocation.start(); } else { BackgroundGeolocation.stop(); } }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
// Fetch the current position onClickGetCurrentPosition() { BackgroundGeolocation.getCurrentPosition({persist: true}, (location) => { console.log('- getCurrentPosition: ', location); }, (error) => { console.warn('- Location error: ', error); }); }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
// Change plugin state between stationary / tracking onClickChangePace() { this.isMoving = !this.isMoving; BackgroundGeolocation.changePace(this.isMoving); }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
// Clear the list of events from ion-list onClickClear() { this.events = []; }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
/// @event enabledchange onEnabledChange(enabled:boolean) { this.isMoving = false; this.addEvent('onEnabledChange', new Date(), {enabled: enabled}); }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
/// @event location onLocation(location:Location) { console.log('[event] location: ', location); this.addEvent('onLocation', new Date(location.timestamp), location); }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
/// @event motionchange onMotionChange(event:MotionChangeEvent) { console.log('[event] motionchange, isMoving: ', event.isMoving, ', location: ', event.location); this.addEvent('onMotionChange', new Date(event.location.timestamp), event); this.isMoving = event.isMoving; }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
/// @event activitychange onActivityChange(event:MotionActivityEvent) { console.log('[event] activitychange: ', event); this.addEvent('onActivityChange', new Date(), event); }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
/// @event geofence onGeofence(event:GeofenceEvent) { console.log('[event] geofence: ', event); this.addEvent('onGeofence', new Date(event.location.timestamp), event); }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
/// @event http onHttp(response:HttpEvent) { console.log('[event] http: ', response); this.addEvent('onHttp', new Date(), response); }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
/// @event providerchange onProviderChange(provider:ProviderChangeEvent) { console.log('[event] providerchange', provider); this.addEvent('onProviderChange', new Date(), provider); }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
/// @event powersavechange onPowerSaveChange(isPowerSaveEnabled:boolean) { console.log('[event] powersavechange', isPowerSaveEnabled); this.addEvent('onPowerSaveChange', new Date(), {isPowerSaveEnabled: isPowerSaveEnabled}); }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
/// @event connectivitychange onConnectivityChange(event:ConnectivityChangeEvent) { console.log('[event] connectivitychange connected? ', event.connected); this.addEvent('onConnectivityChange', new Date(), event); }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
/// @event authorization onAuthorization(event:AuthorizationEvent) { console.log('[event] authorization: ', event); }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
MethodDeclaration
/// Add a record to ion-list private addEvent(name, date, event) { const timestamp = date.toLocaleDateString() + ' ' + date.toLocaleTimeString(); this.zone.run(() => { this.events.push({ name: name, timestamp: timestamp, object: event, content: JSON.stringify(event, null, 2) }); }) }
transistorsoft/capacitor-background-geolocation
example/angular/src/app/hello-world/hello-world.page.ts
TypeScript
FunctionDeclaration
export default function Home(partner: any) { const router = useRouter(); const { locale, defaultLocale } = router; const homeData: any = home; const benefitsData: any = benefits; const partnersData: any = partners; const stepsData: any = steps; const faqData: any = faq; return ( <MainLayout> <Head> <title>{homeData[locale!].pageTitle}</title> <meta name="description" content={homeData[locale!].pageMeta}></meta> </Head> <Script src="https://cadirect-widget.netlify.app/cadwidget-v1.0.js" /> <Hero title={homeData[locale!].title} subtitle={homeData[locale!].subtitle} img={homeData[locale!].bannerImg} partner={partner.partner} /> <Icons data={benefitsData[locale!].benefits} /> <Steps title={stepsData[locale!].title} data={stepsData[locale!].steps} /> <Faq title={faqData[locale!].title} data={faqData[locale!].accordions} /> <Partners data={partnersData[defaultLocale!]} title={partnersData[locale!].title} /> </MainLayout> ); }
oleh-domshynskyi/sellcar.online
src/pages/index.tsx
TypeScript
ClassDeclaration
export class AddonEnabledRepositoryImpl implements AddonEnabledRepository { set(on: boolean): void { enabled = on; } get(): boolean { return enabled; } }
aminroosta/vim-vixen
src/content/repositories/AddonEnabledRepository.ts
TypeScript
InterfaceDeclaration
export default interface AddonEnabledRepository { set(on: boolean): void; get(): boolean; }
aminroosta/vim-vixen
src/content/repositories/AddonEnabledRepository.ts
TypeScript
MethodDeclaration
set(on: boolean): void { enabled = on; }
aminroosta/vim-vixen
src/content/repositories/AddonEnabledRepository.ts
TypeScript
MethodDeclaration
get(): boolean { return enabled; }
aminroosta/vim-vixen
src/content/repositories/AddonEnabledRepository.ts
TypeScript
FunctionDeclaration
function initLinkSrv() { const _dashboard: any = { time: { from: 'now-6h', to: 'now' }, getTimezone: jest.fn(() => 'browser'), timeRangeUpdated: () => {}, }; const timeSrv = new TimeSrv({} as any); timeSrv.init(_dashboard); timeSrv.setTime({ from: 'now-1h', to: 'now' }); _dashboard.refresh = false; setTimeSrv(timeSrv); templateSrv = initTemplateSrv('key', [ { type: 'query', name: 'home', current: { value: '127.0.0.1' } }, { type: 'query', name: 'server1', current: { value: '192.168.0.100' } }, ]); setTemplateSrv(templateSrv); linkSrv = new LinkSrv(); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => ({ appEvents: { subscribe: () => {}, }, })
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { let linkSrv: LinkSrv; let templateSrv: TemplateSrv; let originalTimeService: TimeSrv; function initLinkSrv() { const _dashboard: any = { time: { from: 'now-6h', to: 'now' }, getTimezone: jest.fn(() => 'browser'), timeRangeUpdated: () => {}, }; const timeSrv = new TimeSrv({} as any); timeSrv.init(_dashboard); timeSrv.setTime({ from: 'now-1h', to: 'now' }); _dashboard.refresh = false; setTimeSrv(timeSrv); templateSrv = initTemplateSrv('key', [ { type: 'query', name: 'home', current: { value: '127.0.0.1' } }, { type: 'query', name: 'server1', current: { value: '192.168.0.100' } }, ]); setTemplateSrv(templateSrv); linkSrv = new LinkSrv(); } beforeAll(() => { originalTimeService = getTimeSrv(); variableAdapters.register(createQueryVariableAdapter()); }); beforeEach(() => { initLinkSrv(); jest.resetAllMocks(); }); afterAll(() => { setTimeSrv(originalTimeService); }); describe('getDataLinkUIModel', () => { describe('built in variables', () => { it('should not trim white space from data links', () => { expect( linkSrv.getDataLinkUIModel( { title: 'White space', url: 'www.google.com?query=some query', }, (v) => v, {} ).href ).toEqual('www.google.com?query=some query'); }); it('should remove new lines from data link', () => { expect( linkSrv.getDataLinkUIModel( { title: 'New line', url: 'www.google.com?query=some\nquery', }, (v) => v, {} ).href ).toEqual('www.google.com?query=somequery'); }); }); describe('sanitization', () => { const url = "javascript:alert('broken!);"; it.each` disableSanitizeHtml | expected ${true} | ${url} ${false} | ${'about:blank'} `( "when disable disableSanitizeHtml set to '$disableSanitizeHtml' then result should be '$expected'", ({ disableSanitizeHtml, expected }) => { updateConfig({ disableSanitizeHtml, }); const link = linkSrv.getDataLinkUIModel( { title: 'Any title', url, }, (v) => v, {} ).href; expect(link).toBe(expected); } ); }); describe('Building links with root_url set', () => { it.each` url | appSubUrl | expected ${'/d/XXX'} | ${'/grafana'} | ${'/grafana/d/XXX'} ${'/grafana/d/XXX'} | ${'/grafana'} | ${'/grafana/d/XXX'} ${'d/whatever'} | ${'/grafana'} | ${'d/whatever'} ${'/d/XXX'} | ${''} | ${'/d/XXX'} ${'/grafana/d/XXX'} | ${''} | ${'/grafana/d/XXX'} ${'d/whatever'} | ${''} | ${'d/whatever'} `( "when link '$url' and config.appSubUrl set to '$appSubUrl' then result should be '$expected'", ({ url, appSubUrl, expected }) => { locationUtil.initialize({ config: { appSubUrl } as any, getVariablesUrlParams: (() => {}) as any, getTimeRangeForUrl: (() => {}) as any, }); const link = linkSrv.getDataLinkUIModel( { title: 'Any title', url, }, (v) => v, {} ).href; expect(link).toBe(expected); } ); }); }); describe('getAnchorInfo', () => { it('returns variable values for variable names in link.href and link.tooltip', () => { jest.spyOn(linkSrv, 'getLinkUrl'); jest.spyOn(templateSrv, 'replace'); expect(linkSrv.getLinkUrl).toBeCalledTimes(0); expect(templateSrv.replace).toBeCalledTimes(0); const link = linkSrv.getAnchorInfo({ type: 'link', icon: 'dashboard', tags: [], url: '/graph?home=$home', title: 'Visit home', tooltip: 'Visit ${home:raw}', }); expect(linkSrv.getLinkUrl).toBeCalledTimes(1); expect(templateSrv.replace).toBeCalledTimes(3); expect(link).toStrictEqual({ href: '/graph?home=127.0.0.1', title: 'Visit home', tooltip: 'Visit 127.0.0.1' }); }); }); describe('getLinkUrl', () => { it('converts link urls', () => { const linkUrl = linkSrv.getLinkUrl({ url: '/graph', }); const linkUrlWithVar = linkSrv.getLinkUrl({ url: '/graph?home=$home', }); expect(linkUrl).toBe('/graph'); expect(linkUrlWithVar).toBe('/graph?home=127.0.0.1'); }); it('appends current dashboard time range if keepTime is true', () => { const anchorInfoKeepTime = linkSrv.getLinkUrl({ keepTime: true, url: '/graph', }); expect(anchorInfoKeepTime).toBe('/graph?from=now-1h&to=now'); }); it('adds all variables to the url if includeVars is true', () => { const anchorInfoIncludeVars = linkSrv.getLinkUrl({ includeVars: true, url: '/graph', }); expect(anchorInfoIncludeVars).toBe('/graph?var-home=127.0.0.1&var-server1=192.168.0.100'); }); it('respects config disableSanitizeHtml', () => { const anchorInfo = { url: 'javascript:alert(document.domain)', }; expect(linkSrv.getLinkUrl(anchorInfo)).toBe('about:blank'); updateConfig({ disableSanitizeHtml: true, }); expect(linkSrv.getLinkUrl(anchorInfo)).toBe(anchorInfo.url); }); }); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => 'browser'
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { originalTimeService = getTimeSrv(); variableAdapters.register(createQueryVariableAdapter()); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { initLinkSrv(); jest.resetAllMocks(); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { setTimeSrv(originalTimeService); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { describe('built in variables', () => { it('should not trim white space from data links', () => { expect( linkSrv.getDataLinkUIModel( { title: 'White space', url: 'www.google.com?query=some query', }, (v) => v, {} ).href ).toEqual('www.google.com?query=some query'); }); it('should remove new lines from data link', () => { expect( linkSrv.getDataLinkUIModel( { title: 'New line', url: 'www.google.com?query=some\nquery', }, (v) => v, {} ).href ).toEqual('www.google.com?query=somequery'); }); }); describe('sanitization', () => { const url = "javascript:alert('broken!);"; it.each` disableSanitizeHtml | expected ${true} | ${url} ${false} | ${'about:blank'} `( "when disable disableSanitizeHtml set to '$disableSanitizeHtml' then result should be '$expected'", ({ disableSanitizeHtml, expected }) => { updateConfig({ disableSanitizeHtml, }); const link = linkSrv.getDataLinkUIModel( { title: 'Any title', url, }, (v) => v, {} ).href; expect(link).toBe(expected); } ); }); describe('Building links with root_url set', () => { it.each` url | appSubUrl | expected ${'/d/XXX'} | ${'/grafana'} | ${'/grafana/d/XXX'} ${'/grafana/d/XXX'} | ${'/grafana'} | ${'/grafana/d/XXX'} ${'d/whatever'} | ${'/grafana'} | ${'d/whatever'} ${'/d/XXX'} | ${''} | ${'/d/XXX'} ${'/grafana/d/XXX'} | ${''} | ${'/grafana/d/XXX'} ${'d/whatever'} | ${''} | ${'d/whatever'} `( "when link '$url' and config.appSubUrl set to '$appSubUrl' then result should be '$expected'", ({ url, appSubUrl, expected }) => { locationUtil.initialize({ config: { appSubUrl } as any, getVariablesUrlParams: (() => {}) as any, getTimeRangeForUrl: (() => {}) as any, }); const link = linkSrv.getDataLinkUIModel( { title: 'Any title', url, }, (v) => v, {} ).href; expect(link).toBe(expected); } ); }); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { it('should not trim white space from data links', () => { expect( linkSrv.getDataLinkUIModel( { title: 'White space', url: 'www.google.com?query=some query', }, (v) => v, {} ).href ).toEqual('www.google.com?query=some query'); }); it('should remove new lines from data link', () => { expect( linkSrv.getDataLinkUIModel( { title: 'New line', url: 'www.google.com?query=some\nquery', }, (v) => v, {} ).href ).toEqual('www.google.com?query=somequery'); }); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { expect( linkSrv.getDataLinkUIModel( { title: 'White space', url: 'www.google.com?query=some query', }, (v) => v, {} ).href ).toEqual('www.google.com?query=some query'); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { expect( linkSrv.getDataLinkUIModel( { title: 'New line', url: 'www.google.com?query=some\nquery', }, (v) => v, {} ).href ).toEqual('www.google.com?query=somequery'); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { const url = "javascript:alert('broken!);"; it.each` disableSanitizeHtml | expected ${true} | ${url} ${false} | ${'about:blank'} `( "when disable disableSanitizeHtml set to '$disableSanitizeHtml' then result should be '$expected'", ({ disableSanitizeHtml, expected }) => { updateConfig({ disableSanitizeHtml, }); const link = linkSrv.getDataLinkUIModel( { title: 'Any title', url, }, (v) => v, {} ).href; expect(link).toBe(expected); } ); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
({ disableSanitizeHtml, expected }) => { updateConfig({ disableSanitizeHtml, }); const link = linkSrv.getDataLinkUIModel( { title: 'Any title', url, }, (v) => v, {} ).href; expect(link).toBe(expected); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { it.each` url | appSubUrl | expected ${'/d/XXX'} | ${'/grafana'} | ${'/grafana/d/XXX'} ${'/grafana/d/XXX'} | ${'/grafana'} | ${'/grafana/d/XXX'} ${'d/whatever'} | ${'/grafana'} | ${'d/whatever'} ${'/d/XXX'} | ${''} | ${'/d/XXX'} ${'/grafana/d/XXX'} | ${''} | ${'/grafana/d/XXX'} ${'d/whatever'} | ${''} | ${'d/whatever'} `( "when link '$url' and config.appSubUrl set to '$appSubUrl' then result should be '$expected'", ({ url, appSubUrl, expected }) => { locationUtil.initialize({ config: { appSubUrl } as any, getVariablesUrlParams: (() => {}) as any, getTimeRangeForUrl: (() => {}) as any, }); const link = linkSrv.getDataLinkUIModel( { title: 'Any title', url, }, (v) => v, {} ).href; expect(link).toBe(expected); } ); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
({ url, appSubUrl, expected }) => { locationUtil.initialize({ config: { appSubUrl } as any, getVariablesUrlParams: (() => {}) as any, getTimeRangeForUrl: (() => {}) as any, }); const link = linkSrv.getDataLinkUIModel( { title: 'Any title', url, }, (v) => v, {} ).href; expect(link).toBe(expected); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { it('returns variable values for variable names in link.href and link.tooltip', () => { jest.spyOn(linkSrv, 'getLinkUrl'); jest.spyOn(templateSrv, 'replace'); expect(linkSrv.getLinkUrl).toBeCalledTimes(0); expect(templateSrv.replace).toBeCalledTimes(0); const link = linkSrv.getAnchorInfo({ type: 'link', icon: 'dashboard', tags: [], url: '/graph?home=$home', title: 'Visit home', tooltip: 'Visit ${home:raw}', }); expect(linkSrv.getLinkUrl).toBeCalledTimes(1); expect(templateSrv.replace).toBeCalledTimes(3); expect(link).toStrictEqual({ href: '/graph?home=127.0.0.1', title: 'Visit home', tooltip: 'Visit 127.0.0.1' }); }); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { jest.spyOn(linkSrv, 'getLinkUrl'); jest.spyOn(templateSrv, 'replace'); expect(linkSrv.getLinkUrl).toBeCalledTimes(0); expect(templateSrv.replace).toBeCalledTimes(0); const link = linkSrv.getAnchorInfo({ type: 'link', icon: 'dashboard', tags: [], url: '/graph?home=$home', title: 'Visit home', tooltip: 'Visit ${home:raw}', }); expect(linkSrv.getLinkUrl).toBeCalledTimes(1); expect(templateSrv.replace).toBeCalledTimes(3); expect(link).toStrictEqual({ href: '/graph?home=127.0.0.1', title: 'Visit home', tooltip: 'Visit 127.0.0.1' }); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { it('converts link urls', () => { const linkUrl = linkSrv.getLinkUrl({ url: '/graph', }); const linkUrlWithVar = linkSrv.getLinkUrl({ url: '/graph?home=$home', }); expect(linkUrl).toBe('/graph'); expect(linkUrlWithVar).toBe('/graph?home=127.0.0.1'); }); it('appends current dashboard time range if keepTime is true', () => { const anchorInfoKeepTime = linkSrv.getLinkUrl({ keepTime: true, url: '/graph', }); expect(anchorInfoKeepTime).toBe('/graph?from=now-1h&to=now'); }); it('adds all variables to the url if includeVars is true', () => { const anchorInfoIncludeVars = linkSrv.getLinkUrl({ includeVars: true, url: '/graph', }); expect(anchorInfoIncludeVars).toBe('/graph?var-home=127.0.0.1&var-server1=192.168.0.100'); }); it('respects config disableSanitizeHtml', () => { const anchorInfo = { url: 'javascript:alert(document.domain)', }; expect(linkSrv.getLinkUrl(anchorInfo)).toBe('about:blank'); updateConfig({ disableSanitizeHtml: true, }); expect(linkSrv.getLinkUrl(anchorInfo)).toBe(anchorInfo.url); }); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { const linkUrl = linkSrv.getLinkUrl({ url: '/graph', }); const linkUrlWithVar = linkSrv.getLinkUrl({ url: '/graph?home=$home', }); expect(linkUrl).toBe('/graph'); expect(linkUrlWithVar).toBe('/graph?home=127.0.0.1'); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { const anchorInfoKeepTime = linkSrv.getLinkUrl({ keepTime: true, url: '/graph', }); expect(anchorInfoKeepTime).toBe('/graph?from=now-1h&to=now'); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { const anchorInfoIncludeVars = linkSrv.getLinkUrl({ includeVars: true, url: '/graph', }); expect(anchorInfoIncludeVars).toBe('/graph?var-home=127.0.0.1&var-server1=192.168.0.100'); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { const anchorInfo = { url: 'javascript:alert(document.domain)', }; expect(linkSrv.getLinkUrl(anchorInfo)).toBe('about:blank'); updateConfig({ disableSanitizeHtml: true, }); expect(linkSrv.getLinkUrl(anchorInfo)).toBe(anchorInfo.url); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { it('then it should return correct suggestions', () => { const frame = toDataFrame({ name: 'indoor', fields: [ { name: 'time', type: FieldType.time, values: [1, 2, 3] }, { name: 'temperature', type: FieldType.number, values: [10, 11, 12] }, ], }); const suggestions = getDataFrameVars([frame]); expect(suggestions).toEqual([ { value: '__data.fields.time', label: 'time', documentation: `Formatted value for time on the same row`, origin: VariableOrigin.Fields, }, { value: '__data.fields.temperature', label: 'temperature', documentation: `Formatted value for temperature on the same row`, origin: VariableOrigin.Fields, }, { value: `__data.fields[0]`, label: `Select by index`, documentation: `Enter the field order`, origin: VariableOrigin.Fields, }, { value: `__data.fields.temperature.numeric`, label: `Show numeric value`, documentation: `the numeric field value`, origin: VariableOrigin.Fields, }, { value: `__data.fields.temperature.text`, label: `Show text value`, documentation: `the text value`, origin: VariableOrigin.Fields, }, ]); }); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { const frame = toDataFrame({ name: 'indoor', fields: [ { name: 'time', type: FieldType.time, values: [1, 2, 3] }, { name: 'temperature', type: FieldType.number, values: [10, 11, 12] }, ], }); const suggestions = getDataFrameVars([frame]); expect(suggestions).toEqual([ { value: '__data.fields.time', label: 'time', documentation: `Formatted value for time on the same row`, origin: VariableOrigin.Fields, }, { value: '__data.fields.temperature', label: 'temperature', documentation: `Formatted value for temperature on the same row`, origin: VariableOrigin.Fields, }, { value: `__data.fields[0]`, label: `Select by index`, documentation: `Enter the field order`, origin: VariableOrigin.Fields, }, { value: `__data.fields.temperature.numeric`, label: `Show numeric value`, documentation: `the numeric field value`, origin: VariableOrigin.Fields, }, { value: `__data.fields.temperature.text`, label: `Show text value`, documentation: `the text value`, origin: VariableOrigin.Fields, }, ]); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { it('then it should return correct suggestions', () => { const frame = toDataFrame({ name: 'temperatures', fields: [ { name: 'time', type: FieldType.time, values: [1, 2, 3] }, { name: 'temperature.indoor', type: FieldType.number, values: [10, 11, 12] }, ], }); const suggestions = getDataFrameVars([frame]); expect(suggestions).toEqual([ { value: '__data.fields.time', label: 'time', documentation: `Formatted value for time on the same row`, origin: VariableOrigin.Fields, }, { value: '__data.fields["temperature.indoor"]', label: 'temperature.indoor', documentation: `Formatted value for temperature.indoor on the same row`, origin: VariableOrigin.Fields, }, { value: `__data.fields[0]`, label: `Select by index`, documentation: `Enter the field order`, origin: VariableOrigin.Fields, }, { value: `__data.fields["temperature.indoor"].numeric`, label: `Show numeric value`, documentation: `the numeric field value`, origin: VariableOrigin.Fields, }, { value: `__data.fields["temperature.indoor"].text`, label: `Show text value`, documentation: `the text value`, origin: VariableOrigin.Fields, }, ]); }); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { const frame = toDataFrame({ name: 'temperatures', fields: [ { name: 'time', type: FieldType.time, values: [1, 2, 3] }, { name: 'temperature.indoor', type: FieldType.number, values: [10, 11, 12] }, ], }); const suggestions = getDataFrameVars([frame]); expect(suggestions).toEqual([ { value: '__data.fields.time', label: 'time', documentation: `Formatted value for time on the same row`, origin: VariableOrigin.Fields, }, { value: '__data.fields["temperature.indoor"]', label: 'temperature.indoor', documentation: `Formatted value for temperature.indoor on the same row`, origin: VariableOrigin.Fields, }, { value: `__data.fields[0]`, label: `Select by index`, documentation: `Enter the field order`, origin: VariableOrigin.Fields, }, { value: `__data.fields["temperature.indoor"].numeric`, label: `Show numeric value`, documentation: `the numeric field value`, origin: VariableOrigin.Fields, }, { value: `__data.fields["temperature.indoor"].text`, label: `Show text value`, documentation: `the text value`, origin: VariableOrigin.Fields, }, ]); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { it('then it should return correct suggestions', () => { const frame = toDataFrame({ name: 'temperatures', fields: [ { name: 'time', type: FieldType.time, values: [1, 2, 3] }, { name: 'temperature.indoor', type: FieldType.number, values: [10, 11, 12] }, ], }); frame.fields[1].config = { ...frame.fields[1].config, displayName: 'Indoor Temperature' }; const suggestions = getDataFrameVars([frame]); expect(suggestions).toEqual([ { value: '__data.fields.time', label: 'time', documentation: `Formatted value for time on the same row`, origin: VariableOrigin.Fields, }, { value: '__data.fields["Indoor Temperature"]', label: 'Indoor Temperature', documentation: `Formatted value for Indoor Temperature on the same row`, origin: VariableOrigin.Fields, }, { value: `__data.fields[0]`, label: `Select by index`, documentation: `Enter the field order`, origin: VariableOrigin.Fields, }, { value: `__data.fields["Indoor Temperature"].numeric`, label: `Show numeric value`, documentation: `the numeric field value`, origin: VariableOrigin.Fields, }, { value: `__data.fields["Indoor Temperature"].text`, label: `Show text value`, documentation: `the text value`, origin: VariableOrigin.Fields, }, { value: `__data.fields["Indoor Temperature"]`, label: `Select by title`, documentation: `Use the title to pick the field`, origin: VariableOrigin.Fields, }, ]); }); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { const frame = toDataFrame({ name: 'temperatures', fields: [ { name: 'time', type: FieldType.time, values: [1, 2, 3] }, { name: 'temperature.indoor', type: FieldType.number, values: [10, 11, 12] }, ], }); frame.fields[1].config = { ...frame.fields[1].config, displayName: 'Indoor Temperature' }; const suggestions = getDataFrameVars([frame]); expect(suggestions).toEqual([ { value: '__data.fields.time', label: 'time', documentation: `Formatted value for time on the same row`, origin: VariableOrigin.Fields, }, { value: '__data.fields["Indoor Temperature"]', label: 'Indoor Temperature', documentation: `Formatted value for Indoor Temperature on the same row`, origin: VariableOrigin.Fields, }, { value: `__data.fields[0]`, label: `Select by index`, documentation: `Enter the field order`, origin: VariableOrigin.Fields, }, { value: `__data.fields["Indoor Temperature"].numeric`, label: `Show numeric value`, documentation: `the numeric field value`, origin: VariableOrigin.Fields, }, { value: `__data.fields["Indoor Temperature"].text`, label: `Show text value`, documentation: `the text value`, origin: VariableOrigin.Fields, }, { value: `__data.fields["Indoor Temperature"]`, label: `Select by title`, documentation: `Use the title to pick the field`, origin: VariableOrigin.Fields, }, ]); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { it('then it should ignore duplicates', () => { const frame = toDataFrame({ name: 'temperatures', fields: [ { name: 'time', type: FieldType.time, values: [1, 2, 3] }, { name: 'temperature.indoor', type: FieldType.number, values: [10, 11, 12] }, { name: 'temperature.outdoor', type: FieldType.number, values: [20, 21, 22] }, ], }); frame.fields[1].config = { ...frame.fields[1].config, displayName: 'Indoor Temperature' }; // Someone makes a mistake when renaming a field frame.fields[2].config = { ...frame.fields[2].config, displayName: 'Indoor Temperature' }; const suggestions = getDataFrameVars([frame]); expect(suggestions).toEqual([ { value: '__data.fields.time', label: 'time', documentation: `Formatted value for time on the same row`, origin: VariableOrigin.Fields, }, { value: '__data.fields["Indoor Temperature"]', label: 'Indoor Temperature', documentation: `Formatted value for Indoor Temperature on the same row`, origin: VariableOrigin.Fields, }, { value: `__data.fields[0]`, label: `Select by index`, documentation: `Enter the field order`, origin: VariableOrigin.Fields, }, { value: `__data.fields["Indoor Temperature"].numeric`, label: `Show numeric value`, documentation: `the numeric field value`, origin: VariableOrigin.Fields, }, { value: `__data.fields["Indoor Temperature"].text`, label: `Show text value`, documentation: `the text value`, origin: VariableOrigin.Fields, }, { value: `__data.fields["Indoor Temperature"]`, label: `Select by title`, documentation: `Use the title to pick the field`, origin: VariableOrigin.Fields, }, ]); }); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { const frame = toDataFrame({ name: 'temperatures', fields: [ { name: 'time', type: FieldType.time, values: [1, 2, 3] }, { name: 'temperature.indoor', type: FieldType.number, values: [10, 11, 12] }, { name: 'temperature.outdoor', type: FieldType.number, values: [20, 21, 22] }, ], }); frame.fields[1].config = { ...frame.fields[1].config, displayName: 'Indoor Temperature' }; // Someone makes a mistake when renaming a field frame.fields[2].config = { ...frame.fields[2].config, displayName: 'Indoor Temperature' }; const suggestions = getDataFrameVars([frame]); expect(suggestions).toEqual([ { value: '__data.fields.time', label: 'time', documentation: `Formatted value for time on the same row`, origin: VariableOrigin.Fields, }, { value: '__data.fields["Indoor Temperature"]', label: 'Indoor Temperature', documentation: `Formatted value for Indoor Temperature on the same row`, origin: VariableOrigin.Fields, }, { value: `__data.fields[0]`, label: `Select by index`, documentation: `Enter the field order`, origin: VariableOrigin.Fields, }, { value: `__data.fields["Indoor Temperature"].numeric`, label: `Show numeric value`, documentation: `the numeric field value`, origin: VariableOrigin.Fields, }, { value: `__data.fields["Indoor Temperature"].text`, label: `Show text value`, documentation: `the text value`, origin: VariableOrigin.Fields, }, { value: `__data.fields["Indoor Temperature"]`, label: `Select by title`, documentation: `Use the title to pick the field`, origin: VariableOrigin.Fields, }, ]); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { it('it should not return any suggestions', () => { const frame1 = toDataFrame({ name: 'server1', fields: [ { name: 'time', type: FieldType.time, values: [1, 2, 3] }, { name: 'value', type: FieldType.number, values: [10, 11, 12] }, ], }); const frame2 = toDataFrame({ name: 'server2', fields: [ { name: 'time', type: FieldType.time, values: [1, 2, 3] }, { name: 'value', type: FieldType.number, values: [10, 11, 12] }, ], }); const suggestions = getDataFrameVars([frame1, frame2]); expect(suggestions).toEqual([]); }); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => { const frame1 = toDataFrame({ name: 'server1', fields: [ { name: 'time', type: FieldType.time, values: [1, 2, 3] }, { name: 'value', type: FieldType.number, values: [10, 11, 12] }, ], }); const frame2 = toDataFrame({ name: 'server2', fields: [ { name: 'time', type: FieldType.time, values: [1, 2, 3] }, { name: 'value', type: FieldType.number, values: [10, 11, 12] }, ], }); const suggestions = getDataFrameVars([frame1, frame2]); expect(suggestions).toEqual([]); }
axinoss/grafana
public/app/features/panel/panellinks/specs/link_srv.test.ts
TypeScript
ArrowFunction
() => useDispatch<AppDispatch>()
rg872/dg-hoarder
app/src/hooks/redux.ts
TypeScript
ArrowFunction
() => { let content = <> <TwoPageBanner currentUri="contact" /> <section className="contact_area p_120"> <div className="container"> <div className="row"> <div className="col-lg-3"> <div className="contact_info"> <div className="info_item"> <i className="lnr lnr-home"></i> <h6>Paris, France</h6> <p>Gagny</p> </div> {/* <div className="info_item"> <i className="lnr lnr-phone-handset"></i> <h6><a href="#">00 (440) 9865 562</a></h6> <p>Mon to Fri 9am to 6 pm</p> </div> */} <div className="info_item"> <i className="lnr lnr-envelope"></i> <h6><a href="#">[email protected]</a></h6> <p>Toujours présent en cas de besoin.</p> </div> </div> </div> <ContactForm/> </div> </div> </section> </> return content }
YonnaR/portfolio
client/src/Views/user/ContactPage.tsx
TypeScript
ArrowFunction
() => { let component: VerifiedScreenComponent; let fixture: ComponentFixture<VerifiedScreenComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [VerifiedScreenComponent], imports: [ TranslateModule.forRoot(), SharedMaterialModule, ToastrModule.forRoot(), RouterTestingModule, HttpClientModule, ], providers: [UtilService], }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(VerifiedScreenComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }
governmentbg/eAuth-v2
eauth-tfa/src/app/components/verified-screen/verified-screen.component.spec.ts
TypeScript
ArrowFunction
() => { TestBed.configureTestingModule({ declarations: [VerifiedScreenComponent], imports: [ TranslateModule.forRoot(), SharedMaterialModule, ToastrModule.forRoot(), RouterTestingModule, HttpClientModule, ], providers: [UtilService], }).compileComponents(); }
governmentbg/eAuth-v2
eauth-tfa/src/app/components/verified-screen/verified-screen.component.spec.ts
TypeScript
ArrowFunction
() => { fixture = TestBed.createComponent(VerifiedScreenComponent); component = fixture.componentInstance; fixture.detectChanges(); }
governmentbg/eAuth-v2
eauth-tfa/src/app/components/verified-screen/verified-screen.component.spec.ts
TypeScript
ArrowFunction
(link, idx) => ( <React.Fragment key={idx}> {FoundationDataHelper.buildLink(link.url, link.label)}
iotaledger/iota-react-components
src/utils/foundationDataHelper.tsx
TypeScript
ClassDeclaration
/** * Class to help with foundation data. */ export class FoundationDataHelper { /** * The location of the foundation data. */ public static FOUNDATION_DATA_URL: string = "https://webassets.iota.org/data/foundation.json"; /** * Cached version of the data. */ private static _foundationData: IFoundationData; /** * Load the found data. * @returns The loaded foundation data. */ public static async loadData(): Promise<IFoundationData | undefined> { if (!FoundationDataHelper._foundationData) { try { const foundationDataResponse = await fetch(FoundationDataHelper.FOUNDATION_DATA_URL); FoundationDataHelper._foundationData = await foundationDataResponse.json(); } catch { // eslint-disable-next-line no-console console.error(`Failed loading foundation data from ${FoundationDataHelper.FOUNDATION_DATA_URL}`); } } return FoundationDataHelper._foundationData; } /** * Create the display for a value. * @param info The information to display. * @param info.label The label for the information. * @param info.value The optional value for the information. * @param info.urls The optional urls. * @param key The key of the item. * @returns The element to display. */ public static createValue( info: { /** * The label for the information. */ label: string; /** * The optional value for the information. */ value?: string; /** * The optional urls. */ urls?: { /** * The label for the link. */ label: string; /** * The url to link to. */ url: string; }[]; }, key?: Key): React.ReactNode { return ( <React.Fragment key={key}> {info.label && ( <span className="data-label" dangerouslySetInnerHTML={ { __html: FoundationDataHelper.buildLines(info.label) } }
iotaledger/iota-react-components
src/utils/foundationDataHelper.tsx
TypeScript
MethodDeclaration
/** * Load the found data. * @returns The loaded foundation data. */ public static async loadData(): Promise<IFoundationData | undefined> { if (!FoundationDataHelper._foundationData) { try { const foundationDataResponse = await fetch(FoundationDataHelper.FOUNDATION_DATA_URL); FoundationDataHelper._foundationData = await foundationDataResponse.json(); } catch { // eslint-disable-next-line no-console console.error(`Failed loading foundation data from ${FoundationDataHelper.FOUNDATION_DATA_URL}`); } } return FoundationDataHelper._foundationData; }
iotaledger/iota-react-components
src/utils/foundationDataHelper.tsx
TypeScript
MethodDeclaration
/** * Create the display for a value. * @param info The information to display. * @param info.label The label for the information. * @param info.value The optional value for the information. * @param info.urls The optional urls. * @param key The key of the item. * @returns The element to display. */ public static createValue( info: { /** * The label for the information. */ label: string; /** * The optional value for the information. */ value?: string; /** * The optional urls. */ urls?: { /** * The label for the link. */ label: string; /** * The url to link to. */ url: string; }[]; }, key?: Key): React.ReactNode { return ( <React.Fragment key={key}> {info.label && ( <span className="data-label" dangerouslySetInnerHTML={ { __html: FoundationDataHelper.buildLines(info.label) } }
iotaledger/iota-react-components
src/utils/foundationDataHelper.tsx
TypeScript
ArrowFunction
() => { it("should call ParamFilter.useParam method with the correct parameters", () => { class Test {} class Ctrl { test(@Cookies("expression", Test) body: Test) {} } const param = ParamRegistry.get(Ctrl, "test", 0); param.expression.should.eq("expression"); param.paramType.should.eq(ParamTypes.COOKIES); param.type.should.eq(Test); }); }
psicomante/tsed
packages/common/src/mvc/decorators/params/cookies.spec.ts
TypeScript
ArrowFunction
() => { class Test {} class Ctrl { test(@Cookies("expression", Test) body: Test) {} } const param = ParamRegistry.get(Ctrl, "test", 0); param.expression.should.eq("expression"); param.paramType.should.eq(ParamTypes.COOKIES); param.type.should.eq(Test); }
psicomante/tsed
packages/common/src/mvc/decorators/params/cookies.spec.ts
TypeScript
ClassDeclaration
class Test {}
psicomante/tsed
packages/common/src/mvc/decorators/params/cookies.spec.ts
TypeScript
ClassDeclaration
class Ctrl { test(@Cookies("expression", Test) body: Test) {} }
psicomante/tsed
packages/common/src/mvc/decorators/params/cookies.spec.ts
TypeScript
MethodDeclaration
test(@Cookies("expression", Test) body: Test) {}
psicomante/tsed
packages/common/src/mvc/decorators/params/cookies.spec.ts
TypeScript
ArrowFunction
(args: IconProps) => <ThreeDots {...args} />
dkress59/react-loading-icons
stories/herbert-sam/three-dots.stories.tsx
TypeScript
ClassDeclaration
/** * Mesh representing the gorund */ export declare class GroundMesh extends Mesh { /** If octree should be generated */ generateOctree: boolean; private _heightQuads; /** @hidden */ _subdivisionsX: number; /** @hidden */ _subdivisionsY: number; /** @hidden */ _width: number; /** @hidden */ _height: number; /** @hidden */ _minX: number; /** @hidden */ _maxX: number; /** @hidden */ _minZ: number; /** @hidden */ _maxZ: number; constructor(name: string, scene: Scene); /** * "GroundMesh" * @returns "GroundMesh" */ getClassName(): string; /** * The minimum of x and y subdivisions */ get subdivisions(): number; /** * X subdivisions */ get subdivisionsX(): number; /** * Y subdivisions */ get subdivisionsY(): number; /** * This function will update an octree to help to select the right submeshes for rendering, picking and collision computations. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree * @param chunksCount the number of subdivisions for x and y * @param octreeBlocksSize (Default: 32) */ optimize(chunksCount: number, octreeBlocksSize?: number): void; /** * Returns a height (y) value in the Worl system : * the ground altitude at the coordinates (x, z) expressed in the World system. * @param x x coordinate * @param z z coordinate * @returns the ground y position if (x, z) are outside the ground surface. */ getHeightAtCoordinates(x: number, z: number): number; /** * Returns a normalized vector (Vector3) orthogonal to the ground * at the ground coordinates (x, z) expressed in the World system. * @param x x coordinate * @param z z coordinate * @returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface. */ getNormalAtCoordinates(x: number, z: number): Vector3; /** * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground * at the ground coordinates (x, z) expressed in the World system. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface. * @param x x coordinate * @param z z coordinate * @param ref vector to store the result * @returns the GroundMesh. */ getNormalAtCoordinatesToRef(x: number, z: number, ref: Vector3): GroundMesh; /** * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates() * if the ground has been updated. * This can be used in the render loop. * @returns the GroundMesh. */ updateCoordinateHeights(): GroundMesh; private _getFacetAt; private _initHeightQuads; private _computeHeightQuads; /** * Serializes this ground mesh * @param serializationObject object to write serialization to */ serialize(serializationObject: any): void; /** * Parses a serialized ground mesh * @param parsedMesh the serialized mesh * @param scene the scene to create the ground mesh in * @returns the created ground mesh */ static Parse(parsedMesh: any, scene: Scene): GroundMesh; }
Servletparty/pbi-hexagrid
node_modules/@babylonjs/core/Meshes/groundMesh.d.ts
TypeScript
MethodDeclaration
/** * "GroundMesh" * @returns "GroundMesh" */ getClassName(): string;
Servletparty/pbi-hexagrid
node_modules/@babylonjs/core/Meshes/groundMesh.d.ts
TypeScript
MethodDeclaration
/** * This function will update an octree to help to select the right submeshes for rendering, picking and collision computations. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree * @param chunksCount the number of subdivisions for x and y * @param octreeBlocksSize (Default: 32) */ optimize(chunksCount: number, octreeBlocksSize?: number): void;
Servletparty/pbi-hexagrid
node_modules/@babylonjs/core/Meshes/groundMesh.d.ts
TypeScript
MethodDeclaration
/** * Returns a height (y) value in the Worl system : * the ground altitude at the coordinates (x, z) expressed in the World system. * @param x x coordinate * @param z z coordinate * @returns the ground y position if (x, z) are outside the ground surface. */ getHeightAtCoordinates(x: number, z: number): number;
Servletparty/pbi-hexagrid
node_modules/@babylonjs/core/Meshes/groundMesh.d.ts
TypeScript
MethodDeclaration
/** * Returns a normalized vector (Vector3) orthogonal to the ground * at the ground coordinates (x, z) expressed in the World system. * @param x x coordinate * @param z z coordinate * @returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface. */ getNormalAtCoordinates(x: number, z: number): Vector3;
Servletparty/pbi-hexagrid
node_modules/@babylonjs/core/Meshes/groundMesh.d.ts
TypeScript
MethodDeclaration
/** * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground * at the ground coordinates (x, z) expressed in the World system. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface. * @param x x coordinate * @param z z coordinate * @param ref vector to store the result * @returns the GroundMesh. */ getNormalAtCoordinatesToRef(x: number, z: number, ref: Vector3): GroundMesh;
Servletparty/pbi-hexagrid
node_modules/@babylonjs/core/Meshes/groundMesh.d.ts
TypeScript
MethodDeclaration
/** * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates() * if the ground has been updated. * This can be used in the render loop. * @returns the GroundMesh. */ updateCoordinateHeights(): GroundMesh;
Servletparty/pbi-hexagrid
node_modules/@babylonjs/core/Meshes/groundMesh.d.ts
TypeScript
MethodDeclaration
/** * Serializes this ground mesh * @param serializationObject object to write serialization to */ serialize(serializationObject: any): void;
Servletparty/pbi-hexagrid
node_modules/@babylonjs/core/Meshes/groundMesh.d.ts
TypeScript
MethodDeclaration
/** * Parses a serialized ground mesh * @param parsedMesh the serialized mesh * @param scene the scene to create the ground mesh in * @returns the created ground mesh */ static Parse(parsedMesh: any, scene: Scene): GroundMesh;
Servletparty/pbi-hexagrid
node_modules/@babylonjs/core/Meshes/groundMesh.d.ts
TypeScript
ArrowFunction
({ children }) => { const history = useHistory() const isDisabled = history.length <= 2 const handleClick = useCallback(() => history.goBack(), [history]) return ( <div className={classNames('Back', { disabled: isDisabled })} onClick={handleClick} > {children} </div>
jonhue/plaain
src/components/Back.tsx
TypeScript
MethodDeclaration
classNames('Back', { disabled: isDisabled })
jonhue/plaain
src/components/Back.tsx
TypeScript
TypeAliasDeclaration
export type Track = { id: string; name: string; link: string; artist: string[] | null; album: string[] | null; lastPlayed?: string; length: string; };
cephalization/megawave
packages/web/src/types/library.ts
TypeScript
ClassDeclaration
@Component({ selector: 'app-resources', templateUrl: './resources.component.html', styleUrls: ['./resources.component.scss'] }) export class ResourcesComponent implements OnInit { constructor() {} ngOnInit() { // Specifies the language library to load for Highlights.js instead of loading all languages hljs.registerLanguage('javascript', javascript); } }
Narshe1412/Code-Institute-Interactive-Frontend-Algorithms
src/app/resources/resources.component.ts
TypeScript
MethodDeclaration
ngOnInit() { // Specifies the language library to load for Highlights.js instead of loading all languages hljs.registerLanguage('javascript', javascript); }
Narshe1412/Code-Institute-Interactive-Frontend-Algorithms
src/app/resources/resources.component.ts
TypeScript
FunctionDeclaration
export function loadDataSources(): ThunkResult<void> { return async (dispatch) => { const response = await getBackendSrv().get('/api/datasources'); dispatch(dataSourcesLoaded(response)); }; }
fhirfactory/pegacorn-base-docker-node-alpine-itops
public/app/features/datasources/state/actions.ts
TypeScript
FunctionDeclaration
export function loadDataSource(uid: string): ThunkResult<void> { return async (dispatch) => { const dataSource = await getDataSourceUsingUidOrId(uid); const pluginInfo = (await getPluginSettings(dataSource.type)) as DataSourcePluginMeta; const plugin = await importDataSourcePlugin(pluginInfo); const isBackend = plugin.DataSourceClass.prototype instanceof DataSourceWithBackend; const meta = { ...pluginInfo, isBackend: isBackend, }; dispatch(dataSourceLoaded(dataSource)); dispatch(dataSourceMetaLoaded(meta)); plugin.meta = meta; dispatch(updateNavIndex(buildNavModel(dataSource, plugin))); }; }
fhirfactory/pegacorn-base-docker-node-alpine-itops
public/app/features/datasources/state/actions.ts
TypeScript
FunctionDeclaration
/** * Get data source by uid or id, if old id detected handles redirect */ async function getDataSourceUsingUidOrId(uid: string): Promise<DataSourceSettings> { // Try first with uid api try { const byUid = await getBackendSrv() .fetch<DataSourceSettings>({ method: 'GET', url: `/api/datasources/uid/${uid}`, showErrorAlert: false, }) .toPromise(); if (byUid.ok) { return byUid.data; } } catch (err) { console.log('Failed to lookup data source by uid', err); } // try lookup by old db id const id = parseInt(uid, 10); if (!Number.isNaN(id)) { const response = await getBackendSrv() .fetch<DataSourceSettings>({ method: 'GET', url: `/api/datasources/${id}`, showErrorAlert: false, }) .toPromise(); // Not ideal to do a full page reload here but so tricky to handle this // otherwise We can update the location using react router, but need to // fully reload the route as the nav model page index is not matching with // the url in that case. And react router has no way to unmount remount a // route if (response.ok && response.data.id.toString() === uid) { window.location.href = locationUtil.assureBaseUrl(`/datasources/edit/${response.data.uid}`); return {} as DataSourceSettings; // avoids flashing an error } } throw Error('Could not find data source'); }
fhirfactory/pegacorn-base-docker-node-alpine-itops
public/app/features/datasources/state/actions.ts
TypeScript