commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
689f92b793124078239d103a2a10dd7724bf6676
src/site/components/SiteHeader.tsx
src/site/components/SiteHeader.tsx
import * as React from 'react'; import * as config from '../../config'; interface Props { pageType: string; } export default function SiteHeader({pageType}: Props) { return ( <header className="site-header"> <h1 className="site-header__title"> <a href="/"> Game Boy hardware database <aside>by Gekkio and contributors</aside> </a> </h1> <Navigation pageType={pageType} /> </header> ) } const models = config.consoles.map(type => [type.toUpperCase(), type, config.consoleCfgs[type].name]) function isModel(pageType: string, code: string) { return pageType === code || pageType === `${code}-console` } function Navigation({pageType}: Props) { return ( <nav className="site-navigation"> <ul>{ models.map(([model, code, name]) => ( <li key={code} className={(isModel(pageType, code)) ? 'active' : undefined}> <a href={`/consoles/${code}`}> <strong>{model}</strong> <span className="name">{name}</span> </a> </li> )) }</ul> </nav> ) }
import * as React from 'react'; import * as config from '../../config'; interface Props { pageType: string; } export default function SiteHeader({pageType}: Props) { return ( <header className="site-header"> <h1 className="site-header__title"> <a href="/"> Game Boy hardware database <aside>by Gekkio and contributors</aside> </a> </h1> <Navigation pageType={pageType} /> </header> ) } const models = config.consoles.map(type => [type.toUpperCase(), type, config.consoleCfgs[type].name]); function isModel(pageType: string, code: string) { return pageType === code || pageType === `${code}-console` } function isInCartridges(pageType: string): boolean { return pageType === 'cartridges' || pageType === 'cartridge' || pageType === 'game' || pageType === 'mapper'; } function Navigation({pageType}: Props) { return ( <nav className="site-navigation"> <ul> { models.map(([model, code, name]) => ( <li key={code} className={(isModel(pageType, code)) ? 'active' : undefined}> <a href={`/consoles/${code}`}> <strong>{model}</strong> <span className="name">{name}</span> </a> </li> )) } <li className={isInCartridges(pageType) ? 'active' : undefined}> <a href="/cartridges">Game<br />cartridges</a> </li> </ul> </nav> ) }
Add cartridges section to navigation
Add cartridges section to navigation
TypeScript
mit
Gekkio/gb-hardware-db
--- +++ @@ -20,25 +20,34 @@ ) } -const models = config.consoles.map(type => [type.toUpperCase(), type, config.consoleCfgs[type].name]) +const models = config.consoles.map(type => [type.toUpperCase(), type, config.consoleCfgs[type].name]); function isModel(pageType: string, code: string) { return pageType === code || pageType === `${code}-console` } +function isInCartridges(pageType: string): boolean { + return pageType === 'cartridges' || pageType === 'cartridge' || pageType === 'game' || pageType === 'mapper'; +} + function Navigation({pageType}: Props) { return ( <nav className="site-navigation"> - <ul>{ - models.map(([model, code, name]) => ( - <li key={code} className={(isModel(pageType, code)) ? 'active' : undefined}> - <a href={`/consoles/${code}`}> - <strong>{model}</strong> - <span className="name">{name}</span> - </a> - </li> - )) - }</ul> + <ul> + { + models.map(([model, code, name]) => ( + <li key={code} className={(isModel(pageType, code)) ? 'active' : undefined}> + <a href={`/consoles/${code}`}> + <strong>{model}</strong> + <span className="name">{name}</span> + </a> + </li> + )) + } + <li className={isInCartridges(pageType) ? 'active' : undefined}> + <a href="/cartridges">Game<br />cartridges</a> + </li> + </ul> </nav> ) }
422be766954c4204fcac9c37b263fb1182ae55d5
src/app/app-routing.module.ts
src/app/app-routing.module.ts
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { PageComponent } from './page/page.component'; const routes: Routes = [ { path: '', redirectTo: '/main', pathMatch: 'full' }, { path: 'main', component: PageComponent, data: {section: 'main'} }, { path: 'about', component: PageComponent, data: {section: 'about'} }, { path: 'about/:subsection', component: PageComponent, data: {section: 'about'} }, { path: 'articles', component: PageComponent, data: {section: 'articles'} }, { path: 'articles/:subsection', component: PageComponent, data: {section: 'articles'} }, { path: 'gallery', component: PageComponent, data: {section: 'gallery'} }, { path: 'gallery/:subsection', component: PageComponent, data: {section: 'gallery'} }, { path: 'news', component: PageComponent, data: {section: 'news'} }, { path: 'news/:subsection', component: PageComponent, data: {section: 'news'} }, { path: 'form', component: PageComponent, data: {section: 'form'} }, { path: '**', component: PageComponent, data: {section: '404'} } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { PageComponent } from './page/page.component'; const routes: Routes = [ { path: '', redirectTo: '/main', pathMatch: 'full' }, { path: 'main', component: PageComponent, data: {section: 'main'} }, { path: 'about', component: PageComponent, data: {section: 'about'} }, { path: 'about/:subsection', component: PageComponent, data: {section: 'about'} }, { path: 'articles', component: PageComponent, data: {section: 'articles'} }, { path: 'articles/:subsection', component: PageComponent, data: {section: 'articles'} }, { path: 'gallery', component: PageComponent, data: {section: 'gallery'} }, { path: 'gallery/:subsection', component: PageComponent, data: {section: 'gallery'} }, { path: 'news', component: PageComponent, data: {section: 'news'} }, { path: 'news/:subsection', component: PageComponent, data: {section: 'news'} }, { path: 'form', component: PageComponent, data: {section: 'form'} }, { path: 'contact', component: PageComponent, data: {section: 'contact'} }, { path: '**', component: PageComponent, data: {section: '404'} } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
Add contact page to routing
Add contact page to routing
TypeScript
mit
KeJSaR/artezian-info-web,KeJSaR/artezian-info-web,KeJSaR/artezian-info-web,KeJSaR/artezian-info-web
--- +++ @@ -15,6 +15,7 @@ { path: 'news', component: PageComponent, data: {section: 'news'} }, { path: 'news/:subsection', component: PageComponent, data: {section: 'news'} }, { path: 'form', component: PageComponent, data: {section: 'form'} }, + { path: 'contact', component: PageComponent, data: {section: 'contact'} }, { path: '**', component: PageComponent, data: {section: '404'} } ];
a3e650fffaafffaf0792a8166cbd7947b9ef841e
src/app/app.search.service.ts
src/app/app.search.service.ts
import { Injectable } from '@angular/core'; import {Subject} from "rxjs/Rx"; @Injectable() export class SearchService { private searchTerm: string; private subcategories: any; private productType: string; searchChange: Subject<any> = new Subject<any>(); uiChange: Subject<any> = new Subject<any>(); getSearch() { return { "productType": this.productType, "searchTerm": this.searchTerm, "subcategories": this.subcategories, "termIds": this.getTermIds() }; } getTermIds() { let termIds = []; for (var key in this.subcategories) { if (this.subcategories.hasOwnProperty(key)) { let value = this.subcategories[key]; if(value && value != "null") termIds.push(value) } } return termIds; } findAll() { this.searchChange.next(this.getSearch()); } updateSearchParameters(productType, subcategories, updateUI=false) { this.productType = productType; this.subcategories = subcategories; this.searchChange.next(this.getSearch()); if(updateUI) this.uiChange.next(this.getSearch()) } setSearchTerm(searchTerm) { this.searchTerm = searchTerm; this.searchChange.next(this.getSearch()); } }
import { Injectable } from '@angular/core'; import {Subject} from "rxjs/Rx"; @Injectable() export class SearchService { private searchTerm: string; private subcategories: any; private productType: string; searchChange: Subject<any> = new Subject<any>(); uiChange: Subject<any> = new Subject<any>(); getSearch() { return { "productType": this.productType, "searchTerm": this.searchTerm, "subcategories": this.subcategories, "termIds": this.getTermIds() }; } getTermIds() { let termIds = []; console.log('subcats: ', this.subcategories); for (var key in this.subcategories) { if (this.subcategories.hasOwnProperty(key)) { let value = this.subcategories[key]; console.log(value); if(value && value != "null" && value != "undefined") termIds.push(value) } } return termIds; } findAll() { this.searchChange.next(this.getSearch()); } updateSearchParameters(productType, subcategories, updateUI=false) { this.productType = productType; this.subcategories = subcategories; this.searchChange.next(this.getSearch()); if(updateUI) this.uiChange.next(this.getSearch()) } setSearchTerm(searchTerm) { this.searchTerm = searchTerm; this.searchChange.next(this.getSearch()); } }
Stop undefined terms being returned.
Stop undefined terms being returned.
TypeScript
bsd-3-clause
UoA-eResearch/research-hub,UoA-eResearch/research-hub,UoA-eResearch/research-hub
--- +++ @@ -22,10 +22,12 @@ getTermIds() { let termIds = []; + console.log('subcats: ', this.subcategories); for (var key in this.subcategories) { if (this.subcategories.hasOwnProperty(key)) { let value = this.subcategories[key]; - if(value && value != "null") + console.log(value); + if(value && value != "null" && value != "undefined") termIds.push(value) } }
6adf6067eea275cf8272ba1c8ed763f89c08acd2
tests/cases/fourslash/staticGenericOverloads1.ts
tests/cases/fourslash/staticGenericOverloads1.ts
/// <reference path='fourslash.ts'/> ////class A<T> { //// static B<S>(v: A<S>): A<S>; //// static B<S>(v: S): A<S>; //// static B<S>(v: any): A<S> { //// return null; //// } ////} ////var a = new A<number>(); ////A.B(/**/ goTo.marker(); verify.currentSignatureHelpIs('B<S>(v: A<S>): A<S>') // BUG 701161 //edit.insert('a'); //verify.currentSignatureHelpIs('B<S>(v: A<S>): A<S>');
/// <reference path='fourslash.ts'/> ////class A<T> { //// static B<S>(v: A<S>): A<S>; //// static B<S>(v: S): A<S>; //// static B<S>(v: any): A<S> { //// return null; //// } ////} ////var a = new A<number>(); ////A.B(a/**/ goTo.marker(); verify.currentSignatureHelpIs('B<S>(v: A<number>): A<number>') edit.insert('); A.B('); verify.currentSignatureHelpIs('B<S>(v: A<S>): A<S>'); edit.insert('a'); verify.currentSignatureHelpIs('B<S>(v: A<number>): A<number>')
Update the test for the static generic overload
Update the test for the static generic overload
TypeScript
apache-2.0
popravich/typescript,hippich/typescript,hippich/typescript,fdecampredon/jsx-typescript-old-version,fdecampredon/jsx-typescript-old-version,popravich/typescript,mbebenita/shumway.ts,fdecampredon/jsx-typescript-old-version,popravich/typescript,hippich/typescript,mbebenita/shumway.ts,mbebenita/shumway.ts
--- +++ @@ -9,10 +9,11 @@ ////} ////var a = new A<number>(); -////A.B(/**/ +////A.B(a/**/ goTo.marker(); -verify.currentSignatureHelpIs('B<S>(v: A<S>): A<S>') -// BUG 701161 -//edit.insert('a'); -//verify.currentSignatureHelpIs('B<S>(v: A<S>): A<S>'); +verify.currentSignatureHelpIs('B<S>(v: A<number>): A<number>') +edit.insert('); A.B('); +verify.currentSignatureHelpIs('B<S>(v: A<S>): A<S>'); +edit.insert('a'); +verify.currentSignatureHelpIs('B<S>(v: A<number>): A<number>')
09f5b3367467585d00cd69ab9838641b01d460cb
app/pages/home/home.ts
app/pages/home/home.ts
import {Component} from '@angular/core'; import {NavController, Alert} from 'ionic-angular'; import {LocalNotifications} from 'ionic-native'; @Component({ templateUrl: 'build/pages/home/home.html' }) export class HomePage { constructor(public navCtrl: NavController) { } showAlert() { LocalNotifications.schedule({ id: 1, text: "Single Notification" }); } }
import {Component} from '@angular/core'; import {NavController, Alert} from 'ionic-angular'; import {LocalNotifications} from 'ionic-native'; @Component({ templateUrl: 'build/pages/home/home.html' }) export class HomePage { constructor(public navCtrl: NavController) { LocalNotifications.on('click', (notification, state) => { alert(notification.id + " was clicked"); }) } showAlert() { LocalNotifications.schedule({ id: 1, text: "Single Notification" }) } }
Add event to check notification was clicked
Add event to check notification was clicked and return back to app
TypeScript
apache-2.0
teerasej/training-ionic2-local-notification,teerasej/training-ionic2-local-notification,teerasej/training-ionic2-local-notification
--- +++ @@ -9,12 +9,16 @@ export class HomePage { constructor(public navCtrl: NavController) { + LocalNotifications.on('click', (notification, state) => { + alert(notification.id + " was clicked"); + }) + } showAlert() { LocalNotifications.schedule({ id: 1, text: "Single Notification" - }); + }) } }
3bf8c3974fc6ceb2546cbfa501da0386e0f421ab
src/cli.ts
src/cli.ts
import * as commander from "commander"; import { install, parseTyping, uninstall, Typing, TYPINGS_DIR } from "./index"; commander .version(require("../package").version); commander .command("install <name>") .description(`install typings to ${TYPINGS_DIR}`) .action((name: string) => { const typing = parseTyping(name); install(typing); }); commander .command("uninstall <name>") .alias("remove") .description(`uninstall typings from ${TYPINGS_DIR}`) .action((name: string) => { uninstall(name, (err: any) => { if (err) { console.error(err.message); return; } console.log(`Uninstalled: ${name}`); }); }); commander.parse(process.argv);
import * as commander from "commander"; import { install, parseTyping, uninstall, Typing, TYPINGS_DIR } from "./index"; commander .version(require("../package").version); commander .command("install <name> [otherNames...]") .description(`install typings to ${TYPINGS_DIR}`) .action((name: string, otherNames: string[]) => { [name, ...otherNames] .map(parseTyping) .forEach((typing) => install(typing)); // Don't pass in index, array }); commander .command("uninstall <name> [otherNames...]") .alias("remove") .description(`uninstall typings from ${TYPINGS_DIR}`) .action((name: string, otherNames: string[]) => { [name, ...otherNames].forEach((name) => { uninstall(name, (err: any) => { if (err) { console.error(err.message); return; } console.log(`Uninstalled: ${name}`); }); }); }); commander.parse(process.argv);
Support installing/uninstalling more than one package at once
Support installing/uninstalling more than one package at once
TypeScript
mit
tomshen/tsdm
--- +++ @@ -6,24 +6,27 @@ .version(require("../package").version); commander - .command("install <name>") + .command("install <name> [otherNames...]") .description(`install typings to ${TYPINGS_DIR}`) - .action((name: string) => { - const typing = parseTyping(name); - install(typing); + .action((name: string, otherNames: string[]) => { + [name, ...otherNames] + .map(parseTyping) + .forEach((typing) => install(typing)); // Don't pass in index, array }); commander - .command("uninstall <name>") + .command("uninstall <name> [otherNames...]") .alias("remove") .description(`uninstall typings from ${TYPINGS_DIR}`) - .action((name: string) => { - uninstall(name, (err: any) => { - if (err) { - console.error(err.message); - return; - } - console.log(`Uninstalled: ${name}`); + .action((name: string, otherNames: string[]) => { + [name, ...otherNames].forEach((name) => { + uninstall(name, (err: any) => { + if (err) { + console.error(err.message); + return; + } + console.log(`Uninstalled: ${name}`); + }); }); });
2f6a1417da2f45739ee2d74dfafa5cd5e00b1ad9
src/component/index.ts
src/component/index.ts
/* * @license * Copyright Hôpitaux Universitaires de Genève. All Rights Reserved. * * Use of this source code is governed by an Apache-2.0 license that can be * found in the LICENSE file at https://github.com/DSI-HUG/dejajs-components/blob/master/LICENSE */ export * from './accordion/index'; export * from './autosize-textarea/index'; export * from './backdrop/index'; export * from './circular-picker/index'; export * from './code-viewer/index'; export * from './color-picker/index'; export * from './color-selector/index'; export * from './content-editable/index'; export * from './data-grid/index'; export * from './date-selector/index'; export * from './date-picker/index'; export * from './dialog/index'; export * from './dragdrop/index'; export * from './iframe/index'; export * from './mouse-dragdrop/index'; export * from './dropdown/index'; export * from './menu/index'; export * from './select/index'; export * from './templates/index'; export * from './tiles/index'; export * from './loaders/index'; export * from './tree-list/index'; export * from './markdown/index'; export * from './message-box/index'; export * from './monaco-editor/index'; export * from './snackbar/index'; export * from './range/index'; export * from './splitter/index'; export * from './tooltip/index'; export * from './viewport/index'; /* deja-cli export index */ /* The comment above mustn't be removed ! */
export * from './accordion/index'; export * from './autosize-textarea/index'; export * from './backdrop/index'; export * from './circular-picker/index'; export * from './code-viewer/index'; export * from './color-picker/index'; export * from './color-selector/index'; export * from './content-editable/index'; export * from './data-grid/index'; export * from './date-selector/index'; export * from './date-picker/index'; export * from './dialog/index'; export * from './dragdrop/index'; export * from './iframe/index'; export * from './mouse-dragdrop/index'; export * from './dropdown/index'; export * from './menu/index'; export * from './select/index'; export * from './templates/index'; export * from './tiles/index'; export * from './loaders/index'; export * from './tree-list/index'; export * from './markdown/index'; export * from './message-box/index'; export * from './monaco-editor/index'; export * from './snackbar/index'; export * from './range/index'; export * from './splitter/index'; export * from './tooltip/index'; export * from './viewport/index'; /* deja-cli export index */ /* The comment above mustn't be removed ! */
Test commit ts file without license
Test commit ts file without license
TypeScript
apache-2.0
DSI-HUG/dejajs-components,DSI-HUG/dejajs-components,DSI-HUG/dejajs-components,DSI-HUG/dejajs-components
--- +++ @@ -1,11 +1,3 @@ -/* - * @license - * Copyright Hôpitaux Universitaires de Genève. All Rights Reserved. - * - * Use of this source code is governed by an Apache-2.0 license that can be - * found in the LICENSE file at https://github.com/DSI-HUG/dejajs-components/blob/master/LICENSE - */ - export * from './accordion/index'; export * from './autosize-textarea/index'; export * from './backdrop/index';
43dde6d6aa339177ae24367f636c89d06c41054b
src/index.ts
src/index.ts
/// <reference path="../typings/index.d.ts" /> try { require("source-map-support").install(); } catch (e) { /* empty */ } const log4js = require("log4js"); import {app, BrowserWindow} from "electron"; log4js.configure({ appenders: [{ type: "console", layout: { type: "basic" } }] }); async function main() { await new Promise((resolve, reject) => app.once("ready", resolve)); let win = new BrowserWindow({ width: 800, height: 600, resizable: true, show: true }); win.loadURL(`file://${__dirname}/public/index.html`); } main().catch(e => log4js.getLogger().error(e.stack != null ? e.stack : e));
/// <reference path="../typings/index.d.ts" /> try { require("source-map-support").install(); } catch (e) { /* empty */ } const log4js = require("log4js"); import { app, BrowserWindow } from "electron"; log4js.configure({ appenders: [{ type: "console", layout: { type: "basic" } }] }); async function main() { await new Promise((resolve, reject) => app.once("ready", resolve)); app.on("window-all-closed", () => { app.quit() }); let win = new BrowserWindow({ width: 800, height: 600, resizable: true, show: true }); win.loadURL(`file://${__dirname}/public/index.html`); } main().catch(e => log4js.getLogger().error(e.stack != null ? e.stack : e));
Fix exit when window closed
Fix exit when window closed
TypeScript
mit
progre/chatreader,progre/chatreader,progre/chatreader
--- +++ @@ -1,7 +1,7 @@ /// <reference path="../typings/index.d.ts" /> try { require("source-map-support").install(); } catch (e) { /* empty */ } const log4js = require("log4js"); -import {app, BrowserWindow} from "electron"; +import { app, BrowserWindow } from "electron"; log4js.configure({ appenders: [{ type: "console", layout: { type: "basic" } }] @@ -9,6 +9,11 @@ async function main() { await new Promise((resolve, reject) => app.once("ready", resolve)); + + app.on("window-all-closed", () => { + app.quit() + }); + let win = new BrowserWindow({ width: 800, height: 600,
29980b08e15d0ca29109fc263455b6d0f3b99ece
src/tasks/memory_monitor.ts
src/tasks/memory_monitor.ts
import { Client } from 'discord.js'; import * as cron from 'node-cron'; import { log } from '../helpers/logger'; export const startMemoryMonitor = (bot: Client): void => { cron.schedule('45 * * * * *', () => { log('info', bot.shard.ids[0], `memory usage - ${Math.round((process.memoryUsage().rss / 1024) / 102400) / 100} MB`); }).start(); };
import { Client } from 'discord.js'; import * as cron from 'node-cron'; import { log } from '../helpers/logger'; export const startMemoryMonitor = (bot: Client): void => { cron.schedule('45 * * * * *', () => { log('info', bot.shard.ids[0], `memory usage - ${Math.round(process.memoryUsage().rss / 1024 / 1024 * 100) / 100} MB`); }).start(); };
Fix formula for B to MB?
Fix formula for B to MB?
TypeScript
mpl-2.0
BibleBot/BibleBot,BibleBot/BibleBot,BibleBot/BibleBot
--- +++ @@ -4,6 +4,6 @@ export const startMemoryMonitor = (bot: Client): void => { cron.schedule('45 * * * * *', () => { - log('info', bot.shard.ids[0], `memory usage - ${Math.round((process.memoryUsage().rss / 1024) / 102400) / 100} MB`); + log('info', bot.shard.ids[0], `memory usage - ${Math.round(process.memoryUsage().rss / 1024 / 1024 * 100) / 100} MB`); }).start(); };
231d6a6ad59ecabc66b1bf7556782aad779fe29c
7-redux/app/components/users-list-with-details.ts
7-redux/app/components/users-list-with-details.ts
import {Component, CORE_DIRECTIVES} from 'angular2/angular2'; import {SimpleList} from 'InfomediaLtd/angular2-simple-list/app/components/simple-list.ts!'; import {UserView} from "../views/user-view"; import {User} from "../data/user"; import {AppStore} from "angular2-redux"; import {UserActions} from "../actions/user-actions"; @Component({ selector: 'users-with-details', template: ` <simple-list [list]="users" [content]="getContent" [link]="getLink" (current)="selectCurrentUser($event)"> </simple-list> <user *ng-if="currentUser" [user]="currentUser" class="border:1px solid black"></user> `, directives: [CORE_DIRECTIVES, SimpleList, UserView] }) export class UsersListWithDetails { private users:User[]; private currentUser:User; private selectCurrentUser; constructor(private appStore:AppStore, private userActions:UserActions) { this.selectCurrentUser = userActions.createDispatcher(appStore, userActions.setCurrentUser); appStore.subscribe((state) => { this.users = state.users; this.currentUser = state.current; }); appStore.dispatch(userActions.fetchUsers()); } getContent(user:User):string { return user.name; } getLink(user:User):any[] { return ['User', {id:user.id}]; } }
import {Component, CORE_DIRECTIVES} from 'angular2/angular2'; import {SimpleList} from 'InfomediaLtd/angular2-simple-list/app/components/simple-list.ts!'; import {UserView} from "../views/user-view"; import {User} from "../data/user"; import {AppStore} from "angular2-redux"; import {UserActions} from "../actions/user-actions"; @Component({ selector: 'users-with-details', template: ` <simple-list [list]="users" [content]="getContent" [link]="getLink" (current)="selectCurrentUser($event)"> </simple-list> <user *ng-if="currentUser" [user]="currentUser" class="border:1px solid black"></user> `, directives: [CORE_DIRECTIVES, SimpleList, UserView] }) export class UsersListWithDetails { private users:User[]; private currentUser:User; private selectCurrentUser; constructor(appStore:AppStore, userActions:UserActions) { this.selectCurrentUser = userActions.createDispatcher(appStore, userActions.setCurrentUser); appStore.subscribe((state) => { this.users = state.users; this.currentUser = state.current; }); appStore.dispatch(userActions.fetchUsers()); } getContent(user:User):string { return user.name; } getLink(user:User):any[] { return ['User', {id:user.id}]; } }
Use Actions base class to dispatch actions
Use Actions base class to dispatch actions
TypeScript
mit
InfomediaLtd/angular2-tutorial,InfomediaLtd/angular2-tutorial,InfomediaLtd/angular2-tutorial
--- +++ @@ -26,8 +26,7 @@ private selectCurrentUser; - constructor(private appStore:AppStore, - private userActions:UserActions) { + constructor(appStore:AppStore, userActions:UserActions) { this.selectCurrentUser = userActions.createDispatcher(appStore, userActions.setCurrentUser);
e320d274e478a8b8e52bdc63c3fd7b49ed5043f1
src/Test/Ast/RevisionInsertion.ts
src/Test/Ast/RevisionInsertion.ts
import { expect } from 'chai' import Up from '../../index' import { insideDocumentAndParagraph } from './Helpers' import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode' import { EmphasisNode } from '../../SyntaxNodes/EmphasisNode' import { RevisionInsertionNode } from '../../SyntaxNodes/RevisionInsertionNode' describe('Text surrounded by 2 plus signs', () => { it('is put inside a revision insertion node', () => { expect(Up.toAst('I like ++to brush++ my teeth')).to.be.eql( insideDocumentAndParagraph([ new PlainTextNode('I like '), new RevisionInsertionNode([ new PlainTextNode('to brush') ]), new PlainTextNode(' my teeth') ])) }) }) describe('A revision insertion', () => { it('is evaluated for other conventions', () => { expect(Up.toAst('I like ++to *regularly* brush++ my teeth')).to.be.eql( insideDocumentAndParagraph([ new PlainTextNode('I like '), new RevisionInsertionNode([ new PlainTextNode('to '), new EmphasisNode([ new PlainTextNode('regularly') ]), new PlainTextNode(' brush') ]), new PlainTextNode(' my teeth') ])) }) })
import { expect } from 'chai' import Up from '../../index' import { insideDocumentAndParagraph } from './Helpers' import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode' import { EmphasisNode } from '../../SyntaxNodes/EmphasisNode' import { RevisionInsertionNode } from '../../SyntaxNodes/RevisionInsertionNode' describe('Text surrounded by 2 plus signs', () => { it('is put inside a revision insertion node', () => { expect(Up.toAst('I like ++to brush++ my teeth')).to.be.eql( insideDocumentAndParagraph([ new PlainTextNode('I like '), new RevisionInsertionNode([ new PlainTextNode('to brush') ]), new PlainTextNode(' my teeth') ])) }) }) describe('A revision insertion', () => { it('is evaluated for other conventions', () => { expect(Up.toAst('I like ++to *regularly* brush++ my teeth')).to.be.eql( insideDocumentAndParagraph([ new PlainTextNode('I like '), new RevisionInsertionNode([ new PlainTextNode('to '), new EmphasisNode([ new PlainTextNode('regularly') ]), new PlainTextNode(' brush') ]), new PlainTextNode(' my teeth') ])) }) }) describe('An empty revision insertion', () => { it('produces no syntax nodes', () => { expect(Up.toAst('I have nothing to add: ++++')).to.be.eql( insideDocumentAndParagraph([ new PlainTextNode('I have nothing to add: ') ]) ) }) })
Add passing revisoin insertion test
Add passing revisoin insertion test
TypeScript
mit
start/up,start/up
--- +++ @@ -36,3 +36,15 @@ ])) }) }) + + +describe('An empty revision insertion', () => { + it('produces no syntax nodes', () => { + expect(Up.toAst('I have nothing to add: ++++')).to.be.eql( + insideDocumentAndParagraph([ + new PlainTextNode('I have nothing to add: ') + ]) + ) + }) +}) +
913aa5469010918b314c9bb8ac74353ce84dc422
src/redux/ui/reducers.ts
src/redux/ui/reducers.ts
import { ActionShowMenu, ActionHideMenu } from './actions'; import { ActionTypes, Action } from '../actions'; export interface UIState { isMenuShown: boolean; isFullscreen: boolean; } const initialState: UIState = { isMenuShown: false, isFullscreen: false, }; function handleShowMenu(state: UIState, action: ActionShowMenu): UIState { return { ...state, isMenuShown: true, }; } function handleHideMenu(state: UIState, action: ActionHideMenu): UIState { return { ...state, isMenuShown: false, }; } export const ui = (state: UIState = initialState, action: Action): UIState => { switch (action.type) { case ActionTypes.UI_SHOW_MENU: return handleShowMenu(state, action as ActionShowMenu); case ActionTypes.UI_HIDE_MENU: return handleHideMenu(state, action as ActionHideMenu); case ActionTypes.UI_ENTER_FULLSCREEN: case ActionTypes.UI_EXIT_FULLSCREEN: return { ...state, isMenuShown: false }; case ActionTypes.UI_SET_IS_FULLSCREEN: return { ...state, isFullscreen: action.payload.isFullscreen }; default: return state; } };
import { ActionShowMenu, ActionHideMenu } from './actions'; import { ActionTypes, Action } from '../actions'; export interface UIState { isMenuShown: boolean; isFullscreen: boolean; } const initialState: UIState = { isMenuShown: false, isFullscreen: false, }; function handleShowMenu(state: UIState, action: ActionShowMenu): UIState { return { ...state, isMenuShown: true, }; } function handleHideMenu(state: UIState, action: ActionHideMenu): UIState { return { ...state, isMenuShown: false, }; } export const ui = (state: UIState = initialState, action: Action): UIState => { switch (action.type) { case ActionTypes.UI_SHOW_MENU: return handleShowMenu(state, action as ActionShowMenu); case ActionTypes.UI_HIDE_MENU: return handleHideMenu(state, action as ActionHideMenu); case ActionTypes.UI_ENTER_FULLSCREEN: case ActionTypes.UI_EXIT_FULLSCREEN: return { ...state, isMenuShown: false }; case ActionTypes.UI_SET_IS_FULLSCREEN: return { ...state, isFullscreen: action.payload.isFullscreen }; case ActionTypes.ROOM_LOAD: return { ...state, isMenuShown: false }; default: return state; } };
Hide the menu when loading a room
:lipstick: Hide the menu when loading a room
TypeScript
mit
matthewtole/codenames,matthewtole/codenames,matthewtole/codenames
--- +++ @@ -36,6 +36,8 @@ return { ...state, isMenuShown: false }; case ActionTypes.UI_SET_IS_FULLSCREEN: return { ...state, isFullscreen: action.payload.isFullscreen }; + case ActionTypes.ROOM_LOAD: + return { ...state, isMenuShown: false }; default: return state; }
426b69811ad53a5b002056966ae1384145e27987
test/DispatcherSpec.ts
test/DispatcherSpec.ts
import Dispatcher from '../src/Dispatcher'; import * as chai from 'chai'; const expect = chai.expect; import * as path from 'path'; describe('Dispatcher', function () { it.only('Dispatches to fcat', function (done) { Dispatcher .dispatch('fcat', ['one', 'two'] .map((f) => path.resolve(__dirname + '/fixtures/' + f))) .then((results) => expect(results).to.be.deep.equal(['1', '2', '2', '3'])) .then(() => done()) .catch(done); }) })
import Dispatcher from '../src/Dispatcher'; import * as chai from 'chai'; const expect = chai.expect; import * as path from 'path'; describe('Dispatcher', function () { it('Dispatches to fcat', function (done) { Dispatcher .dispatch('fcat', ['one', 'two'] .map((f) => path.resolve(__dirname + '/fixtures/' + f))) .then((results) => expect(results).to.be.deep.equal(['1', '2', '2', '3'])) .then(() => done()) .catch(done); }) })
Remove test narrowing on Dispatcher
Remove test narrowing on Dispatcher
TypeScript
mit
hershal/fp-cli-ts,hershal/fp-cli-ts
--- +++ @@ -6,7 +6,7 @@ import * as path from 'path'; describe('Dispatcher', function () { - it.only('Dispatches to fcat', function (done) { + it('Dispatches to fcat', function (done) { Dispatcher .dispatch('fcat', ['one', 'two'] .map((f) => path.resolve(__dirname + '/fixtures/' + f)))
be53d643823473a236a2665c233d9557085f7144
app/components/maintenance-banner/component.ts
app/components/maintenance-banner/component.ts
import { computed } from '@ember/object'; import $ from 'jquery'; import Component from '@ember/component'; import { task } from 'ember-concurrency'; import config from 'ember-get-config'; import moment from 'moment'; interface MaintenanceData { level?: number, message?: string, start?: string, end?: string, } export default class MaintenanceBanner extends Component.extend({ didReceiveAttrs(): void { this._super(...arguments); this.get('getMaintenanceStatus').perform(); }, maintenance: <MaintenanceData> null, getMaintenanceStatus: task(function* (): void { const url: string = `${config.OSF.apiUrl}/v2/status/`; const data = yield $.ajax(url, 'GET'); this.set('maintenance', data.maintenance); }).restartable(), }) { start = computed('maintenance.start', function(): string { return moment(this.get('maintenance.start')).format('lll'); }); end = computed('maintenance.end', function(): string { return moment(this.get('maintenance.end')).format('lll'); }); utc = computed('maintenance.start', function(): string { return moment(this.get('maintenance.start')).format('ZZ'); }); alertClass = computed('maintenance.level', function(): string { const levelMap = ['info', 'warning', 'danger']; return `alert-${levelMap[this.get('maintenance.level') - 1]}`; }); }
import { computed } from '@ember/object'; import $ from 'jquery'; import Component from '@ember/component'; import { task } from 'ember-concurrency'; import config from 'ember-get-config'; import moment from 'moment'; interface MaintenanceData { level?: number, message?: string, start?: string, end?: string, } export default class MaintenanceBanner extends Component.extend({ didReceiveAttrs(): void { this._super(...arguments); this.get('getMaintenanceStatus').perform(); }, maintenance: <MaintenanceData> null, getMaintenanceStatus: task(function* (): void { const url: string = `${config.OSF.apiUrl}/v2/status/`; const data = yield $.ajax(url, 'GET'); this.set('maintenance', data.maintenance); }).restartable(), }) { start = computed('maintenance.start', (): string => moment(this.get('maintenance.start')).format('lll')); end = computed('maintenance.end', (): string => moment(this.get('maintenance.end')).format('lll')); utc = computed('maintenance.start', (): string => moment(this.get('maintenance.start')).format('ZZ')); alertClass = computed('maintenance.level', (): string => { const levelMap = ['info', 'warning', 'danger']; return `alert-${levelMap[this.get('maintenance.level') - 1]}`; }); }
Use arrow functions when able
Use arrow functions when able
TypeScript
apache-2.0
hmoco/ember-osf-web,hmoco/ember-osf-web,hmoco/ember-osf-web
--- +++ @@ -24,19 +24,13 @@ this.set('maintenance', data.maintenance); }).restartable(), }) { - start = computed('maintenance.start', function(): string { - return moment(this.get('maintenance.start')).format('lll'); - }); + start = computed('maintenance.start', (): string => moment(this.get('maintenance.start')).format('lll')); - end = computed('maintenance.end', function(): string { - return moment(this.get('maintenance.end')).format('lll'); - }); + end = computed('maintenance.end', (): string => moment(this.get('maintenance.end')).format('lll')); - utc = computed('maintenance.start', function(): string { - return moment(this.get('maintenance.start')).format('ZZ'); - }); + utc = computed('maintenance.start', (): string => moment(this.get('maintenance.start')).format('ZZ')); - alertClass = computed('maintenance.level', function(): string { + alertClass = computed('maintenance.level', (): string => { const levelMap = ['info', 'warning', 'danger']; return `alert-${levelMap[this.get('maintenance.level') - 1]}`; });
d360e2f98660e4f91e2a120f25f75395cdd50b49
src/xrm-mock/usersettings/usersettings.mock.ts
src/xrm-mock/usersettings/usersettings.mock.ts
export class UserSettingsMock implements Xrm.UserSettings { public defaultDashboardId: string; public isGuidedHelpEnabled: boolean; public isHighContrastEnabled: boolean; public isRTL: boolean; public languageId: number; public securityRolePrivileges: string[]; public securityRoles: string[]; public transactionCurrencyId: string; public userId: string; public userName: string; constructor(components: IUserSettingsComponents) { this.defaultDashboardId = components.defaultDashboardId; this.isGuidedHelpEnabled = components.isGuidedHelpEnabled; this.isHighContrastEnabled = components.isHighContrastEnabled; this.isRTL = components.isRTL; this.languageId = components.languageId; this.securityRolePrivileges = components.securityRolePrivileges; this.securityRoles = components.securityRoles; this.transactionCurrencyId = components.transactionCurrencyId; this.userId = components.userId; this.userName = components.userName; } public dateFormattingInfo(): Xrm.DateFormattingInfo { throw new Error("Not implemented."); } public getTimeZoneOffsetMinutes(): number { throw new Error("Not implemented"); } } export interface IUserSettingsComponents { defaultDashboardId?: string; isGuidedHelpEnabled: boolean; isHighContrastEnabled: boolean; isRTL: boolean; languageId?: number; securityRolePrivileges?: string[]; securityRoles?: string[]; transactionCurrencyId?: string; userId: string; userName: string; }
export class UserSettingsMock implements Xrm.UserSettings { public defaultDashboardId: string; public isGuidedHelpEnabled: boolean; public isHighContrastEnabled: boolean; public isRTL: boolean; public languageId: number; public securityRolePrivileges: string[]; public securityRoles: string[]; public transactionCurrencyId: string; public userId: string; public userName: string; public roles: Xrm.Collection.ItemCollection<Xrm.LookupValue>; public transactionCurrency: Xrm.LookupValue; constructor(components: IUserSettingsComponents) { this.defaultDashboardId = components.defaultDashboardId; this.isGuidedHelpEnabled = components.isGuidedHelpEnabled; this.isHighContrastEnabled = components.isHighContrastEnabled; this.isRTL = components.isRTL; this.languageId = components.languageId; this.securityRolePrivileges = components.securityRolePrivileges; this.securityRoles = components.securityRoles; this.transactionCurrencyId = components.transactionCurrencyId; this.userId = components.userId; this.userName = components.userName; this.roles = components.roles; this.transactionCurrency = components.transactionCurrency; } public dateFormattingInfo(): Xrm.DateFormattingInfo { throw new Error("Not implemented."); } public getTimeZoneOffsetMinutes(): number { throw new Error("Not implemented"); } } export interface IUserSettingsComponents { defaultDashboardId?: string; isGuidedHelpEnabled: boolean; isHighContrastEnabled: boolean; isRTL: boolean; languageId?: number; securityRolePrivileges?: string[]; securityRoles?: string[]; transactionCurrencyId?: string; userId: string; userName: string; roles?: Xrm.Collection.ItemCollection<Xrm.LookupValue>; transactionCurrency?: Xrm.LookupValue; }
Add missing properties in getGlobalContext.userSettings
Add missing properties in getGlobalContext.userSettings
TypeScript
mit
camelCaseDave/xrm-mock,camelCaseDave/xrm-mock
--- +++ @@ -9,6 +9,8 @@ public transactionCurrencyId: string; public userId: string; public userName: string; + public roles: Xrm.Collection.ItemCollection<Xrm.LookupValue>; + public transactionCurrency: Xrm.LookupValue; constructor(components: IUserSettingsComponents) { this.defaultDashboardId = components.defaultDashboardId; @@ -21,11 +23,14 @@ this.transactionCurrencyId = components.transactionCurrencyId; this.userId = components.userId; this.userName = components.userName; + this.roles = components.roles; + this.transactionCurrency = components.transactionCurrency; } public dateFormattingInfo(): Xrm.DateFormattingInfo { throw new Error("Not implemented."); } + public getTimeZoneOffsetMinutes(): number { throw new Error("Not implemented"); } @@ -42,4 +47,6 @@ transactionCurrencyId?: string; userId: string; userName: string; + roles?: Xrm.Collection.ItemCollection<Xrm.LookupValue>; + transactionCurrency?: Xrm.LookupValue; }
cfda6267fc7dc7585e406e6b963bb3384909c054
src/testing/support/createElement.ts
src/testing/support/createElement.ts
/** * Create HTML and SVG elements from a valid HTML string. * * The given HTML must contain only one root element, of type `Element`. */ export function createElement(html: string): Element { return document.createRange().createContextualFragment(html).firstElementChild as Element }
/** * Create HTML and SVG elements from a valid HTML string. * * NOTE The given HTML must contain only one root element, of type `Element`. */ export function createElement(html: string): Element { return document.createRange().createContextualFragment(html).firstElementChild as Element }
Change comment for consistency and clarity
Change comment for consistency and clarity
TypeScript
agpl-3.0
inad9300/Soil,inad9300/Soil
--- +++ @@ -1,7 +1,7 @@ /** * Create HTML and SVG elements from a valid HTML string. * - * The given HTML must contain only one root element, of type `Element`. + * NOTE The given HTML must contain only one root element, of type `Element`. */ export function createElement(html: string): Element { return document.createRange().createContextualFragment(html).firstElementChild as Element
4d6952361e5b2d35513036ab5e79da5bcb5bfe81
server/helpers/markdown.ts
server/helpers/markdown.ts
import { getSanitizeOptions, TEXT_WITH_HTML_RULES } from '@shared/core-utils' const sanitizeOptions = getSanitizeOptions() const sanitizeHtml = require('sanitize-html') const markdownItEmoji = require('markdown-it-emoji/light') const MarkdownItClass = require('markdown-it') const markdownIt = new MarkdownItClass('default', { linkify: true, breaks: true, html: true }) markdownIt.enable(TEXT_WITH_HTML_RULES) markdownIt.use(markdownItEmoji) const toSafeHtml = text => { if (!text) return '' // Restore line feed const textWithLineFeed = text.replace(/<br.?\/?>/g, '\r\n') // Convert possible markdown (emojis, emphasis and lists) to html const html = markdownIt.render(textWithLineFeed) // Convert to safe Html return sanitizeHtml(html, sanitizeOptions) } const mdToPlainText = text => { if (!text) return '' // Convert possible markdown (emojis, emphasis and lists) to html const html = markdownIt.render(text) // Convert to safe Html const safeHtml = sanitizeHtml(html, sanitizeOptions) return safeHtml.replace(/<[^>]+>/g, '') .replace(/\n$/, '') .replace('\n', ', ') } // --------------------------------------------------------------------------- export { toSafeHtml, mdToPlainText }
import { getSanitizeOptions, TEXT_WITH_HTML_RULES } from '@shared/core-utils' const sanitizeOptions = getSanitizeOptions() const sanitizeHtml = require('sanitize-html') const markdownItEmoji = require('markdown-it-emoji/light') const MarkdownItClass = require('markdown-it') const markdownIt = new MarkdownItClass('default', { linkify: true, breaks: true, html: true }) markdownIt.enable(TEXT_WITH_HTML_RULES) markdownIt.use(markdownItEmoji) const toSafeHtml = text => { if (!text) return '' // Restore line feed const textWithLineFeed = text.replace(/<br.?\/?>/g, '\r\n') // Convert possible markdown (emojis, emphasis and lists) to html const html = markdownIt.render(textWithLineFeed) // Convert to safe Html return sanitizeHtml(html, sanitizeOptions) } const mdToPlainText = text => { if (!text) return '' // Convert possible markdown (emojis, emphasis and lists) to html const html = markdownIt.render(text) // Convert to safe Html const safeHtml = sanitizeHtml(html, sanitizeOptions) return safeHtml.replace(/<[^>]+>/g, '') .replace(/\n$/, '') .replace(/\n/g, ', ') } // --------------------------------------------------------------------------- export { toSafeHtml, mdToPlainText }
Fix multiple \n in md to plain text
Fix multiple \n in md to plain text
TypeScript
agpl-3.0
Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube
--- +++ @@ -34,7 +34,7 @@ return safeHtml.replace(/<[^>]+>/g, '') .replace(/\n$/, '') - .replace('\n', ', ') + .replace(/\n/g, ', ') } // ---------------------------------------------------------------------------
108a66f0dac7586f2f7871c6bb77f73cb924f2b3
client/src/app/core/routing/redirect.service.ts
client/src/app/core/routing/redirect.service.ts
import { Injectable } from '@angular/core' import { Router } from '@angular/router' import { ServerService } from '../server' @Injectable() export class RedirectService { // Default route could change according to the instance configuration static INIT_DEFAULT_ROUTE = '/videos/trending' static DEFAULT_ROUTE = RedirectService.INIT_DEFAULT_ROUTE constructor ( private router: Router, private serverService: ServerService ) { // The config is first loaded from the cache so try to get the default route const config = this.serverService.getConfig() if (config && config.instance && config.instance.defaultClientRoute) { RedirectService.DEFAULT_ROUTE = config.instance.defaultClientRoute } this.serverService.configLoaded .subscribe(() => { const defaultRouteConfig = this.serverService.getConfig().instance.defaultClientRoute if (defaultRouteConfig) { RedirectService.DEFAULT_ROUTE = defaultRouteConfig } }) } redirectToHomepage () { console.log('Redirecting to %s...', RedirectService.DEFAULT_ROUTE) this.router.navigate([ RedirectService.DEFAULT_ROUTE ]) .catch(() => { console.error( 'Cannot navigate to %s, resetting default route to %s.', RedirectService.DEFAULT_ROUTE, RedirectService.INIT_DEFAULT_ROUTE ) RedirectService.DEFAULT_ROUTE = RedirectService.INIT_DEFAULT_ROUTE return this.router.navigate([ RedirectService.DEFAULT_ROUTE ]) }) } }
import { Injectable } from '@angular/core' import { Router } from '@angular/router' import { ServerService } from '../server' @Injectable() export class RedirectService { // Default route could change according to the instance configuration static INIT_DEFAULT_ROUTE = '/videos/trending' static DEFAULT_ROUTE = RedirectService.INIT_DEFAULT_ROUTE constructor ( private router: Router, private serverService: ServerService ) { // The config is first loaded from the cache so try to get the default route const config = this.serverService.getConfig() if (config && config.instance && config.instance.defaultClientRoute) { RedirectService.DEFAULT_ROUTE = config.instance.defaultClientRoute } this.serverService.configLoaded .subscribe(() => { const defaultRouteConfig = this.serverService.getConfig().instance.defaultClientRoute if (defaultRouteConfig) { RedirectService.DEFAULT_ROUTE = defaultRouteConfig } }) } redirectToHomepage () { console.log('Redirecting to %s...', RedirectService.DEFAULT_ROUTE) this.router.navigate([ RedirectService.DEFAULT_ROUTE ], { replaceUrl: true }) .catch(() => { console.error( 'Cannot navigate to %s, resetting default route to %s.', RedirectService.DEFAULT_ROUTE, RedirectService.INIT_DEFAULT_ROUTE ) RedirectService.DEFAULT_ROUTE = RedirectService.INIT_DEFAULT_ROUTE return this.router.navigate([ RedirectService.DEFAULT_ROUTE ], { replaceUrl: true }) }) } }
Fix history back after a redirect
Fix history back after a redirect
TypeScript
agpl-3.0
Green-Star/PeerTube,Green-Star/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube,Green-Star/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube,Green-Star/PeerTube
--- +++ @@ -31,7 +31,7 @@ redirectToHomepage () { console.log('Redirecting to %s...', RedirectService.DEFAULT_ROUTE) - this.router.navigate([ RedirectService.DEFAULT_ROUTE ]) + this.router.navigate([ RedirectService.DEFAULT_ROUTE ], { replaceUrl: true }) .catch(() => { console.error( 'Cannot navigate to %s, resetting default route to %s.', @@ -40,7 +40,7 @@ ) RedirectService.DEFAULT_ROUTE = RedirectService.INIT_DEFAULT_ROUTE - return this.router.navigate([ RedirectService.DEFAULT_ROUTE ]) + return this.router.navigate([ RedirectService.DEFAULT_ROUTE ], { replaceUrl: true }) }) }
4c49e9bc8a1703dc3aa6701a51bd1bdb43c01e2e
packages/components/containers/topBanners/WelcomeV4TopBanner.tsx
packages/components/containers/topBanners/WelcomeV4TopBanner.tsx
import React from 'react'; import { c } from 'ttag'; import { APPS, SSO_PATHS } from 'proton-shared/lib/constants'; import TopBanner from './TopBanner'; import { useConfig } from '../../hooks'; const IS_INITIAL_LOGIN = [SSO_PATHS.AUTHORIZE, SSO_PATHS.LOGIN, '/'].includes(window.location.pathname); const WelcomeV4TopBanner = () => { const { APP_NAME } = useConfig(); if (!IS_INITIAL_LOGIN || APP_NAME !== APPS.PROTONACCOUNT) { return null; } return ( <TopBanner className="bg-info"> {c('Message display when user visit v4 login first time') .t`Welcome to the new ProtonMail design, modern and easy to use. Sign in to discover more.`} </TopBanner> ); }; export default WelcomeV4TopBanner;
import React from 'react'; import { c } from 'ttag'; import { APPS, SSO_PATHS } from 'proton-shared/lib/constants'; import TopBanner from './TopBanner'; import { useConfig } from '../../hooks'; import { Href } from '../../components'; const IS_INITIAL_LOGIN = [SSO_PATHS.AUTHORIZE, SSO_PATHS.LOGIN, '/'].includes(window.location.pathname); const WelcomeV4TopBanner = () => { const { APP_NAME } = useConfig(); if (!IS_INITIAL_LOGIN || APP_NAME !== APPS.PROTONACCOUNT) { return null; } return ( <TopBanner className="bg-info"> <span className="mr0-5">{c('Message display when user visit v4 login first time') .t`Welcome to the new ProtonMail design, modern and easy to use. Sign in to discover more.`}</span> <Href className="underline inline-block color-inherit" url="https://protonmail.com/blog/new-protonmail">{c( 'Link' ).t`Learn more`}</Href> </TopBanner> ); }; export default WelcomeV4TopBanner;
Update welcome v4 banner to includes link
Update welcome v4 banner to includes link
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -4,6 +4,7 @@ import TopBanner from './TopBanner'; import { useConfig } from '../../hooks'; +import { Href } from '../../components'; const IS_INITIAL_LOGIN = [SSO_PATHS.AUTHORIZE, SSO_PATHS.LOGIN, '/'].includes(window.location.pathname); @@ -16,8 +17,11 @@ return ( <TopBanner className="bg-info"> - {c('Message display when user visit v4 login first time') - .t`Welcome to the new ProtonMail design, modern and easy to use. Sign in to discover more.`} + <span className="mr0-5">{c('Message display when user visit v4 login first time') + .t`Welcome to the new ProtonMail design, modern and easy to use. Sign in to discover more.`}</span> + <Href className="underline inline-block color-inherit" url="https://protonmail.com/blog/new-protonmail">{c( + 'Link' + ).t`Learn more`}</Href> </TopBanner> ); };
35a7d8cfb6c6be4980835a5da029caf1bfc671d6
config/config.local.ts
config/config.local.ts
import * as Config from "webpack-chain"; import * as CommonConfig from "./config.common"; import { Credentials, EnvOptions } from "./types"; function webpackConfig(options: EnvOptions = {}): Config { // get the common configuration to start with const config = CommonConfig.init(options); // TIP: if you symlink the below path into your project as `local`, // it makes for much easier debugging: // (make sure you symlink the dir, not the files) // `# ln -s /path/to/local/deploy/dir ./dist/local` const credentials: Credentials = require("./credentials.json") config.output.path(credentials.outputPath); // modify the args of "define" plugin config.plugin("define").tap((args: any[]) => { args[0].PRODUCTION = JSON.stringify(false); return args; }); // HACK to add .js extension for local server config.output.sourceMapFilename("[file].map.js"); return config; } module.exports = webpackConfig;
/* tslint:disable:no-require-imports */ import * as Config from "webpack-chain"; import * as CommonConfig from "./config.common"; import { Credentials, EnvOptions } from "./types"; function webpackConfig(options: EnvOptions = {}): Config { // get the common configuration to start with const config = CommonConfig.init(options); // TIP: if you symlink the below path into your project as `local`, // it makes for much easier debugging: // (make sure you symlink the dir, not the files) // `# ln -s /path/to/local/deploy/dir ./dist/local` const credentials: Credentials = require("./credentials.json") config.output.path(credentials.outputPath); // modify the args of "define" plugin config.plugin("define").tap((args: any[]) => { args[0].PRODUCTION = JSON.stringify(false); return args; }); // HACK to add .js extension for local server config.output.sourceMapFilename("[file].map.js"); return config; } module.exports = webpackConfig;
Disable no-require-imports on config files
Disable no-require-imports on config files
TypeScript
mit
resir014/screeps,resir014/screeps
--- +++ @@ -1,3 +1,4 @@ +/* tslint:disable:no-require-imports */ import * as Config from "webpack-chain"; import * as CommonConfig from "./config.common";
a068ef8ad62426c2635cea2163dfe5ac6c558599
front-end/src/app/components/search-form/search-form.directive.ts
front-end/src/app/components/search-form/search-form.directive.ts
import { ApiInterface } from '../../common/services/api.service'; /** @ngInject */ export function searchForm(): angular.IDirective { return { restrict: 'E', scope: {}, templateUrl: 'app/components/search-form/search-form.view.html', controller: SearchFormController, controllerAs: 'vm', bindToController: true, link: function () {} }; } /** @ngInject */ class SearchFormController { searchResult:any[] = []; judges:any[] = []; api:any = {}; searchQuery:string = ''; constructor(constants:any, Api:ApiInterface) { console.log('SearchForm injected!'); this.api = Api; this.api.getData().then(res => { debugger; this.judges = res; }); } findData () { } }
import { ApiInterface } from '../../common/services/api.service'; /** @ngInject */ export function searchForm():angular.IDirective { return { restrict: 'E', scope: {}, templateUrl: 'app/components/search-form/search-form.view.html', controller: SearchFormController, controllerAs: 'vm', bindToController: true, link: function () { } }; } /** @ngInject */ class SearchFormController { searchResult:any[] = []; judges:any[] = []; api:any = {}; searchQuery:string = ''; constructor(constants:any, Api:ApiInterface) { console.log('SearchForm injected!'); this.api = Api; this.api.getData().then(res => { this.judges = res; }); } findData() { } }
Reduce lint warnings delete "debugger"
Reduce lint warnings delete "debugger"
TypeScript
mit
automaidan/judges,automaidan/judges,automaidan/judges,automaidan/judges
--- +++ @@ -1,6 +1,6 @@ import { ApiInterface } from '../../common/services/api.service'; /** @ngInject */ -export function searchForm(): angular.IDirective { +export function searchForm():angular.IDirective { return { restrict: 'E', @@ -9,7 +9,8 @@ controller: SearchFormController, controllerAs: 'vm', bindToController: true, - link: function () {} + link: function () { + } }; } @@ -25,12 +26,12 @@ console.log('SearchForm injected!'); this.api = Api; this.api.getData().then(res => { - debugger; this.judges = res; }); } - findData () { + + findData() { } }
16ef5f4b158e3339c332156a65d0a6685c9f3cfd
src/pages/home/home.e2e.ts
src/pages/home/home.e2e.ts
import { browser, by, element } from 'protractor'; class HomeObj { public title; constructor() { // this.title = element(by.id('title')); } } describe('App', () => { // beforeEach(() => { // browser.get('/'); // }); // const home: HomeObj = new HomeObj(); // it('should have a title', () => { // expect((home.title).isDisplayed()).toBeTruthy(); // }); });
import { browser, by, element } from 'protractor'; class HomeObj { public title; constructor() { // this.title = element(by.id('title')); } } describe('App', () => { // beforeEach(() => { // browser.get('/'); // }); // const home: HomeObj = new HomeObj(); // it('should have a title', () => { // expect((home.title).isDisplayed()).toBeTruthy(); // }); });
Add correct indentation to config files
Add correct indentation to config files
TypeScript
mit
kojinkai/predictor-ionic,kojinkai/predictor-ionic,kojinkai/predictor-ionic,kojinkai/predictor-ionic
--- +++ @@ -18,4 +18,5 @@ // it('should have a title', () => { // expect((home.title).isDisplayed()).toBeTruthy(); // }); + });
d2f506845e451dbb61a3e0133cb8bed68f5ce22d
src/vs/languages/html/common/html.contribution.ts
src/vs/languages/html/common/html.contribution.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import modesExtensions = require('vs/editor/common/modes/modesRegistry'); modesExtensions.registerMode({ id: 'html', extensions: ['.html', '.htm', '.shtml', '.mdoc', '.jsp', '.asp', '.aspx', '.jshtm'], aliases: ['HTML', 'htm', 'html', 'xhtml'], mimetypes: ['text/html', 'text/x-jshtm', 'text/template'], moduleId: 'vs/languages/html/common/html', ctorName: 'HTMLMode' });
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import modesExtensions = require('vs/editor/common/modes/modesRegistry'); modesExtensions.registerMode({ id: 'html', extensions: ['.html', '.htm', '.shtml', '.mdoc', '.jsp', '.asp', '.aspx', '.jshtm'], aliases: ['HTML', 'htm', 'html', 'xhtml'], mimetypes: ['text/html', 'text/x-jshtm', 'text/template', 'text/ng-template'], moduleId: 'vs/languages/html/common/html', ctorName: 'HTMLMode' });
Add text/ng-template to the HTML mime types to enable HTML highlighting/help in Angular templates with in <script> blocks
Add text/ng-template to the HTML mime types to enable HTML highlighting/help in Angular templates with in <script> blocks
TypeScript
mit
matthewshirley/vscode,f111fei/vscode,joaomoreno/vscode,edumunoz/vscode,the-ress/vscode,rishii7/vscode,mjbvz/vscode,KattMingMing/vscode,f111fei/vscode,0xmohit/vscode,the-ress/vscode,Zalastax/vscode,sifue/vscode,cleidigh/vscode,ups216/vscode,eamodio/vscode,Microsoft/vscode,veeramarni/vscode,microlv/vscode,cleidigh/vscode,hoovercj/vscode,eamodio/vscode,KattMingMing/vscode,matthewshirley/vscode,stkb/vscode,ioklo/vscode,start/vscode,matthewshirley/vscode,hungys/vscode,oneplus1000/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,williamcspace/vscode,Krzysztof-Cieslak/vscode,cra0zy/VSCode,cleidigh/vscode,Krzysztof-Cieslak/vscode,rishii7/vscode,KattMingMing/vscode,joaomoreno/vscode,eklavyamirani/vscode,eklavyamirani/vscode,williamcspace/vscode,0xmohit/vscode,radshit/vscode,Zalastax/vscode,microsoft/vscode,markrendle/vscode,Krzysztof-Cieslak/vscode,edumunoz/vscode,markrendle/vscode,jchadwick/vscode,stringham/vscode,takumif/vscode,gagangupt16/vscode,charlespierce/vscode,zyml/vscode,michaelcfanning/vscode,rishii7/vscode,charlespierce/vscode,Zalastax/vscode,0xmohit/vscode,radshit/vscode,joaomoreno/vscode,hashhar/vscode,veeramarni/vscode,dersia/vscode,bsmr-x-script/vscode,cleidigh/vscode,matthewshirley/vscode,gagangupt16/vscode,bsmr-x-script/vscode,hoovercj/vscode,eamodio/vscode,Zalastax/vscode,zyml/vscode,cleidigh/vscode,microsoft/vscode,Microsoft/vscode,sifue/vscode,start/vscode,charlespierce/vscode,mjbvz/vscode,gagangupt16/vscode,stringham/vscode,the-ress/vscode,cleidigh/vscode,KattMingMing/vscode,hoovercj/vscode,dersia/vscode,gagangupt16/vscode,zyml/vscode,hashhar/vscode,Microsoft/vscode,veeramarni/vscode,radshit/vscode,zyml/vscode,zyml/vscode,hashhar/vscode,mjbvz/vscode,sifue/vscode,DustinCampbell/vscode,hoovercj/vscode,veeramarni/vscode,ups216/vscode,williamcspace/vscode,start/vscode,radshit/vscode,Microsoft/vscode,alexandrudima/vscode,2947721120/vscode,gagangupt16/vscode,stringham/vscode,joaomoreno/vscode,hashhar/vscode,jchadwick/vscode,SofianHn/vscode,KattMingMing/vscode,microlv/vscode,edumunoz/vscode,Zalastax/vscode,gagangupt16/vscode,gagangupt16/vscode,punker76/vscode,rishii7/vscode,jchadwick/vscode,rishii7/vscode,cleidigh/vscode,Microsoft/vscode,jchadwick/vscode,Zalastax/vscode,0xmohit/vscode,eklavyamirani/vscode,gagangupt16/vscode,mjbvz/vscode,joaomoreno/vscode,tottok-ug/vscode,sifue/vscode,DustinCampbell/vscode,joaomoreno/vscode,ioklo/vscode,jchadwick/vscode,ups216/vscode,rick111111/vscode,radshit/vscode,oneplus1000/vscode,hungys/vscode,michaelcfanning/vscode,hungys/vscode,williamcspace/vscode,DustinCampbell/vscode,landonepps/vscode,takumif/vscode,the-ress/vscode,hungys/vscode,joaomoreno/vscode,alexandrudima/vscode,landonepps/vscode,f111fei/vscode,markrendle/vscode,edumunoz/vscode,f111fei/vscode,veeramarni/vscode,0xmohit/vscode,microsoft/vscode,stringham/vscode,eklavyamirani/vscode,matthewshirley/vscode,stringham/vscode,hashhar/vscode,ioklo/vscode,Krzysztof-Cieslak/vscode,michaelcfanning/vscode,mjbvz/vscode,hungys/vscode,eamodio/vscode,zyml/vscode,cleidigh/vscode,microlv/vscode,veeramarni/vscode,bsmr-x-script/vscode,eklavyamirani/vscode,stringham/vscode,hoovercj/vscode,jchadwick/vscode,hoovercj/vscode,edumunoz/vscode,microsoft/vscode,mjbvz/vscode,eamodio/vscode,Microsoft/vscode,gagangupt16/vscode,rick111111/vscode,DustinCampbell/vscode,edumunoz/vscode,edumunoz/vscode,ioklo/vscode,KattMingMing/vscode,bsmr-x-script/vscode,markrendle/vscode,cleidigh/vscode,charlespierce/vscode,microlv/vscode,edumunoz/vscode,charlespierce/vscode,0xmohit/vscode,williamcspace/vscode,oneplus1000/vscode,rishii7/vscode,williamcspace/vscode,matthewshirley/vscode,the-ress/vscode,Microsoft/vscode,mjbvz/vscode,ups216/vscode,veeramarni/vscode,f111fei/vscode,zyml/vscode,the-ress/vscode,eklavyamirani/vscode,landonepps/vscode,ups216/vscode,mjbvz/vscode,bsmr-x-script/vscode,zyml/vscode,matthewshirley/vscode,Krzysztof-Cieslak/vscode,charlespierce/vscode,the-ress/vscode,rick111111/vscode,punker76/vscode,ioklo/vscode,charlespierce/vscode,jchadwick/vscode,mjbvz/vscode,landonepps/vscode,DustinCampbell/vscode,joaomoreno/vscode,jchadwick/vscode,stringham/vscode,eklavyamirani/vscode,hoovercj/vscode,hoovercj/vscode,veeramarni/vscode,Zalastax/vscode,sifue/vscode,Zalastax/vscode,microsoft/vscode,hoovercj/vscode,DustinCampbell/vscode,williamcspace/vscode,williamcspace/vscode,eamodio/vscode,f111fei/vscode,matthewshirley/vscode,cleidigh/vscode,microlv/vscode,start/vscode,rishii7/vscode,f111fei/vscode,sifue/vscode,hashhar/vscode,joaomoreno/vscode,matthewshirley/vscode,stringham/vscode,DustinCampbell/vscode,zyml/vscode,charlespierce/vscode,veeramarni/vscode,radshit/vscode,landonepps/vscode,sifue/vscode,KattMingMing/vscode,the-ress/vscode,microlv/vscode,bsmr-x-script/vscode,mjbvz/vscode,Microsoft/vscode,rishii7/vscode,joaomoreno/vscode,edumunoz/vscode,Krzysztof-Cieslak/vscode,edumunoz/vscode,jchadwick/vscode,dersia/vscode,ups216/vscode,DustinCampbell/vscode,edumunoz/vscode,veeramarni/vscode,eamodio/vscode,microlv/vscode,radshit/vscode,ioklo/vscode,hungys/vscode,zyml/vscode,cleidigh/vscode,ups216/vscode,stringham/vscode,microlv/vscode,Zalastax/vscode,microsoft/vscode,DustinCampbell/vscode,zyml/vscode,alexandrudima/vscode,sifue/vscode,Microsoft/vscode,Zalastax/vscode,the-ress/vscode,rick111111/vscode,microsoft/vscode,hashhar/vscode,rishii7/vscode,Krzysztof-Cieslak/vscode,hashhar/vscode,dersia/vscode,cleidigh/vscode,jchadwick/vscode,stkb/vscode,tottok-ug/vscode,DustinCampbell/vscode,edumunoz/vscode,hashhar/vscode,matthewshirley/vscode,0xmohit/vscode,hungys/vscode,ups216/vscode,Microsoft/vscode,edumunoz/vscode,veeramarni/vscode,f111fei/vscode,gagangupt16/vscode,KattMingMing/vscode,charlespierce/vscode,Krzysztof-Cieslak/vscode,bsmr-x-script/vscode,bsmr-x-script/vscode,0xmohit/vscode,sifue/vscode,bsmr-x-script/vscode,microsoft/vscode,eklavyamirani/vscode,ioklo/vscode,stringham/vscode,hungys/vscode,williamcspace/vscode,veeramarni/vscode,williamcspace/vscode,microsoft/vscode,f111fei/vscode,microsoft/vscode,stringham/vscode,microlv/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,landonepps/vscode,mjbvz/vscode,tottok-ug/vscode,stringham/vscode,f111fei/vscode,mjbvz/vscode,williamcspace/vscode,Zalastax/vscode,hoovercj/vscode,rishii7/vscode,ups216/vscode,f111fei/vscode,zyml/vscode,Microsoft/vscode,2947721120/vscode,sifue/vscode,rishii7/vscode,ups216/vscode,edumunoz/vscode,veeramarni/vscode,ups216/vscode,sifue/vscode,the-ress/vscode,joaomoreno/vscode,KattMingMing/vscode,oneplus1000/vscode,eklavyamirani/vscode,microsoft/vscode,veeramarni/vscode,punker76/vscode,matthewshirley/vscode,KattMingMing/vscode,bsmr-x-script/vscode,radshit/vscode,2947721120/vscode,0xmohit/vscode,Krzysztof-Cieslak/vscode,radshit/vscode,cleidigh/vscode,f111fei/vscode,microlv/vscode,radshit/vscode,f111fei/vscode,eklavyamirani/vscode,SofianHn/vscode,the-ress/vscode,jchadwick/vscode,veeramarni/vscode,ioklo/vscode,microlv/vscode,hashhar/vscode,0xmohit/vscode,microlv/vscode,stringham/vscode,gagangupt16/vscode,hashhar/vscode,ups216/vscode,ioklo/vscode,hungys/vscode,williamcspace/vscode,eklavyamirani/vscode,Krzysztof-Cieslak/vscode,microlv/vscode,jchadwick/vscode,ioklo/vscode,Zalastax/vscode,hungys/vscode,eamodio/vscode,williamcspace/vscode,DustinCampbell/vscode,gagangupt16/vscode,f111fei/vscode,rishii7/vscode,Microsoft/vscode,ioklo/vscode,eamodio/vscode,hungys/vscode,eklavyamirani/vscode,0xmohit/vscode,the-ress/vscode,DustinCampbell/vscode,matthewshirley/vscode,KattMingMing/vscode,landonepps/vscode,microlv/vscode,jchadwick/vscode,alexandrudima/vscode,joaomoreno/vscode,radshit/vscode,landonepps/vscode,radshit/vscode,eklavyamirani/vscode,ioklo/vscode,microsoft/vscode,hoovercj/vscode,ioklo/vscode,eamodio/vscode,0xmohit/vscode,landonepps/vscode,mjbvz/vscode,williamcspace/vscode,bsmr-x-script/vscode,gagangupt16/vscode,eamodio/vscode,stringham/vscode,microsoft/vscode,takumif/vscode,charlespierce/vscode,joaomoreno/vscode,the-ress/vscode,eamodio/vscode,DustinCampbell/vscode,0xmohit/vscode,charlespierce/vscode,Zalastax/vscode,sifue/vscode,rishii7/vscode,landonepps/vscode,KattMingMing/vscode,rishii7/vscode,hungys/vscode,edumunoz/vscode,radshit/vscode,stringham/vscode,hungys/vscode,Krzysztof-Cieslak/vscode,f111fei/vscode,microsoft/vscode,eamodio/vscode,hungys/vscode,sifue/vscode,SofianHn/vscode,hashhar/vscode,hungys/vscode,mjbvz/vscode,joaomoreno/vscode,rishii7/vscode,charlespierce/vscode,hashhar/vscode,ups216/vscode,stkb/vscode,eamodio/vscode,sifue/vscode,landonepps/vscode,hoovercj/vscode,DustinCampbell/vscode,hashhar/vscode,ups216/vscode,joaomoreno/vscode,cleidigh/vscode,matthewshirley/vscode,DustinCampbell/vscode,KattMingMing/vscode,jchadwick/vscode,Zalastax/vscode,radshit/vscode,eamodio/vscode,bsmr-x-script/vscode,microlv/vscode,rishii7/vscode,Microsoft/vscode,jchadwick/vscode,DustinCampbell/vscode,charlespierce/vscode,hashhar/vscode,jchadwick/vscode,stringham/vscode,mjbvz/vscode,zyml/vscode,KattMingMing/vscode,Microsoft/vscode,microlv/vscode,eklavyamirani/vscode,landonepps/vscode,rkeithhill/VSCode,hoovercj/vscode,veeramarni/vscode,the-ress/vscode,landonepps/vscode,jchadwick/vscode,matthewshirley/vscode,SofianHn/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,0xmohit/vscode,Krzysztof-Cieslak/vscode,eklavyamirani/vscode,zyml/vscode,0xmohit/vscode,charlespierce/vscode,charlespierce/vscode,michaelcfanning/vscode,Krzysztof-Cieslak/vscode,Zalastax/vscode,landonepps/vscode,KattMingMing/vscode,mjbvz/vscode,hoovercj/vscode,KattMingMing/vscode,bsmr-x-script/vscode,cleidigh/vscode,ioklo/vscode,veeramarni/vscode,ioklo/vscode,gagangupt16/vscode,zyml/vscode,sifue/vscode,matthewshirley/vscode,takumif/vscode,gagangupt16/vscode,joaomoreno/vscode,cleidigh/vscode,bsmr-x-script/vscode,2947721120/vscode,Microsoft/vscode,0xmohit/vscode,landonepps/vscode,f111fei/vscode,Microsoft/vscode,eamodio/vscode,ups216/vscode,Zalastax/vscode,gagangupt16/vscode,microsoft/vscode,rishii7/vscode,williamcspace/vscode,hashhar/vscode,the-ress/vscode,charlespierce/vscode,mjbvz/vscode,radshit/vscode,punker76/vscode,eklavyamirani/vscode,hoovercj/vscode,KattMingMing/vscode,Zalastax/vscode,DustinCampbell/vscode,eklavyamirani/vscode,stringham/vscode,zyml/vscode,matthewshirley/vscode,microsoft/vscode,the-ress/vscode,bsmr-x-script/vscode,williamcspace/vscode,joaomoreno/vscode,0xmohit/vscode,stkb/vscode,bsmr-x-script/vscode,landonepps/vscode,hoovercj/vscode,microlv/vscode,tottok-ug/vscode,hashhar/vscode,hungys/vscode,ups216/vscode,cleidigh/vscode,matthewshirley/vscode,charlespierce/vscode,sifue/vscode,Krzysztof-Cieslak/vscode,zyml/vscode,ioklo/vscode,radshit/vscode,landonepps/vscode,gagangupt16/vscode,radshit/vscode,hungys/vscode,ups216/vscode,edumunoz/vscode,hoovercj/vscode,williamcspace/vscode
--- +++ @@ -10,7 +10,7 @@ id: 'html', extensions: ['.html', '.htm', '.shtml', '.mdoc', '.jsp', '.asp', '.aspx', '.jshtm'], aliases: ['HTML', 'htm', 'html', 'xhtml'], - mimetypes: ['text/html', 'text/x-jshtm', 'text/template'], + mimetypes: ['text/html', 'text/x-jshtm', 'text/template', 'text/ng-template'], moduleId: 'vs/languages/html/common/html', ctorName: 'HTMLMode' });
0cdd7af407f46169601ec81f396409ebc576a0c3
platforms/platform-alexa/src/AlexaHandles.ts
platforms/platform-alexa/src/AlexaHandles.ts
import { HandleOptions, Jovo } from '@jovotech/framework'; import { AlexaRequest } from './AlexaRequest'; import { PermissionStatus } from './interfaces'; export type PermissionType = 'timers' | 'reminders'; export class AlexaHandles { static onPermission(status: PermissionStatus, type?: PermissionType): HandleOptions { return { global: true, types: ['Connections.Response'], platforms: ['alexa'], if: (jovo: Jovo) => (jovo.$request as AlexaRequest).request?.name === 'AskFor' && (jovo.$request as AlexaRequest).request?.payload?.status === status && (type ? (jovo.$request as AlexaRequest).request?.payload?.permissionScope === `alexa::alerts:${type}:skill:readwrite` : true), }; } }
import { HandleOptions, Jovo } from '@jovotech/framework'; import { AlexaRequest } from './AlexaRequest'; import { PermissionStatus } from './interfaces'; export type PermissionType = 'timers' | 'reminders'; export class AlexaHandles { static onPermission(status: PermissionStatus, type?: PermissionType): HandleOptions { return { global: true, types: ['Connections.Response'], platforms: ['alexa'], if: (jovo: Jovo) => (jovo.$request as AlexaRequest).request?.name === 'AskFor' && (jovo.$request as AlexaRequest).request?.payload?.status === status && (type ? (jovo.$request as AlexaRequest).request?.payload?.permissionScope === `alexa::alerts:${type}:skill:readwrite` : true), }; } static onDialogInvoked(): HandleOptions { return { global: true, types: ['Dialog.API.Invoked'], platforms: ['alexa'], }; } }
Add onDialogInvoked to handle hand-off from Alexa Conversations
:sparkles: Add onDialogInvoked to handle hand-off from Alexa Conversations
TypeScript
apache-2.0
jovotech/jovo-framework-nodejs,jovotech/jovo-framework-nodejs
--- +++ @@ -19,4 +19,12 @@ : true), }; } + + static onDialogInvoked(): HandleOptions { + return { + global: true, + types: ['Dialog.API.Invoked'], + platforms: ['alexa'], + }; + } }
06e7bc39ce24164e3623b6c630e79af84af1c9bb
admin/src/main/app-ui/src/app/mapping-interface.ts
admin/src/main/app-ui/src/app/mapping-interface.ts
export interface MappingValues { OriginTissue: string; TumorType: string; SampleDiagnosis: string; DataSource: string; } export interface Mapping { entityId: number; entityType: string; mappingLabels: string[]; mappingValues: MappingValues; mappedTerm?: any; mapType?: any; justification?: any; status: string; suggestedMappings: any[]; dateCreated?: any; dateUpdated?: any; } export interface MappingInterface { mappings: Mapping[]; }
export interface MappingValues { OriginTissue: string; TumorType: string; SampleDiagnosis: string; DataSource: string; } export interface Mapping { entityId: number; entityType: string; mappingLabels: string[]; mappingValues: MappingValues; mappedTerm?: any; mapType?: any; justification?: any; status: string; suggestedMappings: any[]; dateCreated?: any; dateUpdated?: any; } export interface MappingInterface { mappings: Mapping[]; size: number; totalElements: number; totaPages: number; page: number; beginIndex: number; endIndex: number; currentIndex: number; }
Extend the Data Transfer Object Interface in angular to capture pagination info
Extend the Data Transfer Object Interface in angular to capture pagination info
TypeScript
apache-2.0
PDXFinder/pdxfinder,PDXFinder/pdxfinder,PDXFinder/pdxfinder,PDXFinder/pdxfinder
--- +++ @@ -20,7 +20,14 @@ } export interface MappingInterface { + mappings: Mapping[]; + + size: number; + totalElements: number; + totaPages: number; + page: number; + beginIndex: number; + endIndex: number; + currentIndex: number; } - -
72f4c0223b751e579194d44d02bbe2dc7a550a41
src/test/model-utils.spec.ts
src/test/model-utils.spec.ts
import {fdescribe,describe,expect,fit,it,xit, inject,beforeEach, beforeEachProviders} from 'angular2/testing'; import {provide} from "angular2/core"; import {IdaiFieldObject} from "../app/model/idai-field-object"; import {ModelUtils} from "../app/model/model-utils"; /** * @author Jan G. Wieners */ export function main() { describe('ModelUtils', () => { it('should clone an IdaiFieldObject with all of its properties', function(){ var initialObject = { "identifier": "ob1", "title": "Title", "synced": 0, "valid": true, "type": "Object" }; var clonedObject = ModelUtils.clone(initialObject); //clonedObject.identifier = "obNew"; // make test fail expect(clonedObject).toEqual(initialObject); } ); }) }
import {fdescribe,describe,expect,fit,it,xit, inject,beforeEach, beforeEachProviders} from 'angular2/testing'; import {provide} from "angular2/core"; import {IdaiFieldObject} from "../app/model/idai-field-object"; import {ModelUtils} from "../app/model/model-utils"; /** * @author Jan G. Wieners */ export function main() { describe('ModelUtils', () => { it('should clone an IdaiFieldObject with all of its properties if no filter properties are given', function(){ var initialObject = { "identifier": "ob1", "title": "Title", "synced": 0, "valid": true, "type": "Object" }; var clonedObject = ModelUtils.filterUnwantedProps(initialObject); expect(clonedObject).toEqual(initialObject); } ); it('should create a full copy of an IdaiFieldObject, not just a reference to the object', function(){ var initialObject = { "identifier": "ob1", "title": "Title", "synced": 0, "valid": true, "type": "Object" }; var clonedObject = ModelUtils.filterUnwantedProps(initialObject); expect(clonedObject).not.toBe(initialObject); } ); it('should create a clone of an IdaiFieldObject which lacks defined properties', function(){ var initialObject = { "identifier": "ob1", "title": "Title", "synced": 0, "valid": true, "type": "Object" }; var clonedObject = ModelUtils.filterUnwantedProps(initialObject, ['title', 'synced', 'type']); var filteredObject = { "identifier": "ob1", "valid": true }; expect(clonedObject).toEqual(filteredObject); } ); }) }
Add tests for cloning objects and filtering unwanted object propierties.
Add tests for cloning objects and filtering unwanted object propierties.
TypeScript
apache-2.0
codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client
--- +++ @@ -9,7 +9,7 @@ export function main() { describe('ModelUtils', () => { - it('should clone an IdaiFieldObject with all of its properties', + it('should clone an IdaiFieldObject with all of its properties if no filter properties are given', function(){ var initialObject = { @@ -19,10 +19,43 @@ "valid": true, "type": "Object" }; - var clonedObject = ModelUtils.clone(initialObject); + var clonedObject = ModelUtils.filterUnwantedProps(initialObject); + expect(clonedObject).toEqual(initialObject); + } + ); - //clonedObject.identifier = "obNew"; // make test fail - expect(clonedObject).toEqual(initialObject); + it('should create a full copy of an IdaiFieldObject, not just a reference to the object', + function(){ + + var initialObject = { + "identifier": "ob1", + "title": "Title", + "synced": 0, + "valid": true, + "type": "Object" + }; + var clonedObject = ModelUtils.filterUnwantedProps(initialObject); + expect(clonedObject).not.toBe(initialObject); + } + ); + + it('should create a clone of an IdaiFieldObject which lacks defined properties', + function(){ + + var initialObject = { + "identifier": "ob1", + "title": "Title", + "synced": 0, + "valid": true, + "type": "Object" + }; + var clonedObject = ModelUtils.filterUnwantedProps(initialObject, ['title', 'synced', 'type']); + + var filteredObject = { + "identifier": "ob1", + "valid": true + }; + expect(clonedObject).toEqual(filteredObject); } ); })
82c47a0d04856a7bfea468db580a20f62a2f55cb
examples/spaceGame.ts
examples/spaceGame.ts
import { Boolean, Number, String, Literal, Array, Tuple, Record, Union, Static } from '../src/index' const Vector = Tuple(Number, Number, Number) type Vector = Static<typeof Vector> const Asteroid = Record({ type: Literal('asteroid'), location: Vector, mass: Number, }) type Asteroid = Static<typeof Asteroid> const Planet = Record({ type: Literal('planet'), location: Vector, mass: Number, population: Number, habitable: Boolean, }) type Planet = Static<typeof Planet> const Rank = Union( Literal('captain'), Literal('first mate'), Literal('officer'), Literal('ensign'), ) type Rank = Static<typeof Rank> const CrewMember = Record({ name: String, age: Number, rank: Rank, home: Planet, }) type CrewMember = Static<typeof CrewMember> const Ship = Record({ type: Literal('ship'), location: Vector, mass: Number, name: String, crew: Array(CrewMember), }) type Ship = Static<typeof Ship> const SpaceObject = Union(Asteroid, Planet, Ship) type SpaceObject = Static<typeof SpaceObject>
import { Boolean, Number, String, Literal, Array, Tuple, Record, Union, Static } from '../src/index' const NonNegative = Number.withConstraint(n => n >= 0) const Vector = Tuple(Number, Number, Number) type Vector = Static<typeof Vector> const Asteroid = Record({ type: Literal('asteroid'), location: Vector, mass: NonNegative, }) type Asteroid = Static<typeof Asteroid> const Planet = Record({ type: Literal('planet'), location: Vector, mass: NonNegative, population: NonNegative, habitable: Boolean, }) type Planet = Static<typeof Planet> const Rank = Union( Literal('captain'), Literal('first mate'), Literal('officer'), Literal('ensign'), ) type Rank = Static<typeof Rank> const CrewMember = Record({ name: String, age: NonNegative, rank: Rank, home: Planet, }) type CrewMember = Static<typeof CrewMember> const Ship = Record({ type: Literal('ship'), location: Vector, mass: NonNegative, name: String, crew: Array(CrewMember), }) type Ship = Static<typeof Ship> const SpaceObject = Union(Asteroid, Planet, Ship) type SpaceObject = Static<typeof SpaceObject>
Add a constraint to the example
Add a constraint to the example
TypeScript
mit
pelotom/runtypes,typeetfunc/runtypes,pelotom/runtypes
--- +++ @@ -1,4 +1,6 @@ import { Boolean, Number, String, Literal, Array, Tuple, Record, Union, Static } from '../src/index' + +const NonNegative = Number.withConstraint(n => n >= 0) const Vector = Tuple(Number, Number, Number) type Vector = Static<typeof Vector> @@ -6,15 +8,15 @@ const Asteroid = Record({ type: Literal('asteroid'), location: Vector, - mass: Number, + mass: NonNegative, }) type Asteroid = Static<typeof Asteroid> const Planet = Record({ type: Literal('planet'), location: Vector, - mass: Number, - population: Number, + mass: NonNegative, + population: NonNegative, habitable: Boolean, }) type Planet = Static<typeof Planet> @@ -29,7 +31,7 @@ const CrewMember = Record({ name: String, - age: Number, + age: NonNegative, rank: Rank, home: Planet, }) @@ -38,7 +40,7 @@ const Ship = Record({ type: Literal('ship'), location: Vector, - mass: Number, + mass: NonNegative, name: String, crew: Array(CrewMember), })
3c1c688716409baf0e104ec9631b1cf3f95ccf37
packages/lesswrong/components/posts/PostsPage/PostsPageEventData.tsx
packages/lesswrong/components/posts/PostsPage/PostsPageEventData.tsx
import React from 'react' import { registerComponent, Components } from '../../../lib/vulcan-lib'; import Typography from '@material-ui/core/Typography' const styles = theme => ({ metadata: { marginTop:theme.spacing.unit*3, ...theme.typography.postStyle, color: 'rgba(0,0,0,0.5)', } }) const PostsPageEventData = ({classes, post}: { classes: ClassesType, post: PostsBase, }) => { const { location, contactInfo } = post return <Typography variant="body2" className={classes.metadata}> <div className={classes.eventTimes}> <Components.EventTime post={post} dense={false} /> </div> { location && <div className={classes.eventLocation}> {location} </div> } { contactInfo && <div className={classes.eventContact}> Contact: {contactInfo} </div> } </Typography> } const PostsPageEventDataComponent = registerComponent('PostsPageEventData', PostsPageEventData, {styles}); declare global { interface ComponentTypes { PostsPageEventData: typeof PostsPageEventDataComponent } }
import React from 'react' import { registerComponent, Components } from '../../../lib/vulcan-lib'; import Typography from '@material-ui/core/Typography' const styles = theme => ({ metadata: { marginTop:theme.spacing.unit*3, ...theme.typography.postStyle, color: 'rgba(0,0,0,0.5)', } }) const PostsPageEventData = ({classes, post}: { classes: ClassesType, post: PostsBase, }) => { const { location, contactInfo } = post return <Typography variant="body2" className={classes.metadata}> <div className={classes.eventTimes}> <Components.EventTime post={post} dense={false} /> </div> { location && <div className={classes.eventLocation}> {location} </div> } { contactInfo && <div className={classes.eventContact}> Contact: {contactInfo} </div> } <Components.Covid19Notice/> </Typography> } const PostsPageEventDataComponent = registerComponent('PostsPageEventData', PostsPageEventData, {styles}); declare global { interface ComponentTypes { PostsPageEventData: typeof PostsPageEventDataComponent } }
Add COVID-19 notice to event pages
Add COVID-19 notice to event pages
TypeScript
mit
Discordius/Lesswrong2,Discordius/Telescope,Discordius/Telescope,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Lesswrong2
--- +++ @@ -19,6 +19,7 @@ <div className={classes.eventTimes}> <Components.EventTime post={post} dense={false} /> </div> { location && <div className={classes.eventLocation}> {location} </div> } { contactInfo && <div className={classes.eventContact}> Contact: {contactInfo} </div> } + <Components.Covid19Notice/> </Typography> }
1dcf933dde3946397d38dde78ddc668c66d728d7
packages/@sanity/field/src/diff/annotations/DiffAnnotationCard.tsx
packages/@sanity/field/src/diff/annotations/DiffAnnotationCard.tsx
import React, {createElement} from 'react' import {useAnnotationColor} from './hooks' import {AnnotationProps, AnnotatedDiffProps} from './DiffAnnotation' import {getAnnotationAtPath} from './helpers' interface BaseDiffAnnotationCardProps { as?: React.ElementType | keyof JSX.IntrinsicElements } export type DiffAnnotationCardProps = (AnnotationProps | AnnotatedDiffProps) & BaseDiffAnnotationCardProps export function DiffAnnotationCard( props: DiffAnnotationCardProps & React.HTMLProps<HTMLDivElement> ): React.ReactElement { const {as = 'div', children, style = {}, ...restProps} = props const annotation = 'diff' in props ? getAnnotationAtPath(props.diff, props.path || []) : props.annotation const color = useAnnotationColor(annotation) const colorStyle = color ? {background: color.background, color: color.text} : {} return createElement(as, {...restProps, style: {...colorStyle, ...style}}, children) }
import React, {createElement} from 'react' import {useAnnotationColor} from './hooks' import {AnnotationProps, AnnotatedDiffProps} from './DiffAnnotation' import {getAnnotationAtPath} from './helpers' import {Diff, Annotation} from '../../types' import {Path} from '../../paths' interface BaseDiffAnnotationCardProps { as?: React.ElementType | keyof JSX.IntrinsicElements diff?: Diff path?: Path | string annotation?: Annotation } export type DiffAnnotationCardProps = (AnnotationProps | AnnotatedDiffProps) & BaseDiffAnnotationCardProps export function DiffAnnotationCard( props: DiffAnnotationCardProps & React.HTMLProps<HTMLDivElement> ): React.ReactElement { const { as = 'div', children, path, diff, annotation: specifiedAnnotation, style = {}, ...restProps } = props const annotation = diff ? getAnnotationAtPath(diff, path || []) : specifiedAnnotation const color = useAnnotationColor(annotation) const colorStyle = color ? {background: color.background, color: color.text} : {} return createElement(as, {...restProps, style: {...colorStyle, ...style}}, children) }
Fix diff/path/annotation passed down to DOM element
[field] Fix diff/path/annotation passed down to DOM element
TypeScript
mit
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
--- +++ @@ -2,9 +2,14 @@ import {useAnnotationColor} from './hooks' import {AnnotationProps, AnnotatedDiffProps} from './DiffAnnotation' import {getAnnotationAtPath} from './helpers' +import {Diff, Annotation} from '../../types' +import {Path} from '../../paths' interface BaseDiffAnnotationCardProps { as?: React.ElementType | keyof JSX.IntrinsicElements + diff?: Diff + path?: Path | string + annotation?: Annotation } export type DiffAnnotationCardProps = (AnnotationProps | AnnotatedDiffProps) & @@ -13,10 +18,17 @@ export function DiffAnnotationCard( props: DiffAnnotationCardProps & React.HTMLProps<HTMLDivElement> ): React.ReactElement { - const {as = 'div', children, style = {}, ...restProps} = props - const annotation = - 'diff' in props ? getAnnotationAtPath(props.diff, props.path || []) : props.annotation + const { + as = 'div', + children, + path, + diff, + annotation: specifiedAnnotation, + style = {}, + ...restProps + } = props + const annotation = diff ? getAnnotationAtPath(diff, path || []) : specifiedAnnotation const color = useAnnotationColor(annotation) const colorStyle = color ? {background: color.background, color: color.text} : {} return createElement(as, {...restProps, style: {...colorStyle, ...style}}, children)
7699ca680dd0a6c5b81da3e1a5cc194c46e8c87c
src/app/doc/utilities/code.card.component.ts
src/app/doc/utilities/code.card.component.ts
import { Component, Input } from '@angular/core'; @Component({ selector: 'codeCard', template: `<plrsCard sectioned title="Angular Code"> <pre><code>{{ code }}</code></pre> </plrsCard>`, styles: ["plrscard {margin-top: 2rem;}"] }) export class CodeCardComponent { @Input() public code = ''; }
import { Component, Input } from '@angular/core'; @Component({ selector: 'codeCard', template: `<plrsCard sectioned title="Angular Code"> <pre><code>{{ code }}</code></pre> </plrsCard>`, styles: [ "plrscard {margin-top: 2rem;}", "pre {overflow: auto;}" ] }) export class CodeCardComponent { @Input() public code = ''; }
Allow scrolling of the code.
Allow scrolling of the code.
TypeScript
mit
syrp-nz/angular-polaris,syrp-nz/angular-polaris,syrp-nz/angular-polaris
--- +++ @@ -4,7 +4,10 @@ template: `<plrsCard sectioned title="Angular Code"> <pre><code>{{ code }}</code></pre> </plrsCard>`, - styles: ["plrscard {margin-top: 2rem;}"] + styles: [ + "plrscard {margin-top: 2rem;}", + "pre {overflow: auto;}" + ] }) export class CodeCardComponent { @Input() public code = '';
b2ef9b22bb880342e7688303b698a7410ee98763
server/src/providers/DocumentSymbolProvider.ts
server/src/providers/DocumentSymbolProvider.ts
import { DocumentSymbol, DocumentSymbolParams, IConnection } from 'vscode-languageserver'; import Provider from './Provider'; import { analyses } from '../Analyzer'; export default class DocumentSymbolProvider extends Provider { static register(connection: IConnection) { return new DocumentSymbolProvider(connection); } constructor(connection: IConnection) { super(connection); this.connection.onDocumentSymbol(this.handleDocumentSymbol); } private handleDocumentSymbol = async ( params: DocumentSymbolParams ): Promise<DocumentSymbol[]> => { const { textDocument: { uri }, } = params; const analysis = analyses.getAnalysis(uri); console.log(JSON.stringify(analysis.documentSymbols)); return analysis.documentSymbols; }; }
import { DocumentSymbol, DocumentSymbolParams, IConnection } from 'vscode-languageserver'; import Provider from './Provider'; import { analyses } from '../Analyzer'; export default class DocumentSymbolProvider extends Provider { static register(connection: IConnection) { return new DocumentSymbolProvider(connection); } constructor(connection: IConnection) { super(connection); this.connection.onDocumentSymbol(this.handleDocumentSymbol); } private handleDocumentSymbol = async ( params: DocumentSymbolParams ): Promise<DocumentSymbol[]> => { const { textDocument: { uri }, } = params; const analysis = analyses.getAnalysis(uri); return analysis.documentSymbols; }; }
Remove document symbol console.log statement
Remove document symbol console.log statement
TypeScript
mit
rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby
--- +++ @@ -19,7 +19,6 @@ textDocument: { uri }, } = params; const analysis = analyses.getAnalysis(uri); - console.log(JSON.stringify(analysis.documentSymbols)); return analysis.documentSymbols; }; }
c6feaa016a92ff3ef9ba36ea6694a43f04712e2d
tests/cases/fourslash/completionListImplementingInterfaceFunctions.ts
tests/cases/fourslash/completionListImplementingInterfaceFunctions.ts
/// <reference path="fourslash.ts" /> ////interface I1 { //// a(): void; //// b(): void; ////} //// ////var imp1: I1 { //// a() {}, //// /*0*/ ////} //// ////interface I2 { //// a(): void; //// b(): void; ////} //// ////var imp2: I2 { //// a: () => {}, //// /*1*/ ////} goTo.marker("0"); verify.not.completionListContains("a"); goTo.marker("1"); verify.not.completionListContains("a");
/// <reference path="fourslash.ts" /> ////interface I1 { //// a(): void; //// b(): void; ////} //// ////var imp1: I1 { //// a() {}, //// /*0*/ ////} //// ////var imp2: I1 { //// a: () => {}, //// /*1*/ ////} goTo.marker("0"); verify.not.completionListContains("a"); goTo.marker("1"); verify.not.completionListContains("a");
Remove unnecessary I2 from test case
Remove unnecessary I2 from test case
TypeScript
apache-2.0
microsoft/TypeScript,DLehenbauer/TypeScript,weswigham/TypeScript,jeremyepling/TypeScript,kitsonk/TypeScript,erikmcc/TypeScript,mihailik/TypeScript,nycdotnet/TypeScript,kimamula/TypeScript,kpreisser/TypeScript,DLehenbauer/TypeScript,ziacik/TypeScript,synaptek/TypeScript,erikmcc/TypeScript,minestarks/TypeScript,mmoskal/TypeScript,evgrud/TypeScript,fabioparra/TypeScript,blakeembrey/TypeScript,mmoskal/TypeScript,kitsonk/TypeScript,basarat/TypeScript,evgrud/TypeScript,SaschaNaz/TypeScript,donaldpipowitch/TypeScript,basarat/TypeScript,yortus/TypeScript,kpreisser/TypeScript,plantain-00/TypeScript,vilic/TypeScript,yortus/TypeScript,ionux/TypeScript,plantain-00/TypeScript,evgrud/TypeScript,thr0w/Thr0wScript,kimamula/TypeScript,chuckjaz/TypeScript,Eyas/TypeScript,alexeagle/TypeScript,kpreisser/TypeScript,mihailik/TypeScript,samuelhorwitz/typescript,yortus/TypeScript,thr0w/Thr0wScript,jwbay/TypeScript,nycdotnet/TypeScript,DLehenbauer/TypeScript,SaschaNaz/TypeScript,Eyas/TypeScript,jwbay/TypeScript,RyanCavanaugh/TypeScript,erikmcc/TypeScript,jeremyepling/TypeScript,weswigham/TypeScript,vilic/TypeScript,mmoskal/TypeScript,donaldpipowitch/TypeScript,TukekeSoft/TypeScript,alexeagle/TypeScript,mmoskal/TypeScript,vilic/TypeScript,samuelhorwitz/typescript,Eyas/TypeScript,microsoft/TypeScript,RyanCavanaugh/TypeScript,thr0w/Thr0wScript,nojvek/TypeScript,Eyas/TypeScript,nycdotnet/TypeScript,jeremyepling/TypeScript,AbubakerB/TypeScript,kitsonk/TypeScript,nojvek/TypeScript,minestarks/TypeScript,blakeembrey/TypeScript,synaptek/TypeScript,chuckjaz/TypeScript,ziacik/TypeScript,SaschaNaz/TypeScript,synaptek/TypeScript,mihailik/TypeScript,chuckjaz/TypeScript,basarat/TypeScript,DLehenbauer/TypeScript,AbubakerB/TypeScript,minestarks/TypeScript,donaldpipowitch/TypeScript,donaldpipowitch/TypeScript,blakeembrey/TypeScript,TukekeSoft/TypeScript,yortus/TypeScript,alexeagle/TypeScript,ionux/TypeScript,kimamula/TypeScript,samuelhorwitz/typescript,microsoft/TypeScript,AbubakerB/TypeScript,ziacik/TypeScript,TukekeSoft/TypeScript,plantain-00/TypeScript,nycdotnet/TypeScript,mihailik/TypeScript,Microsoft/TypeScript,weswigham/TypeScript,thr0w/Thr0wScript,ionux/TypeScript,kimamula/TypeScript,RyanCavanaugh/TypeScript,fabioparra/TypeScript,vilic/TypeScript,plantain-00/TypeScript,nojvek/TypeScript,samuelhorwitz/typescript,jwbay/TypeScript,Microsoft/TypeScript,ziacik/TypeScript,chuckjaz/TypeScript,nojvek/TypeScript,SaschaNaz/TypeScript,evgrud/TypeScript,erikmcc/TypeScript,synaptek/TypeScript,fabioparra/TypeScript,ionux/TypeScript,fabioparra/TypeScript,basarat/TypeScript,jwbay/TypeScript,blakeembrey/TypeScript,AbubakerB/TypeScript,Microsoft/TypeScript
--- +++ @@ -10,12 +10,7 @@ //// /*0*/ ////} //// -////interface I2 { -//// a(): void; -//// b(): void; -////} -//// -////var imp2: I2 { +////var imp2: I1 { //// a: () => {}, //// /*1*/ ////}
811a44e5fd539d6dd1da83ec807795e9c40d850a
src/app/model/SearchQuery.ts
src/app/model/SearchQuery.ts
/** * Created by user on 4/7/2017. */ export class Rule { condition = 'equal'; field = 'all_fields'; data = ''; data2 = ''; query: SearchQuery = null; } export class SearchQuery { operator = 'AND'; rules: Rule[] = []; constructor() { const rule: Rule = new Rule(); this.rules.push(rule); } public toQueryString(): string { let str = ''; for (let i = 0; i < this.rules.length; i++) { if (i > 0) { str += ' ' + this.operator + ' '; } if (null != this.rules[i].query) { const tmp = this.rules[i].query.toQueryString(); if (tmp !== '') { str += '(' + tmp + ')'; } } else { const rule = this.rules[i]; let strtemp = ''; if (rule.condition === 'range') { strtemp = '["' + rule.data + '" TO "' + (rule.data2 || '') + '"]'; } if (rule.condition === 'equal') { if (rule.data !== '') { strtemp = '"' + rule.data + '"'; } } if (rule.field === 'all_fields') { str += strtemp; } else { str += rule.field + ': ' + strtemp; } } } return str; } }
/** * Created by user on 4/7/2017. */ export class Rule { condition = 'equal'; field = 'all_fields'; data = ''; data2 = ''; query: SearchQuery = null; } export class SearchQuery { operator = 'AND'; rules: Rule[] = []; constructor() { const rule: Rule = new Rule(); this.rules.push(rule); } public toQueryString(): string { let str = ''; for (let i = 0; i < this.rules.length; i++) { if (i > 0) { str += ' ' + this.operator + ' '; } if (null != this.rules[i].query) { const tmp = this.rules[i].query.toQueryString(); if (tmp !== '') { str += '(' + tmp + ')'; } } else { const rule = this.rules[i]; let strtemp = ''; if (rule.condition === 'range') { strtemp = '["' + rule.data + '" TO "' + (rule.data2 || '') + '"]'; } if (rule.condition === 'equal') { if (rule.data !== '') { strtemp = '"' + rule.data + '"'; } } if (rule.field === 'all_fields') { if (strtemp[0] === '"') { strtemp = strtemp.slice(1, strtemp.length - 1); } str += strtemp; } else { str += rule.field + ': ' + strtemp; } } } return str; } }
Fix facet selecting not worked
Fix facet selecting not worked
TypeScript
unknown
BD2K-DDI/ddi-web-app,OmicsDI/ddi-web-app,OmicsDI/ddi-web-app,BD2K-DDI/ddi-web-app,OmicsDI/ddi-web-app
--- +++ @@ -43,6 +43,9 @@ } if (rule.field === 'all_fields') { + if (strtemp[0] === '"') { + strtemp = strtemp.slice(1, strtemp.length - 1); + } str += strtemp; } else { str += rule.field + ': ' + strtemp;
0ad3e930c5bf430b1fc5210b99706e6ab4639041
packages/tux/src/services/editor.ts
packages/tux/src/services/editor.ts
const schema = new Map() export interface Field { field: string, label: string, component: React.ReactElement<any>, props?: Object } export interface Meta { type: string, editorSchema?: Array<Field>, name?: string, } export function registerEditable(type: string, value: Array<Object> | ((editorSchema: Map<string, Field>) => Map<string, Field>)) { schema.set(type, value) } export function getEditorSchema(meta: Meta): Array<Field> { const adapterSchema = meta.editorSchema const userDefinedSchema = schema.get(meta.type) if (adapterSchema && !userDefinedSchema) { return adapterSchema } else if (!adapterSchema && userDefinedSchema) { if (userDefinedSchema instanceof Array) { return userDefinedSchema } // else, if the userDefinedSchema is a function to operate on current schema // we do not have any schema to operate on, so return an empty array } else if (adapterSchema && userDefinedSchema) { if (userDefinedSchema instanceof Array) { // overwrite adapter schema return userDefinedSchema } else if (userDefinedSchema instanceof Function) { // operate on adapter schema with user provided function const schemaAsMap = new Map(adapterSchema.map(field => [field.field, field])) const editedSchema = userDefinedSchema(schemaAsMap) const result = [] for (const field of editedSchema) { result.push(field) } return result } } return [] }
const schema = new Map() export interface Field { field: string, label: string, component: React.ReactElement<any>, props?: Object } export interface Meta { type: string, editorSchema?: Array<Field>, name?: string, } export function registerEditable( type: string, value: Array<Field> | ((editorSchema: Map<string, Field>) => Map<string, Field>) ) { schema.set(type, value) } export function getEditorSchema(meta: Meta): Array<Field> { const adapterSchema = meta.editorSchema const userDefinedSchema = schema.get(meta.type) if (adapterSchema && !userDefinedSchema) { return adapterSchema } else if (!adapterSchema && userDefinedSchema) { if (userDefinedSchema instanceof Array) { return userDefinedSchema } // else, if the userDefinedSchema is a function to operate on current schema // we do not have any schema to operate on, so return an empty array } else if (adapterSchema && userDefinedSchema) { if (userDefinedSchema instanceof Array) { // overwrite adapter schema return userDefinedSchema } else if (userDefinedSchema instanceof Function) { // operate on adapter schema with user provided function const schemaAsMap = new Map(adapterSchema.map(field => [field.field, field])) const editedSchema = userDefinedSchema(schemaAsMap) const result = [] for (const field of editedSchema) { result.push(field) } return result } } return [] }
Change expected type of value in registerEditable
Change expected type of value in registerEditable
TypeScript
mit
aranja/tux,aranja/tux,aranja/tux
--- +++ @@ -13,8 +13,10 @@ name?: string, } -export function registerEditable(type: string, - value: Array<Object> | ((editorSchema: Map<string, Field>) => Map<string, Field>)) { +export function registerEditable( + type: string, + value: Array<Field> | ((editorSchema: Map<string, Field>) => Map<string, Field>) +) { schema.set(type, value) }
143ac55a08c94b524581d4a8cbe0a48d40f834b6
src/providers/sentry-error.ts
src/providers/sentry-error.ts
import { IonicErrorHandler } from 'ionic-angular'; import Raven from 'raven-js'; Raven .config('https://54c01f896cbb4594b75639dfbf59b81e@sentry.io/155883') .install(); // Sentry.io error handling export class SentryErrorHandler extends IonicErrorHandler { handleError(error) { super.handleError(error); try { Raven.captureException(error.originalError || error); Raven.showReportDialog({}); } catch (e) { console.error(e); } } }
import { IonicErrorHandler } from 'ionic-angular'; import Raven from 'raven-js'; // only initialize Sentry.io if on actual device if ((<any>window).cordova) Raven .config('https://54c01f896cbb4594b75639dfbf59b81e@sentry.io/155883') .install(); // Sentry.io error handling export class SentryErrorHandler extends IonicErrorHandler { handleError(error) { super.handleError(error); try { Raven.captureException(error.originalError || error); Raven.showReportDialog({}); } catch (e) { console.error(e); } } }
Disable error logging in dev
Disable error logging in dev
TypeScript
mit
longzheng/mypal-ionic,longzheng/mypal-ionic,longzheng/mypal-ionic
--- +++ @@ -1,9 +1,11 @@ import { IonicErrorHandler } from 'ionic-angular'; import Raven from 'raven-js'; -Raven - .config('https://54c01f896cbb4594b75639dfbf59b81e@sentry.io/155883') - .install(); +// only initialize Sentry.io if on actual device +if ((<any>window).cordova) + Raven + .config('https://54c01f896cbb4594b75639dfbf59b81e@sentry.io/155883') + .install(); // Sentry.io error handling export class SentryErrorHandler extends IonicErrorHandler {
86047a7206c60e7964e7108f7aab758bc485bd5b
tests/cases/fourslash/superInsideInnerClass.ts
tests/cases/fourslash/superInsideInnerClass.ts
/// <reference path="fourslash.ts" /> ////class Base { //// constructor(n: number) { //// } ////} ////class Derived extends Base { //// constructor() { //// class Nested { //// [super(/*1*/)] = 11111 //// } //// } ////} goTo.marker('1'); verify.signatureHelpCountIs(0);
/// <reference path="fourslash.ts" /> ////class Base { //// constructor(n: number) { //// } ////} ////class Derived extends Base { //// constructor() { //// class Nested { //// [super(/*1*/)] = 11111 //// } //// } ////} goTo.marker('1'); verify.signatureHelpCountIs(0);
Switch test encoding from UTF16 to iso-8859
Switch test encoding from UTF16 to iso-8859
TypeScript
apache-2.0
kitsonk/TypeScript,blakeembrey/TypeScript,synaptek/TypeScript,nycdotnet/TypeScript,evgrud/TypeScript,kpreisser/TypeScript,mihailik/TypeScript,nojvek/TypeScript,plantain-00/TypeScript,microsoft/TypeScript,ziacik/TypeScript,RyanCavanaugh/TypeScript,thr0w/Thr0wScript,plantain-00/TypeScript,jwbay/TypeScript,mihailik/TypeScript,vilic/TypeScript,chuckjaz/TypeScript,basarat/TypeScript,weswigham/TypeScript,TukekeSoft/TypeScript,nojvek/TypeScript,evgrud/TypeScript,jwbay/TypeScript,Eyas/TypeScript,minestarks/TypeScript,Eyas/TypeScript,jeremyepling/TypeScript,DLehenbauer/TypeScript,donaldpipowitch/TypeScript,alexeagle/TypeScript,basarat/TypeScript,DLehenbauer/TypeScript,chuckjaz/TypeScript,basarat/TypeScript,Eyas/TypeScript,vilic/TypeScript,synaptek/TypeScript,thr0w/Thr0wScript,samuelhorwitz/typescript,erikmcc/TypeScript,vilic/TypeScript,chuckjaz/TypeScript,DLehenbauer/TypeScript,weswigham/TypeScript,ziacik/TypeScript,kpreisser/TypeScript,RyanCavanaugh/TypeScript,kitsonk/TypeScript,SaschaNaz/TypeScript,basarat/TypeScript,Microsoft/TypeScript,donaldpipowitch/TypeScript,nycdotnet/TypeScript,DLehenbauer/TypeScript,minestarks/TypeScript,nojvek/TypeScript,SaschaNaz/TypeScript,thr0w/Thr0wScript,donaldpipowitch/TypeScript,alexeagle/TypeScript,ziacik/TypeScript,mihailik/TypeScript,jwbay/TypeScript,Microsoft/TypeScript,TukekeSoft/TypeScript,Microsoft/TypeScript,chuckjaz/TypeScript,erikmcc/TypeScript,evgrud/TypeScript,kitsonk/TypeScript,alexeagle/TypeScript,vilic/TypeScript,weswigham/TypeScript,evgrud/TypeScript,TukekeSoft/TypeScript,minestarks/TypeScript,ziacik/TypeScript,SaschaNaz/TypeScript,synaptek/TypeScript,RyanCavanaugh/TypeScript,blakeembrey/TypeScript,blakeembrey/TypeScript,nojvek/TypeScript,jeremyepling/TypeScript,microsoft/TypeScript,synaptek/TypeScript,nycdotnet/TypeScript,mihailik/TypeScript,plantain-00/TypeScript,thr0w/Thr0wScript,Eyas/TypeScript,erikmcc/TypeScript,samuelhorwitz/typescript,nycdotnet/TypeScript,samuelhorwitz/typescript,kpreisser/TypeScript,blakeembrey/TypeScript,microsoft/TypeScript,jwbay/TypeScript,jeremyepling/TypeScript,erikmcc/TypeScript,samuelhorwitz/typescript,SaschaNaz/TypeScript,donaldpipowitch/TypeScript,plantain-00/TypeScript
--- +++ @@ -1,31 +1,15 @@ -/// <reference path="fourslash.ts" /> - -////class Base { - -//// constructor(n: number) { - -//// } - -////} - -////class Derived extends Base { - -//// constructor() { - -//// class Nested { - -//// [super(/*1*/)] = 11111 - -//// } - -//// } - -////} - - - -goTo.marker('1'); - -verify.signatureHelpCountIs(0); - - +/// <reference path="fourslash.ts" /> +////class Base { +//// constructor(n: number) { +//// } +////} +////class Derived extends Base { +//// constructor() { +//// class Nested { +//// [super(/*1*/)] = 11111 +//// } +//// } +////} + +goTo.marker('1'); +verify.signatureHelpCountIs(0);
6569ca62df89085a2a409a9c24281a9c1a854bf5
server/models/user.ts
server/models/user.ts
import { Schema, model, Document } from 'mongoose'; const UserSchema = new Schema({ createTime: { type: Date, default: Date.now }, lastLoginTime: { type: Date, default: Date.now }, username: { type: String, trim: true, unique: true, match: /^([0-9a-zA-Z]{1,2}|[\u4e00-\u9eff]){1,8}$/, index: true, }, salt: String, password: String, avatar: String, tag: { type: String, default: '', trim: true, match: /^([0-9a-zA-Z]{1,2}|[\u4e00-\u9eff]){1,5}$/, }, expressions: [ { type: String, }, ], notificationTokens: [{ type: String }], }); export interface UserDocument extends Document { /** 用户名 */ username: string; /** 密码加密盐 */ salt: string; /** 加密的密码 */ password: string; /** 头像 */ avatar: string; /** 用户标签 */ tag: string; /** 表情收藏 */ expressions: string[]; notificationTokens: string[]; /** 创建时间 */ createTime: Date; /** 最后登录时间 */ lastLoginTime: Date; } /** * User Model * 用户信息 */ const User = model<UserDocument>('User', UserSchema); export default User;
import { Schema, model, Document } from 'mongoose'; const UserSchema = new Schema({ createTime: { type: Date, default: Date.now }, lastLoginTime: { type: Date, default: Date.now }, username: { type: String, trim: true, unique: true, match: /^([0-9a-zA-Z]{1,2}|[\u4e00-\u9eff]){1,8}$/, index: true, }, salt: String, password: String, avatar: String, tag: { type: String, default: '', trim: true, match: /^([0-9a-zA-Z]{1,2}|[\u4e00-\u9eff]){1,5}$/, }, expressions: [ { type: String, }, ], notificationTokens: { type: [{ type: String }], validate: [(arr: Array<string>) => arr.length <= 3, '{PATH} exceeds the limit of 3'], }, }); export interface UserDocument extends Document { /** 用户名 */ username: string; /** 密码加密盐 */ salt: string; /** 加密的密码 */ password: string; /** 头像 */ avatar: string; /** 用户标签 */ tag: string; /** 表情收藏 */ expressions: string[]; notificationTokens: string[]; /** 创建时间 */ createTime: Date; /** 最后登录时间 */ lastLoginTime: Date; } /** * User Model * 用户信息 */ const User = model<UserDocument>('User', UserSchema); export default User;
Store up to 3 notification tokens
Store up to 3 notification tokens
TypeScript
mit
yinxin630/fiora,yinxin630/fiora,yinxin630/fiora
--- +++ @@ -25,7 +25,10 @@ type: String, }, ], - notificationTokens: [{ type: String }], + notificationTokens: { + type: [{ type: String }], + validate: [(arr: Array<string>) => arr.length <= 3, '{PATH} exceeds the limit of 3'], + }, }); export interface UserDocument extends Document {
578be142bb7cc4d3c2886038a40b5a16a17395a6
generators/app/templates/src/index.ts
generators/app/templates/src/index.ts
import 'reflect-metadata'; import { bootstrap } from 'angular2/bootstrap'; <% if (modules === 'webpack') { -%> import './index.<%- css %>'; <% } -%> import { Hello } from './app/hello'; bootstrap(Hello);
///<reference path="../node_modules/angular2/typings/browser.d.ts"/> import 'reflect-metadata'; import { bootstrap } from 'angular2/bootstrap'; <% if (modules === 'webpack') { -%> import './index.<%- css %>'; <% } -%> import { Hello } from './app/hello'; bootstrap(Hello);
Fix angular-beta.6 change that require reference path to typings/browser.d.ts
Fix angular-beta.6 change that require reference path to typings/browser.d.ts
TypeScript
mit
FountainJS/generator-fountain-angular2,FountainJS/generator-fountain-angular2,FountainJS/generator-fountain-angular2
--- +++ @@ -1,3 +1,5 @@ +///<reference path="../node_modules/angular2/typings/browser.d.ts"/> + import 'reflect-metadata'; import { bootstrap } from 'angular2/bootstrap';
8880a9201886c288eb9ef95f96ff5926f97133d8
app/scripts/components/modal/ActionDialog.tsx
app/scripts/components/modal/ActionDialog.tsx
import * as React from 'react'; import { SubmitButton, FormContainer, FieldError } from '@waldur/form-react'; import { CloseDialogButton } from './CloseDialogButton'; import { ModalDialog } from './ModalDialog'; export const ActionDialog = props => ( <ModalDialog title={props.title} footer={ <form onSubmit={props.onSubmit}> <SubmitButton submitting={props.submitting} label={props.submitLabel}/> <CloseDialogButton/> </form> }> <FormContainer submitting={props.submitting}> {props.children} </FormContainer> <FieldError error={props.error}/> </ModalDialog> );
import * as React from 'react'; import { SubmitButton, FormContainer, FieldError } from '@waldur/form-react'; import { CloseDialogButton } from './CloseDialogButton'; import { ModalDialog } from './ModalDialog'; export const ActionDialog = props => ( <form onSubmit={props.onSubmit}> <ModalDialog title={props.title} footer={ <div> <SubmitButton submitting={props.submitting} label={props.submitLabel}/> <CloseDialogButton/> </div> }> <FormContainer submitting={props.submitting}> {props.children} </FormContainer> <FieldError error={props.error}/> </ModalDialog> </form> );
Implement client-side validation for required fields using HTML5
Implement client-side validation for required fields using HTML5 [WAL-1313]
TypeScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -6,17 +6,19 @@ import { ModalDialog } from './ModalDialog'; export const ActionDialog = props => ( - <ModalDialog - title={props.title} - footer={ - <form onSubmit={props.onSubmit}> - <SubmitButton submitting={props.submitting} label={props.submitLabel}/> - <CloseDialogButton/> - </form> - }> - <FormContainer submitting={props.submitting}> - {props.children} - </FormContainer> - <FieldError error={props.error}/> - </ModalDialog> + <form onSubmit={props.onSubmit}> + <ModalDialog + title={props.title} + footer={ + <div> + <SubmitButton submitting={props.submitting} label={props.submitLabel}/> + <CloseDialogButton/> + </div> + }> + <FormContainer submitting={props.submitting}> + {props.children} + </FormContainer> + <FieldError error={props.error}/> + </ModalDialog> + </form> );
a86778ef6ba114ab3b2e4fdfc326e0dd8251bad6
core/connectEditable.ts
core/connectEditable.ts
import * as BaseActions from "actions/BaseEditActions"; import { EditableCallbacks, EditableProps} from "core/EditableProps"; import { connect } from "react-redux"; import {Store} from "stores"; type MappedProps<TProps extends EditableProps<any>> = TProps & EditableProps<TProps["value"]>; type EditableComponentProps = EditableProps<any> & EditableCallbacks<any>; type RequiredProps = {itemId: number}; function mapStateToProps <TProps extends EditableComponentProps>(state: Store, {itemId}: RequiredProps): MappedProps<TProps> { return state.document[itemId] as TProps; }; const mapBaseActionsToProps = { onEdited: (id: number, newValue: any) => (<BaseActions.OnEdited> { itemId : id, type : "onEdited", value : newValue, }), setIsEditing : (id: number, isEditing: boolean) => (<BaseActions.SetIsEditing> { editing : isEditing, itemId : id, type : "setIsEditing", }), }; export default function connectEditable<TProps extends EditableComponentProps>(Component: React.SFC<TProps> | React.ComponentClass<TProps>) { return connect(mapStateToProps, mapBaseActionsToProps)(Component); }
import * as BaseActions from "actions/BaseEditActions"; import { EditableCallbacks, EditableProps} from "core/EditableProps"; import { connect } from "react-redux"; import {Store} from "stores"; type MappedProps<TProps extends EditableProps<any>> = TProps & EditableProps<TProps["value"]>; type EditableComponentProps = EditableProps<any> & EditableCallbacks<any>; type RequiredProps = {itemId: number}; function mapStateToProps <TProps extends EditableComponentProps>(state: Store, {itemId}: RequiredProps): MappedProps<TProps> { return {... state.document[itemId]} as TProps; }; const mapBaseActionsToProps = { onEdited: (id: number, newValue: any) => (<BaseActions.OnEdited> { itemId : id, type : "onEdited", value : newValue, }), setIsEditing : (id: number, isEditing: boolean) => (<BaseActions.SetIsEditing> { editing : isEditing, itemId : id, type : "setIsEditing", }), }; export default function connectEditable<TProps extends EditableComponentProps>(Component: React.SFC<TProps> | React.ComponentClass<TProps>) { return connect(mapStateToProps, mapBaseActionsToProps)(Component); }
Use spread to create a new props object since we have some connected elements nested in nonconnected elements (so sometimes stuff will break if we don't clone the props)
Use spread to create a new props object since we have some connected elements nested in nonconnected elements (so sometimes stuff will break if we don't clone the props)
TypeScript
mit
software-training-for-students/manual-editor,software-training-for-students/manual-editor,software-training-for-students/manual-editor
--- +++ @@ -10,7 +10,7 @@ type RequiredProps = {itemId: number}; function mapStateToProps <TProps extends EditableComponentProps>(state: Store, {itemId}: RequiredProps): MappedProps<TProps> { - return state.document[itemId] as TProps; + return {... state.document[itemId]} as TProps; }; const mapBaseActionsToProps = {
e33fc763ee5106cf9684c161a89ff0e7f16be0fe
src/custom-compiler.ts
src/custom-compiler.ts
// Only for types; take care never to use ts_types in expressions, only in type annotations import * as ts_types from 'typescript'; import { wrapError } from './utils/wrap-error'; import { TsJestConfig } from './types'; /** * Return a typescript compiler. * Allows config to specify alternative compiler. * For example, `ntypescript`. */ export function getTypescriptCompiler(config: TsJestConfig): typeof ts_types { const compilerName = typeof config.compiler === 'string' ? config.compiler : 'typescript'; try { return require(compilerName); } catch (err) { throw wrapError(err, new Error('Could not import typescript compiler "' + compilerName + '"')); } }
// Only for types; take care never to use ts_types in expressions, only in type annotations import * as ts_types from 'typescript'; import { wrapError } from './utils/wrap-error'; import { TsJestConfig } from './types'; /** * Return a typescript compiler. * Allows config to specify alternative compiler. * For example, `ntypescript`. */ export function getTypescriptCompiler(config: TsJestConfig | undefined): typeof ts_types { const compilerName = config && typeof config.compiler === 'string' ? config.compiler : 'typescript'; try { return require(compilerName); } catch (err) { throw wrapError(err, new Error('Could not import typescript compiler "' + compilerName + '"')); } }
Fix bug getting typescript compiler when tsjestconfig is undefined
Fix bug getting typescript compiler when tsjestconfig is undefined
TypeScript
mit
kulshekhar/ts-jest,kulshekhar/ts-jest
--- +++ @@ -8,8 +8,8 @@ * Allows config to specify alternative compiler. * For example, `ntypescript`. */ -export function getTypescriptCompiler(config: TsJestConfig): typeof ts_types { - const compilerName = typeof config.compiler === 'string' ? config.compiler : 'typescript'; +export function getTypescriptCompiler(config: TsJestConfig | undefined): typeof ts_types { + const compilerName = config && typeof config.compiler === 'string' ? config.compiler : 'typescript'; try { return require(compilerName); } catch (err) {
2e2de9e67ad46d1b3ad261d9c83e85f84e9ef9e0
src/ts/models/square.ts
src/ts/models/square.ts
namespace MainApp { /** * Square */ export class Square { constructor() { } } }
/// <reference path="./interfaces/puttable.ts" /> namespace MainApp { /** * Square */ export class Square { constructor(public piece:Puttable = null) { } } }
Add piece property to Square
Add piece property to Square
TypeScript
mit
yajamon/marukake,yajamon/marukake,yajamon/marukake
--- +++ @@ -1,9 +1,11 @@ +/// <reference path="./interfaces/puttable.ts" /> + namespace MainApp { /** * Square */ export class Square { - constructor() { + constructor(public piece:Puttable = null) { } } }
f7b45868cf77ba78fd397c078e89d7f0d279923f
packages/skin-database/api/processUserUploads.ts
packages/skin-database/api/processUserUploads.ts
import * as Skins from "../data/skins"; import S3 from "../s3"; import { addSkinFromBuffer } from "../addSkin"; import { EventHandler } from "./app"; let processing = false; export async function processUserUploads(eventHandler: EventHandler) { // Ensure we only have one worker processing requests. if (processing) { return; } processing = true; let upload = await Skins.getReportedUpload(); while (upload != null) { try { const buffer = await S3.getUploadedSkin(upload.id); const result = await addSkinFromBuffer( buffer, upload.filename, "Web API" ); await Skins.recordUserUploadArchived(upload.id); if (result.status === "ADDED") { const action = { type: result.skinType === "CLASSIC" ? "CLASSIC_SKIN_UPLOADED" : "MODERN_SKIN_UPLOADED", md5: result.md5, } as const; eventHandler(action); } } catch (e) { await Skins.recordUserUploadErrored(upload.id); const action = { type: "SKIN_UPLOAD_ERROR", uploadId: upload.id, message: e.message, } as const; eventHandler(action); console.error(e); } upload = await Skins.getReportedUpload(); } processing = false; }
import * as Skins from "../data/skins"; import S3 from "../s3"; import { addSkinFromBuffer } from "../addSkin"; import { EventHandler } from "./app"; async function* reportedUploads() { const upload = await Skins.getReportedUpload(); if (upload != null) { yield upload; } } let processing = false; export async function processUserUploads(eventHandler: EventHandler) { // Ensure we only have one worker processing requests. if (processing) { return; } processing = true; const uploads = reportedUploads(); for await (const upload of uploads) { try { const buffer = await S3.getUploadedSkin(upload.id); const result = await addSkinFromBuffer( buffer, upload.filename, "Web API" ); await Skins.recordUserUploadArchived(upload.id); if (result.status === "ADDED") { const action = { type: result.skinType === "CLASSIC" ? "CLASSIC_SKIN_UPLOADED" : "MODERN_SKIN_UPLOADED", md5: result.md5, } as const; eventHandler(action); } } catch (e) { await Skins.recordUserUploadErrored(upload.id); const action = { type: "SKIN_UPLOAD_ERROR", uploadId: upload.id, message: e.message, } as const; eventHandler(action); console.error(e); } } processing = false; }
Use async generator for handling uploads
Use async generator for handling uploads
TypeScript
mit
captbaritone/winamp2-js,captbaritone/winamp2-js,captbaritone/winamp2-js
--- +++ @@ -2,6 +2,13 @@ import S3 from "../s3"; import { addSkinFromBuffer } from "../addSkin"; import { EventHandler } from "./app"; + +async function* reportedUploads() { + const upload = await Skins.getReportedUpload(); + if (upload != null) { + yield upload; + } +} let processing = false; @@ -11,8 +18,8 @@ return; } processing = true; - let upload = await Skins.getReportedUpload(); - while (upload != null) { + const uploads = reportedUploads(); + for await (const upload of uploads) { try { const buffer = await S3.getUploadedSkin(upload.id); const result = await addSkinFromBuffer( @@ -41,7 +48,6 @@ eventHandler(action); console.error(e); } - upload = await Skins.getReportedUpload(); } processing = false;
3305a16c89afa0124b32581a5228a159c8a2e6af
src/common/appState.ts
src/common/appState.ts
type AppStateKey = | "transcript" | "userWantsToQuit" | "safeToQuit" | "lastSavedFilepath" | "lastSavedFileName" | "pathToMediaSource" | "currentTime" type AppStateValue = true | false | string | number const appState = new Map() export const setAppState = (key: AppStateKey, value: AppStateValue): void => { appState.set(key, value) } export const getAppState = (key: AppStateKey): AppStateKey => { return appState.get(key) } export const logAppState = (): void => { console.log("App state is", appState) } setAppState("transcript", "") setAppState("userWantsToQuit", false) setAppState("safeToQuit", false) setAppState("lastSavedFilepath", null) setAppState("lastSavedFileName", null) setAppState("pathToMediaSource", null) setAppState("currentTime", 0)
interface AppState { transcript: string userWantsToQuit: boolean safeToQuit: boolean lastSavedFilepath: string lastSavedFileName: string pathToMediaSource: string currentTime: number } const appState: AppState = { transcript: "", userWantsToQuit: false, safeToQuit: false, lastSavedFileName: "", lastSavedFilepath: "", pathToMediaSource: "", currentTime: 0, } export function getAppState<K extends keyof AppState>(key: K): AppState[K] { return appState[key] } export function setAppState<T, K extends keyof AppState, V extends AppState[K]>( key: K, value: V, ): void { appState[key] = value } export const logAppState = (): void => { console.log("App state is", appState) }
Reimplement app state as an interface
Reimplement app state as an interface
TypeScript
agpl-3.0
briandk/transcriptase,briandk/transcriptase
--- +++ @@ -1,32 +1,34 @@ -type AppStateKey = - | "transcript" - | "userWantsToQuit" - | "safeToQuit" - | "lastSavedFilepath" - | "lastSavedFileName" - | "pathToMediaSource" - | "currentTime" - -type AppStateValue = true | false | string | number - -const appState = new Map() - -export const setAppState = (key: AppStateKey, value: AppStateValue): void => { - appState.set(key, value) +interface AppState { + transcript: string + userWantsToQuit: boolean + safeToQuit: boolean + lastSavedFilepath: string + lastSavedFileName: string + pathToMediaSource: string + currentTime: number } -export const getAppState = (key: AppStateKey): AppStateKey => { - return appState.get(key) +const appState: AppState = { + transcript: "", + userWantsToQuit: false, + safeToQuit: false, + lastSavedFileName: "", + lastSavedFilepath: "", + pathToMediaSource: "", + currentTime: 0, +} + +export function getAppState<K extends keyof AppState>(key: K): AppState[K] { + return appState[key] +} + +export function setAppState<T, K extends keyof AppState, V extends AppState[K]>( + key: K, + value: V, +): void { + appState[key] = value } export const logAppState = (): void => { console.log("App state is", appState) } - -setAppState("transcript", "") -setAppState("userWantsToQuit", false) -setAppState("safeToQuit", false) -setAppState("lastSavedFilepath", null) -setAppState("lastSavedFileName", null) -setAppState("pathToMediaSource", null) -setAppState("currentTime", 0)
87ff182c289c60036d5fb87c842aa60d15594560
src/picturepark-sdk-v1-angular/projects/picturepark-sdk-v1-angular/src/tests/share-service.spec.ts
src/picturepark-sdk-v1-angular/projects/picturepark-sdk-v1-angular/src/tests/share-service.spec.ts
import { } from 'jasmine'; import { async, inject } from '@angular/core/testing'; import { configureTest } from './config'; import { ContentService, ShareService, ContentSearchRequest, ShareContent, ShareBasicCreateRequest, OutputAccess } from '../lib/api-services'; describe('ShareService', () => { beforeEach(configureTest); it('should create embed share', async(inject([ContentService, ShareService], async (contentService: ContentService, shareService: ShareService) => { // arrange const request = new ContentSearchRequest(); request.searchString = 'm'; const response = await contentService.search(request).toPromise(); // act const contents = response.results.map(i => new ShareContent({ contentId: i.id, outputFormatIds: ['Original'] })); const result = await shareService.create( null, new ShareBasicCreateRequest({ name: 'Share', languageCode: 'en', contents: contents, outputAccess: OutputAccess.Full, suppressNotifications: false })).toPromise(); const share = await shareService.get(result.shareId!).toPromise(); // assert expect(result.shareId).not.toBeNull(); expect(share.id).toEqual(result.shareId!); }))); });
import { } from 'jasmine'; import { async, inject } from '@angular/core/testing'; import { configureTest } from './config'; import { ContentService, ShareService, ContentSearchRequest, ShareContent, ShareBasicCreateRequest, OutputAccess } from '../lib/api-services'; describe('ShareService', () => { beforeEach(configureTest); // it('should create embed share', async(inject([ContentService, ShareService], // async (contentService: ContentService, shareService: ShareService) => { // // arrange // const request = new ContentSearchRequest(); // request.searchString = 'm'; // const response = await contentService.search(request).toPromise(); // // act // const contents = response.results.map(i => new ShareContent({ // contentId: i.id, // outputFormatIds: ['Original'] // })); // const result = await shareService.create( null, new ShareBasicCreateRequest({ // name: 'Share', // languageCode: 'en', // contents: contents, // outputAccess: OutputAccess.Full, // suppressNotifications: false // })).toPromise(); // const share = await shareService.get(result.shareId!).toPromise(); // // assert // expect(result.shareId).not.toBeNull(); // expect(share.id).toEqual(result.shareId!); // }))); });
Disable "should create embed share" test
Disable "should create embed share" test
TypeScript
mit
Picturepark/Picturepark.SDK.TypeScript,Picturepark/Picturepark.SDK.TypeScript,Picturepark/Picturepark.SDK.TypeScript
--- +++ @@ -7,32 +7,32 @@ describe('ShareService', () => { beforeEach(configureTest); - it('should create embed share', async(inject([ContentService, ShareService], - async (contentService: ContentService, shareService: ShareService) => { - // arrange - const request = new ContentSearchRequest(); - request.searchString = 'm'; + // it('should create embed share', async(inject([ContentService, ShareService], + // async (contentService: ContentService, shareService: ShareService) => { + // // arrange + // const request = new ContentSearchRequest(); + // request.searchString = 'm'; - const response = await contentService.search(request).toPromise(); + // const response = await contentService.search(request).toPromise(); - // act - const contents = response.results.map(i => new ShareContent({ - contentId: i.id, - outputFormatIds: ['Original'] - })); + // // act + // const contents = response.results.map(i => new ShareContent({ + // contentId: i.id, + // outputFormatIds: ['Original'] + // })); - const result = await shareService.create( null, new ShareBasicCreateRequest({ - name: 'Share', - languageCode: 'en', - contents: contents, - outputAccess: OutputAccess.Full, - suppressNotifications: false - })).toPromise(); + // const result = await shareService.create( null, new ShareBasicCreateRequest({ + // name: 'Share', + // languageCode: 'en', + // contents: contents, + // outputAccess: OutputAccess.Full, + // suppressNotifications: false + // })).toPromise(); - const share = await shareService.get(result.shareId!).toPromise(); + // const share = await shareService.get(result.shareId!).toPromise(); - // assert - expect(result.shareId).not.toBeNull(); - expect(share.id).toEqual(result.shareId!); - }))); + // // assert + // expect(result.shareId).not.toBeNull(); + // expect(share.id).toEqual(result.shareId!); + // }))); });
7c5a17a916d1f52612f695d226a217710bb494da
src/models/platform.ts
src/models/platform.ts
let isLinux = process.platform === 'linux'; let isFreeBSD = process.platform === 'freebsd'; let isOSX = process.platform === 'darwin'; let isSunOS = process.platform === 'sunos'; export { isLinux, isFreeBSD, isOSX, isSunOS }
const isLinux = process.platform === 'linux'; const isFreeBSD = process.platform === 'freebsd'; const isOSX = process.platform === 'darwin'; const isSunOS = process.platform === 'sunos'; export { isLinux, isFreeBSD, isOSX, isSunOS }
Use const instead of let
Use const instead of let
TypeScript
mit
AyaMorisawa/Disskey,AyaMorisawa/Disskey,AyaMorisawa/Disskey
--- +++ @@ -1,6 +1,6 @@ -let isLinux = process.platform === 'linux'; -let isFreeBSD = process.platform === 'freebsd'; -let isOSX = process.platform === 'darwin'; -let isSunOS = process.platform === 'sunos'; +const isLinux = process.platform === 'linux'; +const isFreeBSD = process.platform === 'freebsd'; +const isOSX = process.platform === 'darwin'; +const isSunOS = process.platform === 'sunos'; export { isLinux, isFreeBSD, isOSX, isSunOS }
311f4f875da3d2f98bd11763afd52f06fbf5fa70
src/app/components/videoContainer.tsx
src/app/components/videoContainer.tsx
import React from "react" import { Event, ipcRenderer } from "electron" // import { PlayerOptions, Source } from "video.js" import { VideoPlayer, PlayerOptions } from "./videojs" import { userHasChosenMediaFile } from "../ipcChannelNames" interface PlayerContainerProps {} export class PlayerContainer extends React.Component<PlayerContainerProps, PlayerOptions> { baseOptions: any constructor(props: PlayerContainerProps) { super(props) this.state = { controls: true, autoplay: false, fluid: true, playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2], sources: [{ src: "" }], } } public handleSourceChanges(event: Event, pathToMedia: string) { this.setState({ sources: [{ src: pathToMedia }] } as any) console.log("path to media is ", this.state.sources) } public componentDidMount() { ipcRenderer.on(userHasChosenMediaFile, (event: Event, pathToMedia: string) => { this.handleSourceChanges(event, pathToMedia) }) } public componentWillUnmount() { ipcRenderer.removeListener(userHasChosenMediaFile, this.handleSourceChanges) } render() { return <VideoPlayer {...this.state as any} /> } }
import React from "react" import { Event, ipcRenderer } from "electron" // import { PlayerOptions, Source } from "video.js" // import { VideoPlayer, PlayerOptions } from "./videojs" import { userHasChosenMediaFile } from "../ipcChannelNames" interface PlayerContainerProps {} interface PlayerContainerState { src: string } export class PlayerContainer extends React.Component<{}, PlayerContainerState> { mediaPlayer: HTMLVideoElement constructor(props: PlayerContainerProps) { super(props) this.state = { src: "" } this.togglePlayPause = this.togglePlayPause.bind(this) } public handleSourceChanges(event: Event, pathToMedia: string) { this.setState({ src: pathToMedia }) console.log("path to media is ", this.state.src) } public componentDidMount() { ipcRenderer.on(userHasChosenMediaFile, (event: Event, pathToMedia: string) => { this.handleSourceChanges(event, pathToMedia) }) } public componentWillUnmount() { ipcRenderer.removeListener(userHasChosenMediaFile, this.handleSourceChanges) } public togglePlayPause() { console.log("Play/pause has been toggled. `this` is", this) this.mediaPlayer.paused ? this.mediaPlayer.play() : this.mediaPlayer.pause() } render() { console.log("render was called. `this` is ", this) return ( <video controls={true} onClick={this.togglePlayPause} ref={element => (this.mediaPlayer = element)} src={this.state.src} /> ) } }
Use simple <video> element for player
Use simple <video> element for player Instead of video.js, or react-player, or video-react, or the other things that drove me nuts
TypeScript
agpl-3.0
briandk/transcriptase,briandk/transcriptase
--- +++ @@ -1,26 +1,24 @@ import React from "react" import { Event, ipcRenderer } from "electron" // import { PlayerOptions, Source } from "video.js" -import { VideoPlayer, PlayerOptions } from "./videojs" +// import { VideoPlayer, PlayerOptions } from "./videojs" import { userHasChosenMediaFile } from "../ipcChannelNames" interface PlayerContainerProps {} +interface PlayerContainerState { + src: string +} -export class PlayerContainer extends React.Component<PlayerContainerProps, PlayerOptions> { - baseOptions: any +export class PlayerContainer extends React.Component<{}, PlayerContainerState> { + mediaPlayer: HTMLVideoElement constructor(props: PlayerContainerProps) { super(props) - this.state = { - controls: true, - autoplay: false, - fluid: true, - playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2], - sources: [{ src: "" }], - } + this.state = { src: "" } + this.togglePlayPause = this.togglePlayPause.bind(this) } public handleSourceChanges(event: Event, pathToMedia: string) { - this.setState({ sources: [{ src: pathToMedia }] } as any) - console.log("path to media is ", this.state.sources) + this.setState({ src: pathToMedia }) + console.log("path to media is ", this.state.src) } public componentDidMount() { ipcRenderer.on(userHasChosenMediaFile, (event: Event, pathToMedia: string) => { @@ -30,7 +28,19 @@ public componentWillUnmount() { ipcRenderer.removeListener(userHasChosenMediaFile, this.handleSourceChanges) } + public togglePlayPause() { + console.log("Play/pause has been toggled. `this` is", this) + this.mediaPlayer.paused ? this.mediaPlayer.play() : this.mediaPlayer.pause() + } render() { - return <VideoPlayer {...this.state as any} /> + console.log("render was called. `this` is ", this) + return ( + <video + controls={true} + onClick={this.togglePlayPause} + ref={element => (this.mediaPlayer = element)} + src={this.state.src} + /> + ) } }
493b8500738f3669907de4426ade88f7f3c543a4
src/providers/setting-service.spec.ts
src/providers/setting-service.spec.ts
import { StorageMock } from '../mocks/mocks'; import { Storage } from '@ionic/storage'; import { TestBed, inject, async } from '@angular/core/testing'; import { SettingService } from './setting-service'; describe('Provider: SettingService', () => { beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [], providers: [SettingService, { provide: Storage, useClass: StorageMock }], imports: [] }).compileComponents(); })); it('Should initialize with default values', inject([SettingService], (settingService: SettingService) => { settingService.isShowRestUrlField().subscribe(isShowRestUrlField => expect(isShowRestUrlField).toBe(settingService.isShowRestUrlFieldDefault)); })); it('Settings should bebe written and read from store', async(inject([SettingService, Storage], (settingService: SettingService, storage: Storage) => { storage.set(settingService.restUrlKey, 'abc'); storage.set(settingService.usernameKey, 'def'); storage.set(settingService.isShowRestUrlFieldKey, false); settingService.getRestUrl().subscribe(restUrl => expect(restUrl).toBe('abc')); settingService.getUsername().subscribe(username => expect(username).toBe('def')); settingService.isShowRestUrlField().subscribe(isShowRestUrlField => expect(isShowRestUrlField).toBeFalsy()); }))); });
import { StorageMock } from '../mocks/mocks'; import { Storage } from '@ionic/storage'; import { TestBed, inject, async } from '@angular/core/testing'; import { SettingService } from './setting-service'; describe('Provider: SettingService', () => { beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [], providers: [SettingService, { provide: Storage, useClass: StorageMock }], imports: [] }).compileComponents(); })); it('Should initialize with default values', inject([SettingService], (settingService: SettingService) => { settingService.isShowRestUrlField().subscribe(isShowRestUrlField => expect(isShowRestUrlField).toBe(settingService.isShowRestUrlFieldDefault)); })); it('Settings should be written and read from store', async(inject([SettingService, Storage], (settingService: SettingService, storage: Storage) => { storage.set(settingService.restUrlKey, 'abc'); storage.set(settingService.usernameKey, 'def'); storage.set(settingService.isShowRestUrlFieldKey, false); settingService.getRestUrl().subscribe(restUrl => expect(restUrl).toBe('abc')); settingService.getUsername().subscribe(username => expect(username).toBe('def')); settingService.isShowRestUrlField().subscribe(isShowRestUrlField => expect(isShowRestUrlField).toBeFalsy()); }))); });
Fix type in test description
Fix type in test description
TypeScript
mit
IMSmobile/app,IMSmobile/app,IMSmobile/app,IMSmobile/app
--- +++ @@ -20,7 +20,7 @@ settingService.isShowRestUrlField().subscribe(isShowRestUrlField => expect(isShowRestUrlField).toBe(settingService.isShowRestUrlFieldDefault)); })); - it('Settings should bebe written and read from store', async(inject([SettingService, Storage], (settingService: SettingService, storage: Storage) => { + it('Settings should be written and read from store', async(inject([SettingService, Storage], (settingService: SettingService, storage: Storage) => { storage.set(settingService.restUrlKey, 'abc'); storage.set(settingService.usernameKey, 'def'); storage.set(settingService.isShowRestUrlFieldKey, false);
dd6ddcaa040209b52d0efdae12145701e25bae6b
packages/webcomponentsjs/externs/webcomponents.d.ts
packages/webcomponentsjs/externs/webcomponents.d.ts
/** * @externs * @license * Copyright (c) 2021 The Polymer Project Authors. All rights reserved. This * code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt The complete set of authors may be found * at http://polymer.github.io/AUTHORS.txt The complete set of contributors may * be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by * Google as part of the polymer project is also subject to an additional IP * rights grant found at http://polymer.github.io/PATENTS.txt */ // eslint-disable-next-line no-var declare var WebComponents; interface HTMLTemplateElement { bootstrap(): void; }
/** * @externs * @license * Copyright (c) 2021 The Polymer Project Authors. All rights reserved. This * code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt The complete set of authors may be found * at http://polymer.github.io/AUTHORS.txt The complete set of contributors may * be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by * Google as part of the polymer project is also subject to an additional IP * rights grant found at http://polymer.github.io/PATENTS.txt */ // eslint-disable-next-line no-var declare var WebComponents: {}; interface HTMLTemplateElement { bootstrap(): void; }
Fix implicit any for `WebComponents` global.
Fix implicit any for `WebComponents` global.
TypeScript
bsd-3-clause
webcomponents/polyfills,webcomponents/polyfills,webcomponents/polyfills
--- +++ @@ -11,7 +11,7 @@ */ // eslint-disable-next-line no-var -declare var WebComponents; +declare var WebComponents: {}; interface HTMLTemplateElement { bootstrap(): void;
f798f308f32c1d41e700fd9c9d1144fe0e82c82e
src/Microsoft.AspNet.ReactServices/npm/redux-typed/src/StrongProvide.ts
src/Microsoft.AspNet.ReactServices/npm/redux-typed/src/StrongProvide.ts
import * as React from 'react'; import { connect as nativeConnect, ElementClass } from 'react-redux'; interface ClassDecoratorWithProps<TProps> extends Function { <T extends (typeof ElementClass)>(component: T): T; props: TProps; } export type ReactComponentClass<T, S> = new(props: T) => React.Component<T, S>; export class ComponentBuilder<TOwnProps, TActions, TExternalProps> { constructor(private stateToProps: (appState: any) => TOwnProps, private actionCreators: TActions) { } public withExternalProps<TAddExternalProps>() { return this as any as ComponentBuilder<TOwnProps, TActions, TAddExternalProps>; } public get allProps(): TOwnProps & TActions & TExternalProps { return null; } public connect<TState>(componentClass: ReactComponentClass<TOwnProps & TActions & TExternalProps, TState>): ReactComponentClass<TExternalProps, TState> { return nativeConnect(this.stateToProps, this.actionCreators as any)(componentClass); } } export function provide<TOwnProps, TActions>(stateToProps: (appState: any) => TOwnProps, actionCreators: TActions) { return new ComponentBuilder<TOwnProps, TActions, {}>(stateToProps, actionCreators); }
import * as React from 'react'; import { connect as nativeConnect } from 'react-redux'; export type ReactComponentClass<T, S> = new(props: T) => React.Component<T, S>; export class ComponentBuilder<TOwnProps, TActions, TExternalProps> { constructor(private stateToProps: (appState: any) => TOwnProps, private actionCreators: TActions) { } public withExternalProps<TAddExternalProps>() { return this as any as ComponentBuilder<TOwnProps, TActions, TAddExternalProps>; } public get allProps(): TOwnProps & TActions & TExternalProps { return null; } public connect<TState>(componentClass: ReactComponentClass<TOwnProps & TActions & TExternalProps, TState>): ReactComponentClass<TExternalProps, TState> { return nativeConnect(this.stateToProps, this.actionCreators as any)(componentClass) as any; } } export function provide<TOwnProps, TActions>(stateToProps: (appState: any) => TOwnProps, actionCreators: TActions) { return new ComponentBuilder<TOwnProps, TActions, {}>(stateToProps, actionCreators); }
Update redux-typed to match latest third-party .d.ts files for React and Redux
Update redux-typed to match latest third-party .d.ts files for React and Redux
TypeScript
apache-2.0
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
--- +++ @@ -1,10 +1,5 @@ import * as React from 'react'; -import { connect as nativeConnect, ElementClass } from 'react-redux'; - -interface ClassDecoratorWithProps<TProps> extends Function { - <T extends (typeof ElementClass)>(component: T): T; - props: TProps; -} +import { connect as nativeConnect } from 'react-redux'; export type ReactComponentClass<T, S> = new(props: T) => React.Component<T, S>; export class ComponentBuilder<TOwnProps, TActions, TExternalProps> { @@ -18,7 +13,7 @@ public get allProps(): TOwnProps & TActions & TExternalProps { return null; } public connect<TState>(componentClass: ReactComponentClass<TOwnProps & TActions & TExternalProps, TState>): ReactComponentClass<TExternalProps, TState> { - return nativeConnect(this.stateToProps, this.actionCreators as any)(componentClass); + return nativeConnect(this.stateToProps, this.actionCreators as any)(componentClass) as any; } }
8b79a6410236aef80cb2a941755d2bd89f7122bd
app/services/sync-mediator.ts
app/services/sync-mediator.ts
import {Injectable, Inject} from "@angular/core"; import {Observable} from "rxjs/Observable"; import {Indexeddb} from "../datastore/indexeddb" import {Datastore} from "idai-components-2/idai-components-2"; /** * @author Daniel de Oliveira */ @Injectable() export class SyncMediator { private db:Promise<any>; private observers = []; constructor( private idb:Indexeddb, private datastore:Datastore ){ this.db=idb.db(); this.datastore.documentChangesNotifications().subscribe( document=>{ for (var obs of this.observers) { if (document['synced']!==1) obs.next(document); } }, (err)=>console.log("err in syncmediator",err) ); }; public getUnsyncedDocuments(): Observable<Document> { return Observable.create( observer => { this.db.then(db => { var cursor = db.openCursor("idai-field-object","synced",IDBKeyRange.only(0)); cursor.onsuccess = (event) => { var cursor = event.target.result; if (cursor) { this.datastore.get(cursor.value['resource']['@id']).then( possiblyCachedDocFromDS=>{ observer.next(possiblyCachedDocFromDS); cursor.continue(); }); } else { this.observers.push(observer); } }; cursor.onerror = err => observer.onError(cursor.error); }); }); } }
import {Injectable, Inject} from "@angular/core"; import {Observable} from "rxjs/Observable"; import {Indexeddb} from "../datastore/indexeddb" import {Datastore} from "idai-components-2/idai-components-2"; /** * @author Daniel de Oliveira */ @Injectable() export class SyncMediator { private db:Promise<any>; private observers = []; constructor( private idb:Indexeddb, private datastore:Datastore ){ this.db=idb.db(); this.datastore.documentChangesNotifications().subscribe( document=>{ for (var obs of this.observers) { if (document['synced']!==1) obs.next(document); } }, (err)=>console.log("err in syncmediator",err) ); }; public getUnsyncedDocuments(): Observable<Document> { return Observable.create( observer => { this.db.then(db => { var cursor = db.openCursor("idai-field-object","synced",IDBKeyRange.only(0)); cursor.onsuccess = (event) => { var cursor = event.target.result; if (cursor) { this.datastore.get(cursor.value['resource']['@id']).then( possiblyCachedDocFromDS=>{ observer.next(possiblyCachedDocFromDS); }); cursor.continue(); } else { this.observers.push(observer); } }; cursor.onerror = err => observer.onError(cursor.error); }); }); } }
Fix issue with transaction timing.
Fix issue with transaction timing.
TypeScript
apache-2.0
codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client
--- +++ @@ -39,8 +39,8 @@ this.datastore.get(cursor.value['resource']['@id']).then( possiblyCachedDocFromDS=>{ observer.next(possiblyCachedDocFromDS); - cursor.continue(); }); + cursor.continue(); } else { this.observers.push(observer); }
4333cafc17c702a1290de84f45a06476bf8ef44b
src/app/components/devlog/post/edit/edit-service.ts
src/app/components/devlog/post/edit/edit-service.ts
import { Injectable, Inject } from 'ng-metadata/core'; import { Fireside_Post } from './../../../../../lib/gj-lib-client/components/fireside/post/post-model'; import template from 'html!./edit.html'; @Injectable() export class DevlogPostEdit { constructor( @Inject( '$modal' ) private $modal: any ) { } show( post: Fireside_Post ): ng.IPromise<Fireside_Post> { const modalInstance = this.$modal.open( { template, controller: 'Devlog.Post.EditModalCtrl', controllerAs: '$ctrl', resolve: { // They may load this on the game page without having dash stuff loaded in yet. init: [ '$ocLazyLoad', ( $ocLazyLoad: oc.ILazyLoad ) => $ocLazyLoad.load( '/app/modules/dash.js' ) ], post: () => post, }, } ); return modalInstance.result; } }
import { Injectable, Inject } from 'ng-metadata/core'; import { Fireside_Post } from './../../../../../lib/gj-lib-client/components/fireside/post/post-model'; import template from 'html!./edit.html'; @Injectable() export class DevlogPostEdit { constructor( @Inject( '$modal' ) private $modal: any ) { } show( post: Fireside_Post ): ng.IPromise<Fireside_Post> { const modalInstance = this.$modal.open( { keyboard: false, backdrop: 'static', template, controller: 'Devlog.Post.EditModalCtrl', controllerAs: '$ctrl', resolve: { // They may load this on the game page without having dash stuff loaded in yet. init: [ '$ocLazyLoad', ( $ocLazyLoad: oc.ILazyLoad ) => $ocLazyLoad.load( '/app/modules/dash.js' ) ], post: () => post, }, } ); return modalInstance.result; } }
Make devlog post add/edit more sticky. This way you don't accidentally close it in the middle of writing and composing a post.
Make devlog post add/edit more sticky. This way you don't accidentally close it in the middle of writing and composing a post.
TypeScript
mit
gamejolt/gamejolt,gamejolt/gamejolt,gamejolt/gamejolt,gamejolt/gamejolt
--- +++ @@ -14,6 +14,8 @@ show( post: Fireside_Post ): ng.IPromise<Fireside_Post> { const modalInstance = this.$modal.open( { + keyboard: false, + backdrop: 'static', template, controller: 'Devlog.Post.EditModalCtrl', controllerAs: '$ctrl',
102b34cd4e29bd491f1f6dfb5ad5c8e7eeaed82a
desktop/src/renderer/components/app-document/app-document-pane/app-document-pane-tabs/app-document-pane-tabs.tsx
desktop/src/renderer/components/app-document/app-document-pane/app-document-pane-tabs/app-document-pane-tabs.tsx
import { EntityId } from '@reduxjs/toolkit' import { Component, h, Host, Prop } from '@stencil/core' import { option as O } from 'fp-ts' import { constFalse, pipe } from 'fp-ts/function' import { state } from '../../../../../renderer/store' import { selectPaneViews } from '../../../../../renderer/store/documentPane/documentPaneSelectors' @Component({ tag: 'app-document-pane-tabs', styleUrl: 'app-document-pane-tabs.css', scoped: true, }) export class AppDocumentPaneTabs { @Prop() activeDocument: O.Option<EntityId> @Prop() paneId: EntityId private isActive = (id: EntityId): boolean => { return pipe( this.activeDocument, O.map((activeId) => activeId === id), O.getOrElse(constFalse) ) } render() { return ( <Host> <ul class="documentPaneTabs"> {selectPaneViews(state)(this.paneId).map((docId) => ( <app-document-pane-tab isActive={this.isActive(docId)} viewId={docId} paneId={this.paneId} ></app-document-pane-tab> ))} </ul> </Host> ) } }
import { EntityId } from '@reduxjs/toolkit' import { Component, h, Host, Prop } from '@stencil/core' import { option as O } from 'fp-ts' import { constFalse, pipe } from 'fp-ts/function' import { state } from '../../../../../renderer/store' import { selectPaneViews } from '../../../../../renderer/store/documentPane/documentPaneSelectors' @Component({ tag: 'app-document-pane-tabs', styleUrl: 'app-document-pane-tabs.css', scoped: true, }) export class AppDocumentPaneTabs { @Prop() activeDocument: O.Option<EntityId> @Prop() paneId: EntityId private isActive = (id: EntityId): boolean => { return pipe( this.activeDocument, O.map((activeId) => activeId === id), O.getOrElse(constFalse) ) } render() { return ( <Host> <ul class="documentPaneTabs"> {selectPaneViews(state)(this.paneId).map((docId) => ( <app-document-pane-tab isActive={this.isActive(docId)} viewId={docId} paneId={this.paneId} key={docId} ></app-document-pane-tab> ))} </ul> </Host> ) } }
Add unique keys to tabs for stable identity
chore(Tabs): Add unique keys to tabs for stable identity
TypeScript
apache-2.0
stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila
--- +++ @@ -32,6 +32,7 @@ isActive={this.isActive(docId)} viewId={docId} paneId={this.paneId} + key={docId} ></app-document-pane-tab> ))} </ul>
67f905b1d25acf78a535f95b39a7ed08de5c5886
server/src/redux.store.ts
server/src/redux.store.ts
import { createStore } from 'redux'; import { reducer } from '../../client/src/redux/reducers'; export const store = createStore(reducer);
import { createStore } from 'redux'; import { reducer } from '../../client/src/store/reducers'; export const store = createStore(reducer);
Fix imprt path to reducer
Fix imprt path to reducer
TypeScript
unlicense
forabi/hollowverse,forabi/hollowverse,forabi/hollowverse,forabi/hollowverse
--- +++ @@ -1,4 +1,4 @@ import { createStore } from 'redux'; -import { reducer } from '../../client/src/redux/reducers'; +import { reducer } from '../../client/src/store/reducers'; export const store = createStore(reducer);
127bb42cfcc35adff89d536467f0e5bd091a2f15
Mechanism/AudioPlayer.ts
Mechanism/AudioPlayer.ts
class AudioPlayer { view: HTMLDivElement; private audioElements: HTMLAudioElement[] = []; private freeAudioElements: HTMLAudioElement[] = []; constructor() { this.view = document.createElement("div"); } play(source: string, loop: boolean = false) { let audioElement: HTMLAudioElement; if (!this.freeAudioElements.any()) { this.freeAudioElements = this.audioElements.filter(e => e.paused); } if (!this.freeAudioElements.any()) { audioElement = document.createElement("audio"); this.view.appendChild(audioElement); } else { audioElement = this.freeAudioElements.pop()!; } audioElement.src = source; audioElement.loop = loop; audioElement.play(); } }
class AudioPlayer { view: HTMLDivElement; private audioElements: HTMLAudioElement[] = []; private freeAudioElements: HTMLAudioElement[] = []; constructor() { this.view = document.createElement("div"); } play(source: string, loop: boolean = false) { let audioElement: HTMLAudioElement; if (!this.freeAudioElements.any()) { this.freeAudioElements = this.audioElements.filter(e => e.paused); } if (!this.freeAudioElements.any()) { audioElement = document.createElement("audio"); this.audioElements.push(audioElement); this.view.appendChild(audioElement); } else { audioElement = this.freeAudioElements.pop()!; } audioElement.src = source; audioElement.loop = loop; audioElement.play(); } }
Fix registering new audio elements in audio player.
Fix registering new audio elements in audio player.
TypeScript
apache-2.0
Dia6lo/Mechanism,Dia6lo/Mechanism,Dia6lo/Mechanism
--- +++ @@ -14,6 +14,7 @@ } if (!this.freeAudioElements.any()) { audioElement = document.createElement("audio"); + this.audioElements.push(audioElement); this.view.appendChild(audioElement); } else {
e01da0c83f80f3e9a52649c0e7b4808ab299365c
src/lib/middleware/unsupportedBrowser.ts
src/lib/middleware/unsupportedBrowser.ts
import { parse } from "url" import useragent from "useragent" export const unsupportedBrowserCheck = (req, res, next) => { const ua = useragent.parse(req.headers["user-agent"]) if (!res.locals.sd.BROWSER) { res.locals.sd.BROWSER = ua } if ( isUnsupported(ua, req) && !/\/unsupported-browser|assets|fonts|images/.test(req.path) ) { res.locals.sd.UNSUPPORTED_BROWSER_REDIRECT = getRedirectTo(req) res.redirect("/unsupported-browser") } next() } export const isUnsupported = (ua, req) => { return ( !req.cookies.continue_with_bad_browser && ((ua.family === "IE" && ua.major <= 11) || (ua.family === "Safari" && ua.major <= 10)) ) } export const getRedirectTo = req => { return ( req.body["redirect-to"] || req.query["redirect-to"] || req.query["redirect_uri"] || parse(req.get("Referrer") || "").path || "/" ) }
import { parse } from "url" import useragent from "useragent" export const unsupportedBrowserCheck = (req, res, next) => { const ua = useragent.parse(req.headers["user-agent"]) if (!res.locals.sd.BROWSER) { res.locals.sd.BROWSER = ua } if ( req.path !== "/unsupported-browser" && isUnsupported(ua, req) && !/\/unsupported-browser|assets|fonts|images/.test(req.path) ) { res.locals.sd.UNSUPPORTED_BROWSER_REDIRECT = getRedirectTo(req) return res.redirect("/unsupported-browser") } next() } export const isUnsupported = (ua, req) => { return ( !req.cookies.continue_with_bad_browser && ((ua.family === "IE" && ua.major <= 11) || (ua.family === "Safari" && ua.major <= 10)) ) } export const getRedirectTo = req => { return ( req.body["redirect-to"] || req.query["redirect-to"] || req.query["redirect_uri"] || parse(req.get("Referrer") || "").path || "/" ) }
Add a `return` before redirecting
[Middleware] Add a `return` before redirecting
TypeScript
mit
artsy/force,izakp/force,erikdstock/force,damassi/force,yuki24/force,yuki24/force,anandaroop/force,eessex/force,joeyAghion/force,artsy/force-public,erikdstock/force,erikdstock/force,eessex/force,anandaroop/force,damassi/force,oxaudo/force,erikdstock/force,joeyAghion/force,anandaroop/force,damassi/force,oxaudo/force,izakp/force,eessex/force,izakp/force,joeyAghion/force,artsy/force-public,yuki24/force,oxaudo/force,eessex/force,joeyAghion/force,yuki24/force,artsy/force,artsy/force,izakp/force,artsy/force,damassi/force,oxaudo/force,anandaroop/force
--- +++ @@ -7,11 +7,12 @@ res.locals.sd.BROWSER = ua } if ( + req.path !== "/unsupported-browser" && isUnsupported(ua, req) && !/\/unsupported-browser|assets|fonts|images/.test(req.path) ) { res.locals.sd.UNSUPPORTED_BROWSER_REDIRECT = getRedirectTo(req) - res.redirect("/unsupported-browser") + return res.redirect("/unsupported-browser") } next() }
e49f4b1f74e164078903e07475689aa05903f611
src/app/projects/states/dashboard/directives/student-task-list/create-portfolio-task-list-item/create-portfolio-task-list-item.component.ts
src/app/projects/states/dashboard/directives/student-task-list/create-portfolio-task-list-item/create-portfolio-task-list-item.component.ts
import { Component, Input, Inject } from '@angular/core'; import { taskService } from 'src/app/ajs-upgraded-providers'; import { UIRouter } from '@uirouter/angular'; @Component({ selector: 'create-portfolio-task-list-item', templateUrl: 'create-portfolio-task-list-item.component.html', styleUrls: ['create-portfolio-task-list-item.component.scss'] }) export class CreatePortfolioTaskListItemComponent { @Input() setSelectedTask: any; @Input() project: any; constructor( @Inject(taskService) private ts: any, @Inject(UIRouter) private router: UIRouter ) { } public status(): string { if (this.hasPortfolio()) { return 'complete'; } return 'not_started'; } public statusClass(): string { return this.ts.statusClass(this.status()); } public hasPortfolio(): boolean { return this.project.portfolio_status > 0; } public switchToPortfolioCreation() { this.router.stateService.go('projects/portfolio') } }
import { Component, Input, Inject } from '@angular/core'; import { taskService } from 'src/app/ajs-upgraded-providers'; import { UIRouter } from '@uirouter/angular'; @Component({ selector: 'create-portfolio-task-list-item', templateUrl: 'create-portfolio-task-list-item.component.html', styleUrls: ['create-portfolio-task-list-item.component.scss'] }) export class CreatePortfolioTaskListItemComponent { @Input() setSelectedTask: any; @Input() project: any; constructor( @Inject(taskService) private ts: any, @Inject(UIRouter) private router: UIRouter ) { } public status(): string { return this.project.portfolioTaskStatus() } public statusClass(): string { return this.project.portfolioTaskStatusClass() } public switchToPortfolioCreation() { this.router.stateService.go('projects/portfolio') } }
Use portfolio task status in create portfolio list item
FIX: Use portfolio task status in create portfolio list item
TypeScript
agpl-3.0
doubtfire-lms/doubtfire-web,doubtfire-lms/doubtfire-web,doubtfire-lms/doubtfire-web,doubtfire-lms/doubtfire-web
--- +++ @@ -18,18 +18,11 @@ } public status(): string { - if (this.hasPortfolio()) { - return 'complete'; - } - return 'not_started'; + return this.project.portfolioTaskStatus() } public statusClass(): string { - return this.ts.statusClass(this.status()); - } - - public hasPortfolio(): boolean { - return this.project.portfolio_status > 0; + return this.project.portfolioTaskStatusClass() } public switchToPortfolioCreation() {
cfdd4d3496b96711bc9fa2600213a9dd244875a2
js-md5/index.d.ts
js-md5/index.d.ts
// Type definitions for js-md5 v0.4 // Project: https://github.com/emn178/js-md5 // Definitions by: Michael McCarthy <https://github.com/mwmccarthy> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/ declare namespace md5 { type message = string | any[] | Uint8Array | ArrayBuffer; interface Md5 { array: () => number[]; arrayBuffer: () => ArrayBuffer; buffer: () => ArrayBuffer; digest: () => number[]; finalize: () => void; hex: () => string; toString: () => string; update: (message: message) => Md5; } interface md5 { (message: message): string; hex: (message: message) => string; array: (message: message) => number[]; digest: (message: message) => number[]; arrayBuffer: (message: message) => ArrayBuffer; buffer: (message: message) => ArrayBuffer; create: () => Md5; update: (message: message) => Md5; } } declare const md5: md5.md5; export = md5;
// Type definitions for js-md5 0.4 // Project: https://github.com/emn178/js-md5 // Definitions by: Michael McCarthy <https://github.com/mwmccarthy> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/ declare namespace md5 { type message = string | any[] | Uint8Array | ArrayBuffer; interface Md5 { array: () => number[]; arrayBuffer: () => ArrayBuffer; buffer: () => ArrayBuffer; digest: () => number[]; finalize: () => void; hex: () => string; toString: () => string; update: (message: message) => Md5; } interface md5 { (message: message): string; hex: (message: message) => string; array: (message: message) => number[]; digest: (message: message) => number[]; arrayBuffer: (message: message) => ArrayBuffer; buffer: (message: message) => ArrayBuffer; create: () => Md5; update: (message: message) => Md5; } } declare const md5: md5.md5; export = md5;
Remove v from version number
Remove v from version number
TypeScript
mit
magny/DefinitelyTyped,minodisk/DefinitelyTyped,georgemarshall/DefinitelyTyped,QuatroCode/DefinitelyTyped,mcrawshaw/DefinitelyTyped,borisyankov/DefinitelyTyped,jimthedev/DefinitelyTyped,dsebastien/DefinitelyTyped,minodisk/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,amir-arad/DefinitelyTyped,ashwinr/DefinitelyTyped,AgentME/DefinitelyTyped,borisyankov/DefinitelyTyped,isman-usoh/DefinitelyTyped,aciccarello/DefinitelyTyped,chrootsu/DefinitelyTyped,zuzusik/DefinitelyTyped,abbasmhd/DefinitelyTyped,markogresak/DefinitelyTyped,isman-usoh/DefinitelyTyped,jimthedev/DefinitelyTyped,zuzusik/DefinitelyTyped,smrq/DefinitelyTyped,zuzusik/DefinitelyTyped,AgentME/DefinitelyTyped,smrq/DefinitelyTyped,georgemarshall/DefinitelyTyped,one-pieces/DefinitelyTyped,abbasmhd/DefinitelyTyped,arusakov/DefinitelyTyped,rolandzwaga/DefinitelyTyped,benishouga/DefinitelyTyped,aciccarello/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,AgentME/DefinitelyTyped,chrootsu/DefinitelyTyped,johan-gorter/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,magny/DefinitelyTyped,georgemarshall/DefinitelyTyped,YousefED/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,arusakov/DefinitelyTyped,alexdresko/DefinitelyTyped,mcrawshaw/DefinitelyTyped,benishouga/DefinitelyTyped,ashwinr/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,YousefED/DefinitelyTyped,arusakov/DefinitelyTyped,benliddicott/DefinitelyTyped,AgentME/DefinitelyTyped,nycdotnet/DefinitelyTyped,mcliment/DefinitelyTyped,johan-gorter/DefinitelyTyped,georgemarshall/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,benishouga/DefinitelyTyped,aciccarello/DefinitelyTyped,rolandzwaga/DefinitelyTyped,progre/DefinitelyTyped,nycdotnet/DefinitelyTyped,jimthedev/DefinitelyTyped,progre/DefinitelyTyped,QuatroCode/DefinitelyTyped,dsebastien/DefinitelyTyped,alexdresko/DefinitelyTyped
--- +++ @@ -1,4 +1,4 @@ -// Type definitions for js-md5 v0.4 +// Type definitions for js-md5 0.4 // Project: https://github.com/emn178/js-md5 // Definitions by: Michael McCarthy <https://github.com/mwmccarthy> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/
fc454bd61533875e50cd9e3abea347d391216b33
src/main/index.ts
src/main/index.ts
import { ipcMain, app, Menu, session } from 'electron'; import { resolve } from 'path'; import { platform, homedir } from 'os'; import { AppWindow } from './app-window'; ipcMain.setMaxListeners(0); app.setPath('userData', resolve(homedir(), '.wexond')); export const appWindow = new AppWindow(); session.defaultSession.setPermissionRequestHandler( (webContents, permission, callback) => { if (permission === 'notifications' || permission === 'fullscreen') { callback(true); } else { callback(false); } }, ); app.on('ready', () => { // Create our menu entries so that we can use macOS shortcuts Menu.setApplicationMenu( Menu.buildFromTemplate([ { label: 'Edit', submenu: [ { role: 'undo' }, { role: 'redo' }, { type: 'separator' }, { role: 'cut' }, { role: 'copy' }, { role: 'paste' }, { role: 'pasteandmatchstyle' }, { role: 'delete' }, { role: 'selectall' }, { role: 'quit' }, ], }, ]), ); appWindow.createWindow(); }); app.on('window-all-closed', () => { if (platform() !== 'darwin') { app.quit(); } });
import { ipcMain, app, Menu, session } from 'electron'; import { resolve } from 'path'; import { platform, homedir } from 'os'; import { AppWindow } from './app-window'; ipcMain.setMaxListeners(0); app.setPath('userData', resolve(homedir(), '.wexond')); export const appWindow = new AppWindow(); app.on('ready', () => { // Create our menu entries so that we can use macOS shortcuts Menu.setApplicationMenu( Menu.buildFromTemplate([ { label: 'Edit', submenu: [ { role: 'undo' }, { role: 'redo' }, { type: 'separator' }, { role: 'cut' }, { role: 'copy' }, { role: 'paste' }, { role: 'pasteandmatchstyle' }, { role: 'delete' }, { role: 'selectall' }, { role: 'quit' }, ], }, ]), ); session.defaultSession.setPermissionRequestHandler( (webContents, permission, callback) => { if (permission === 'notifications' || permission === 'fullscreen') { callback(true); } else { callback(false); } }, ); appWindow.createWindow(); }); app.on('window-all-closed', () => { if (platform() !== 'darwin') { app.quit(); } });
Use setPermissionRequestHandler when app is ready to avoid errors
Use setPermissionRequestHandler when app is ready to avoid errors
TypeScript
apache-2.0
Nersent/Wexond,Nersent/Wexond
--- +++ @@ -8,16 +8,6 @@ app.setPath('userData', resolve(homedir(), '.wexond')); export const appWindow = new AppWindow(); - -session.defaultSession.setPermissionRequestHandler( - (webContents, permission, callback) => { - if (permission === 'notifications' || permission === 'fullscreen') { - callback(true); - } else { - callback(false); - } - }, -); app.on('ready', () => { // Create our menu entries so that we can use macOS shortcuts @@ -41,6 +31,16 @@ ]), ); + session.defaultSession.setPermissionRequestHandler( + (webContents, permission, callback) => { + if (permission === 'notifications' || permission === 'fullscreen') { + callback(true); + } else { + callback(false); + } + }, + ); + appWindow.createWindow(); });
f95cd84fb4bd418d311d9e2c2396a6687a8c0e09
src/util/util.ts
src/util/util.ts
import * as vscode from 'vscode'; import * as os from 'os'; import * as path from 'path'; import { Position } from '../common/motion/position'; import { Range } from '../common/motion/range'; import { logger } from './logger'; const AppDirectory = require('appdirectory'); /** * This is certainly quite janky! The problem we're trying to solve * is that writing editor.selection = new Position() won't immediately * update the position of the cursor. So we have to wait! */ export async function waitForCursorSync( timeout: number = 0, rejectOnTimeout = false ): Promise<void> { await new Promise((resolve, reject) => { let timer = setTimeout(rejectOnTimeout ? reject : resolve, timeout); const disposable = vscode.window.onDidChangeTextEditorSelection(x => { disposable.dispose(); clearTimeout(timer); resolve(); }); }); } export async function getCursorsAfterSync(timeout: number = 0): Promise<Range[]> { try { await waitForCursorSync(timeout, true); } catch (e) { logger.warn(`getCursorsAfterSync: selection not updated within ${timeout}ms. error=${e}.`); } return vscode.window.activeTextEditor!.selections.map( x => new Range(Position.FromVSCodePosition(x.start), Position.FromVSCodePosition(x.end)) ); } export function getExtensionDirPath(): string { const dirs = new AppDirectory('VSCodeVim'); return dirs.userCache(); }
import * as vscode from 'vscode'; import * as os from 'os'; import * as path from 'path'; import { Position } from '../common/motion/position'; import { Range } from '../common/motion/range'; import { logger } from './logger'; const AppDirectory = require('appdirectory'); /** * This is certainly quite janky! The problem we're trying to solve * is that writing editor.selection = new Position() won't immediately * update the position of the cursor. So we have to wait! */ export async function waitForCursorSync( timeout: number = 0, rejectOnTimeout = false ): Promise<void> { await new Promise((resolve, reject) => { let timer = setTimeout(rejectOnTimeout ? reject : resolve, timeout); const disposable = vscode.window.onDidChangeTextEditorSelection(x => { disposable.dispose(); clearTimeout(timer); resolve(); }); }); } export async function getCursorsAfterSync(timeout: number = 0): Promise<Range[]> { try { await waitForCursorSync(timeout, true); } catch (e) { logger.warn(`getCursorsAfterSync: selection not updated within ${timeout}ms. error=${e}.`); } return vscode.window.activeTextEditor!.selections.map( x => new Range(Position.FromVSCodePosition(x.start), Position.FromVSCodePosition(x.end)) ); } export function getExtensionDirPath(): string { const dirs = new AppDirectory('VSCodeVim'); logger.debug("VSCodeVim Cache Directory: " + dirs.userCache()); return dirs.userCache(); }
Add cache directory to debug logger
Add cache directory to debug logger
TypeScript
mit
VSCodeVim/Vim,VSCodeVim/Vim,Chillee/Vim,Chillee/Vim
--- +++ @@ -41,6 +41,7 @@ export function getExtensionDirPath(): string { const dirs = new AppDirectory('VSCodeVim'); + logger.debug("VSCodeVim Cache Directory: " + dirs.userCache()); return dirs.userCache(); }
9cdfd4d2082198fe2382ab93b069b8f50e0bbd02
src/vdom/connect_descriptor.ts
src/vdom/connect_descriptor.ts
import { Context } from "../common/types"; import { IVNode } from "./ivnode"; export interface SelectorData<T = {}, U = {}> { in: T; out: U; } export interface ConnectDescriptor<T, U, K> { select: (prev: SelectorData<K, U> | null, props: T, context: Context) => SelectorData<K, U>; render: (props: U) => IVNode<any>; }
import { Context } from "../common/types"; import { IVNode } from "./ivnode"; export interface SelectorData<T = {}, U = T> { in: T; out: U; } export interface ConnectDescriptor<T, U, K> { select: (prev: SelectorData<K, U> | null, props: T, context: Context) => SelectorData<K, U>; render: (props: U) => IVNode<any>; }
Make SelectorData out type by default the same as in type
Make SelectorData out type by default the same as in type
TypeScript
mit
ivijs/ivi,ivijs/ivi
--- +++ @@ -1,7 +1,7 @@ import { Context } from "../common/types"; import { IVNode } from "./ivnode"; -export interface SelectorData<T = {}, U = {}> { +export interface SelectorData<T = {}, U = T> { in: T; out: U; }
5d62f75c6dc028cea5bc6ce7cf2aaa2dd99717f1
app/src/lib/notifications/show-notification.ts
app/src/lib/notifications/show-notification.ts
import { focusWindow } from '../../ui/main-process-proxy' import { supportsNotifications } from 'desktop-notifications' import { showNotification as invokeShowNotification } from '../../ui/main-process-proxy' import { notificationCallbacks } from './notification-handler' import { DesktopAliveEvent } from '../stores/alive-store' interface IShowNotificationOptions { title: string body: string userInfo?: DesktopAliveEvent onClick: () => void } /** * Shows a notification with a title, a body, and a function to handle when the * user clicks on the notification. */ export async function showNotification(options: IShowNotificationOptions) { if (!supportsNotifications()) { const notification = new Notification(options.title, { body: options.body, }) notification.onclick = () => { focusWindow() options.onClick() } return } const notificationID = await invokeShowNotification( options.title, options.body, options.userInfo ) if (notificationID !== null) { notificationCallbacks.set(notificationID, options.onClick) } }
import { focusWindow } from '../../ui/main-process-proxy' import { supportsNotifications } from 'desktop-notifications' import { showNotification as invokeShowNotification } from '../../ui/main-process-proxy' import { notificationCallbacks } from './notification-handler' import { DesktopAliveEvent } from '../stores/alive-store' interface IShowNotificationOptions { title: string body: string userInfo?: DesktopAliveEvent onClick: () => void } /** * Shows a notification with a title, a body, and a function to handle when the * user clicks on the notification. */ export async function showNotification(options: IShowNotificationOptions) { // `supportNotifications` checks if `desktop-notifications` is supported by // the current platform. Otherwise, we'll rely on the HTML5 notification API. if (!supportsNotifications()) { const notification = new Notification(options.title, { body: options.body, }) notification.onclick = () => { focusWindow() options.onClick() } return } const notificationID = await invokeShowNotification( options.title, options.body, options.userInfo ) if (notificationID !== null) { notificationCallbacks.set(notificationID, options.onClick) } }
Add comment explaining the use of desktop-notifications vs HTML5 API
Add comment explaining the use of desktop-notifications vs HTML5 API
TypeScript
mit
shiftkey/desktop,desktop/desktop,desktop/desktop,desktop/desktop,shiftkey/desktop,shiftkey/desktop,shiftkey/desktop,desktop/desktop
--- +++ @@ -16,6 +16,8 @@ * user clicks on the notification. */ export async function showNotification(options: IShowNotificationOptions) { + // `supportNotifications` checks if `desktop-notifications` is supported by + // the current platform. Otherwise, we'll rely on the HTML5 notification API. if (!supportsNotifications()) { const notification = new Notification(options.title, { body: options.body,
ebfae5fa03fb4aa1813205120de692ebd03a1293
src/main/js/controller/binding-creators/util.ts
src/main/js/controller/binding-creators/util.ts
import {Constants} from '../../misc/constants'; import {IntervalTicker} from '../../misc/ticker/interval'; import {Ticker} from '../../misc/ticker/ticker'; import {TypeUtil} from '../../misc/type-util'; export function createTicker( document: Document, interval: number | undefined, ): Ticker { const ticker = new IntervalTicker( document, TypeUtil.getOrDefault<number>(interval, Constants.monitorDefaultInterval), ); return ticker; }
import {Constants} from '../../misc/constants'; import {IntervalTicker} from '../../misc/ticker/interval'; import {ManualTicker} from '../../misc/ticker/manual'; import {Ticker} from '../../misc/ticker/ticker'; import {TypeUtil} from '../../misc/type-util'; export function createTicker( document: Document, interval: number | undefined, ): Ticker { return interval === 0 ? new ManualTicker() : new IntervalTicker( document, TypeUtil.getOrDefault<number>( interval, Constants.monitorDefaultInterval, ), ); }
Use ManualTicker for invalid interval
Use ManualTicker for invalid interval
TypeScript
mit
cocopon/tweakpane,cocopon/tweakpane,cocopon/tweakpane
--- +++ @@ -1,5 +1,6 @@ import {Constants} from '../../misc/constants'; import {IntervalTicker} from '../../misc/ticker/interval'; +import {ManualTicker} from '../../misc/ticker/manual'; import {Ticker} from '../../misc/ticker/ticker'; import {TypeUtil} from '../../misc/type-util'; @@ -7,9 +8,13 @@ document: Document, interval: number | undefined, ): Ticker { - const ticker = new IntervalTicker( - document, - TypeUtil.getOrDefault<number>(interval, Constants.monitorDefaultInterval), - ); - return ticker; + return interval === 0 + ? new ManualTicker() + : new IntervalTicker( + document, + TypeUtil.getOrDefault<number>( + interval, + Constants.monitorDefaultInterval, + ), + ); }
bfd820adefd072bcaaab98f7585f93937857bf0f
src/rancher/cluster/create/LonghornWorkerWarning.tsx
src/rancher/cluster/create/LonghornWorkerWarning.tsx
import * as classNames from 'classnames'; import * as React from 'react'; import { useSelector } from 'react-redux'; import { formValueSelector } from 'redux-form'; import { translate } from '@waldur/i18n'; import { FORM_ID } from '@waldur/marketplace/details/constants'; import { NodeRole } from '@waldur/rancher/types'; export const LonghornWorkerWarning = ({ nodeIndex }) => { const roles: Array<NodeRole> = useSelector((state) => formValueSelector(FORM_ID)(state, `attributes.nodes[${nodeIndex}].roles`), ); const longhornSelected = useSelector((state) => formValueSelector(FORM_ID)(state, `attributes.install_longhorn`), ); const flavor = useSelector((state) => formValueSelector(FORM_ID)(state, `attributes.nodes[${nodeIndex}].flavor`), ); if ( !roles.includes('worker') || !flavor || (flavor.cores > 4 && flavor.ram > 4 * 1024) ) { return null; } return ( <p className={classNames('help-block m-b-none', { 'text-danger': longhornSelected, 'text-muted': !longhornSelected, })} > {longhornSelected ? translate( 'The worker node is expected to have at least 4 vCPU and 4 GB RAM to run Longhorn.', ) : translate( 'A minimal expected configuration of worker is 4 vCPU and 4 GB RAM.', )} </p> ); };
import * as classNames from 'classnames'; import * as React from 'react'; import { useSelector } from 'react-redux'; import { formValueSelector } from 'redux-form'; import { translate } from '@waldur/i18n'; import { FORM_ID } from '@waldur/marketplace/details/constants'; import { NodeRole } from '@waldur/rancher/types'; export const LonghornWorkerWarning = ({ nodeIndex }) => { const roles: Array<NodeRole> = useSelector((state) => formValueSelector(FORM_ID)(state, `attributes.nodes[${nodeIndex}].roles`), ); const longhornSelected = useSelector((state) => formValueSelector(FORM_ID)(state, `attributes.install_longhorn`), ); const flavor = useSelector((state) => formValueSelector(FORM_ID)(state, `attributes.nodes[${nodeIndex}].flavor`), ); if ( !roles.includes('worker') || !flavor || (flavor.cores >= 4 && flavor.ram >= 4 * 1024) ) { return null; } return ( <p className={classNames('help-block m-b-none', { 'text-danger': longhornSelected, 'text-muted': !longhornSelected, })} > {longhornSelected ? translate( 'The worker node is expected to have at least 4 vCPU and 4 GB RAM to run Longhorn.', ) : translate( 'A minimal expected configuration of worker is 4 vCPU and 4 GB RAM.', )} </p> ); };
Fix error message for Longhorn
Fix error message for Longhorn [WAL-3321]
TypeScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -20,7 +20,7 @@ if ( !roles.includes('worker') || !flavor || - (flavor.cores > 4 && flavor.ram > 4 * 1024) + (flavor.cores >= 4 && flavor.ram >= 4 * 1024) ) { return null; }
9c3b55622913a47cf4a706516932d1fd4a90d316
src/marketplace/offerings/InternalNameField.tsx
src/marketplace/offerings/InternalNameField.tsx
import * as React from 'react'; import { Field } from 'redux-form'; import { required } from '@waldur/core/validators'; import { translate } from '@waldur/i18n'; import { FormGroupWithError } from './FormGroupWithError'; interface InternalNameFieldProps { name: string; } const INTERNAL_NAME_PATTERN = new RegExp('^[a-zA-Z0-9_]+$'); export const validateInternalName = (value: string) => !value.match(INTERNAL_NAME_PATTERN) ? translate('Please use Latin letters without spaces only.') : undefined; const validators = [required, validateInternalName]; export const InternalNameField = (props: InternalNameFieldProps) => ( <Field name={props.name} validate={validators} parse={(v) => v.replace('.', '')} label={translate('Internal name')} required={true} description={translate( 'Technical name intended for integration and automated reporting. Please use Latin letters without spaces only.', )} component={FormGroupWithError} /> );
import * as React from 'react'; import { Field } from 'redux-form'; import { required } from '@waldur/core/validators'; import { translate } from '@waldur/i18n'; import { FormGroupWithError } from './FormGroupWithError'; interface InternalNameFieldProps { name: string; } const INTERNAL_NAME_PATTERN = new RegExp('^[a-zA-Z0-9_-]+$'); export const validateInternalName = (value: string) => !value.match(INTERNAL_NAME_PATTERN) ? translate('Please use Latin letters without spaces only.') : undefined; const validators = [required, validateInternalName]; export const InternalNameField = (props: InternalNameFieldProps) => ( <Field name={props.name} validate={validators} parse={(v) => v.replace('.', '')} label={translate('Internal name')} required={true} description={translate( 'Technical name intended for integration and automated reporting. Please use Latin letters without spaces only.', )} component={FormGroupWithError} /> );
Allow minus in internal names.
Allow minus in internal names.
TypeScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -10,7 +10,7 @@ name: string; } -const INTERNAL_NAME_PATTERN = new RegExp('^[a-zA-Z0-9_]+$'); +const INTERNAL_NAME_PATTERN = new RegExp('^[a-zA-Z0-9_-]+$'); export const validateInternalName = (value: string) => !value.match(INTERNAL_NAME_PATTERN)
3ebc5bdff5e41d5b38f5a1bcc77556c2f490bca8
src/app/lists/lists-table.component.ts
src/app/lists/lists-table.component.ts
import { Component, Input } from '@angular/core'; import { ListsApi } from '../services'; import { List } from './list'; @Component({ selector: 'lists-table', templateUrl: './lists-table.component.html' }) export class ListsTableComponent { @Input() lists: List[]; rowHighlightColor: string = '#d2f3c7'; constructor(private _listsApi: ListsApi) { this.lists = []; } deleteList(list: List) { this._listsApi.deleteList(list._id).subscribe(); } }
import { Component, Input } from '@angular/core'; import { ListsApi } from '../services'; import { List } from './list'; @Component({ selector: 'lists-table', templateUrl: './lists-table.component.html' }) export class ListsTableComponent { private _lists: List[]; @Input() set lists(lists: List[]) { this._lists = lists; } get lists(): List[] { return this._lists; } rowHighlightColor: string; constructor(private _listsApi: ListsApi) { this._lists = []; //set default value for lists array this.rowHighlightColor = '#d2f3c7'; //color for highlighting table rows (for directive) } deleteList(list: List) { this._listsApi.deleteList(list._id).subscribe(); } }
Use getter and setter for Lists input in ListsTableComponent
Use getter and setter for Lists input in ListsTableComponent
TypeScript
mit
shohrukh92/TaskManagerMEAN,shohrukh92/TaskManagerMEAN,shohrukh92/TaskManagerMEAN
--- +++ @@ -8,11 +8,20 @@ }) export class ListsTableComponent { - @Input() lists: List[]; - rowHighlightColor: string = '#d2f3c7'; + private _lists: List[]; + @Input() + set lists(lists: List[]) { + this._lists = lists; + } + get lists(): List[] { + return this._lists; + } + + rowHighlightColor: string; constructor(private _listsApi: ListsApi) { - this.lists = []; + this._lists = []; //set default value for lists array + this.rowHighlightColor = '#d2f3c7'; //color for highlighting table rows (for directive) } deleteList(list: List) {
e1b67a49111cdb67c6b4a6b2ea15c4d3736e6dbb
src/component/feature/FeatureView2/FeatureMetrics/FeatureMetrics.tsx
src/component/feature/FeatureView2/FeatureMetrics/FeatureMetrics.tsx
import { useParams } from 'react-router'; import useFeature from '../../../../hooks/api/getters/useFeature/useFeature'; import MetricComponent from '../../view/metric-container'; import { useStyles } from './FeatureMetrics.styles'; import { IFeatureViewParams } from '../../../../interfaces/params'; import useUiConfig from '../../../../hooks/api/getters/useUiConfig/useUiConfig'; import ConditionallyRender from '../../../common/ConditionallyRender'; import EnvironmentMetricComponent from '../EnvironmentMetricComponent/EnvironmentMetricComponent'; const FeatureMetrics = () => { const styles = useStyles(); const { projectId, featureId } = useParams<IFeatureViewParams>(); const { feature } = useFeature(projectId, featureId); const { uiConfig } = useUiConfig(); const isEnterprise = uiConfig.flags.E; return ( <div className={styles.container}> <ConditionallyRender condition={isEnterprise} show={<EnvironmentMetricComponent />} elseShow={<MetricComponent featureToggle={feature} />} /> </div> ); }; export default FeatureMetrics;
import { useParams } from 'react-router'; import useFeature from '../../../../hooks/api/getters/useFeature/useFeature'; import MetricComponent from '../../view/metric-container'; import { useStyles } from './FeatureMetrics.styles'; import { IFeatureViewParams } from '../../../../interfaces/params'; import useUiConfig from '../../../../hooks/api/getters/useUiConfig/useUiConfig'; import ConditionallyRender from '../../../common/ConditionallyRender'; import EnvironmentMetricComponent from '../EnvironmentMetricComponent/EnvironmentMetricComponent'; const FeatureMetrics = () => { const styles = useStyles(); const { projectId, featureId } = useParams<IFeatureViewParams>(); const { feature } = useFeature(projectId, featureId); const { uiConfig } = useUiConfig(); const isNewMetricsEnabled = uiConfig.flags.V; return ( <div className={styles.container}> <ConditionallyRender condition={isNewMetricsEnabled} show={<EnvironmentMetricComponent />} elseShow={<MetricComponent featureToggle={feature} />} /> </div> ); }; export default FeatureMetrics;
Use V flag for new metrics component
Use V flag for new metrics component
TypeScript
apache-2.0
Unleash/unleash-frontend,Unleash/unleash-frontend,Unleash/unleash-frontend,Unleash/unleash-frontend
--- +++ @@ -12,11 +12,11 @@ const { projectId, featureId } = useParams<IFeatureViewParams>(); const { feature } = useFeature(projectId, featureId); const { uiConfig } = useUiConfig(); - const isEnterprise = uiConfig.flags.E; + const isNewMetricsEnabled = uiConfig.flags.V; return ( <div className={styles.container}> - <ConditionallyRender condition={isEnterprise} + <ConditionallyRender condition={isNewMetricsEnabled} show={<EnvironmentMetricComponent />} elseShow={<MetricComponent featureToggle={feature} />} />
7dddf950f2cbd5bd968b30a780ba9f7b947bc7ad
src/pages/patientView/mutation/GeneFilterMenu.tsx
src/pages/patientView/mutation/GeneFilterMenu.tsx
import React, { Component } from 'react' import { Radio } from 'react-bootstrap'; import { observer } from 'mobx-react'; export interface IGeneFilterSelection { currentSelection:GeneFilterOption; onOptionChanged?:(currentSelection:GeneFilterOption)=>void; } export enum GeneFilterOption { ANY_SAMPLE = "anySample", ALL_SAMPLES = "allSamples" } @observer export default class GeneFilterMenu extends React.Component<IGeneFilterSelection , {}> { constructor(props:IGeneFilterSelection) { super(props); } private handleOptionChange(e:React.FormEvent<Radio>) { if (this.props.onOptionChanged) { const target = e.target as HTMLInputElement; this.props.onOptionChanged(target.value as GeneFilterOption); } } render() { return ( <React.Fragment> <Radio value={GeneFilterOption.ANY_SAMPLE} checked={this.props.currentSelection === GeneFilterOption.ANY_SAMPLE} onChange={(e:React.FormEvent<Radio>) => this.handleOptionChange(e)} > Genes profiled in any sample </Radio> <Radio value={GeneFilterOption.ALL_SAMPLES} checked={this.props.currentSelection === GeneFilterOption.ALL_SAMPLES} onChange={(e:React.FormEvent<Radio>) => this.handleOptionChange(e)} > Genes profiled in all samples </Radio> </React.Fragment> ) } }
import React, { Component } from 'react' import { Radio } from 'react-bootstrap'; import { observer } from 'mobx-react'; export interface IGeneFilterSelection { currentSelection:GeneFilterOption; onOptionChanged?:(currentSelection:GeneFilterOption)=>void; } export enum GeneFilterOption { ANY_SAMPLE = "anySample", ALL_SAMPLES = "allSamples" } @observer export default class GeneFilterMenu extends React.Component<IGeneFilterSelection , {}> { constructor(props:IGeneFilterSelection) { super(props); } private handleOptionChange(e:React.FormEvent<Radio>) { if (this.props.onOptionChanged) { const target = e.target as HTMLInputElement; this.props.onOptionChanged(target.value as GeneFilterOption); } } render() { return ( <React.Fragment> <div>Different gene panels were used for the samples.</div> <div>Filter mutations for:</div> <Radio value={GeneFilterOption.ANY_SAMPLE} checked={this.props.currentSelection === GeneFilterOption.ANY_SAMPLE} onChange={(e:React.FormEvent<Radio>) => this.handleOptionChange(e)} > Genes profiled in any sample </Radio> <Radio value={GeneFilterOption.ALL_SAMPLES} checked={this.props.currentSelection === GeneFilterOption.ALL_SAMPLES} onChange={(e:React.FormEvent<Radio>) => this.handleOptionChange(e)} > Genes profiled in all samples </Radio> </React.Fragment> ) } }
Update text in gene selection filter menu
Update text in gene selection filter menu Former-commit-id: f36ff9b3548887f39e888be13b5c603c70da3784
TypeScript
agpl-3.0
cBioPortal/cbioportal-frontend,alisman/cbioportal-frontend,alisman/cbioportal-frontend,cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend,alisman/cbioportal-frontend,alisman/cbioportal-frontend,alisman/cbioportal-frontend,cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend,alisman/cbioportal-frontend,cBioPortal/cbioportal-frontend
--- +++ @@ -28,6 +28,8 @@ render() { return ( <React.Fragment> + <div>Different gene panels were used for the samples.</div> + <div>Filter mutations for:</div> <Radio value={GeneFilterOption.ANY_SAMPLE} checked={this.props.currentSelection === GeneFilterOption.ANY_SAMPLE}
61c5ebd6b40f2405cee091550b51411901c51b7c
src/noStringBasedSetImmediateRule.ts
src/noStringBasedSetImmediateRule.ts
import NoStringParameterToFunctionCallWalker = require('./utils/NoStringParameterToFunctionCallWalker'); /** * Implementation of the no-string-parameter-to-function-call rule. */ export class Rule extends Lint.Rules.AbstractRule { public apply(sourceFile : ts.SourceFile): Lint.RuleFailure[] { var languageServiceHost; var documentRegistry = ts.createDocumentRegistry(); languageServiceHost = Lint.createLanguageServiceHost('file.ts', sourceFile.getFullText()); var languageService = ts.createLanguageService(languageServiceHost, documentRegistry); var walker : Lint.RuleWalker = new NoStringParameterToFunctionCallWalker( sourceFile , 'setImmediate', this.getOptions(), languageService ); return this.applyWithWalker(walker); } }
import NoStringParameterToFunctionCallWalker = require('./utils/NoStringParameterToFunctionCallWalker'); /** * Implementation of the no-string-parameter-to-function-call rule. */ export class Rule extends Lint.Rules.AbstractRule { public apply(sourceFile : ts.SourceFile): Lint.RuleFailure[] { var documentRegistry = ts.createDocumentRegistry(); var languageServiceHost = Lint.createLanguageServiceHost('file.ts', sourceFile.getFullText()); var languageService = ts.createLanguageService(languageServiceHost, documentRegistry); var walker : Lint.RuleWalker = new NoStringParameterToFunctionCallWalker( sourceFile , 'setImmediate', this.getOptions(), languageService ); return this.applyWithWalker(walker); } }
Set & declare var on same line
Set & declare var on same line Useful for Visual Studio projects with the "Allow implicit `any` type" disabled. Otherwise Visual Studio complains with the error: `Error TS7005 Variable 'languageServiceHost' implicitly has an 'any' type.`
TypeScript
mit
Microsoft/tslint-microsoft-contrib,Microsoft/tslint-microsoft-contrib
--- +++ @@ -7,9 +7,8 @@ export class Rule extends Lint.Rules.AbstractRule { public apply(sourceFile : ts.SourceFile): Lint.RuleFailure[] { - var languageServiceHost; var documentRegistry = ts.createDocumentRegistry(); - languageServiceHost = Lint.createLanguageServiceHost('file.ts', sourceFile.getFullText()); + var languageServiceHost = Lint.createLanguageServiceHost('file.ts', sourceFile.getFullText()); var languageService = ts.createLanguageService(languageServiceHost, documentRegistry); var walker : Lint.RuleWalker = new NoStringParameterToFunctionCallWalker(
381f9411de12be979f0f43f8cd702805df08d5c7
packages/extension/src/js/components/WinList.tsx
packages/extension/src/js/components/WinList.tsx
import React, { useRef, useEffect } from 'react' import { observer } from 'mobx-react-lite' import Scrollbar from 'libs/Scrollbar' import ReactResizeDetector from 'react-resize-detector' import Loading from './Loading' import { useStore } from './hooks/useStore' import Window from './Window' export default observer(() => { const { windowStore, focusStore: { setContainerRef } } = useStore() const scrollbarRef = useRef(null) const onResize = () => { const { height } = scrollbarRef.current.getBoundingClientRect() windowStore.updateHeight(height) } useEffect(() => setContainerRef(scrollbarRef)) const resizeDetector = ( <ReactResizeDetector handleHeight refreshMode='throttle' refreshOptions={{ leading: true, trailing: true }} refreshRate={500} onResize={onResize} /> ) const { initialLoading, windows, visibleColumn } = windowStore if (initialLoading) { return ( <div ref={scrollbarRef}> <Loading /> {resizeDetector} </div> ) } const width = 100 / Math.min(4, visibleColumn) + '%' const list = windows.map((window) => ( <Window key={window.id} width={width} win={window} /> )) return ( <Scrollbar scrollbarRef={scrollbarRef}> {list} {resizeDetector} </Scrollbar> ) })
import React, { useRef, useEffect } from 'react' import { observer } from 'mobx-react-lite' import Scrollbar from 'libs/Scrollbar' import ReactResizeDetector from 'react-resize-detector' import Loading from './Loading' import { useStore } from './hooks/useStore' import Window from './Window' export default observer(() => { const { windowStore, userStore, focusStore: { setContainerRef } } = useStore() const scrollbarRef = useRef(null) const onResize = () => { const { height } = scrollbarRef.current.getBoundingClientRect() windowStore.updateHeight(height) } useEffect(() => setContainerRef(scrollbarRef)) const resizeDetector = ( <ReactResizeDetector handleHeight refreshMode='throttle' refreshOptions={{ leading: true, trailing: true }} refreshRate={500} onResize={onResize} /> ) const { initialLoading, windows, visibleColumn } = windowStore if (initialLoading) { return ( <div ref={scrollbarRef}> <Loading /> {resizeDetector} </div> ) } const width = visibleColumn <= 4 ? 100 / visibleColumn + '%' : `${userStore.tabWidth}rem` const list = windows.map((window) => ( <Window key={window.id} width={width} win={window} /> )) return ( <Scrollbar scrollbarRef={scrollbarRef}> {list} {resizeDetector} </Scrollbar> ) })
Use tab/window width from user preferences if there are more than 4 columns
fix: Use tab/window width from user preferences if there are more than 4 columns
TypeScript
mit
xcv58/Tab-Manager-v2,xcv58/Tab-Manager-v2,xcv58/Tab-Manager-v2,xcv58/Tab-Manager-v2
--- +++ @@ -9,6 +9,7 @@ export default observer(() => { const { windowStore, + userStore, focusStore: { setContainerRef } } = useStore() const scrollbarRef = useRef(null) @@ -37,7 +38,8 @@ </div> ) } - const width = 100 / Math.min(4, visibleColumn) + '%' + const width = + visibleColumn <= 4 ? 100 / visibleColumn + '%' : `${userStore.tabWidth}rem` const list = windows.map((window) => ( <Window key={window.id} width={width} win={window} /> ))
92b2dbd2264689cde90c338fa1efd1b257ddf3c1
commands/navigation.ts
commands/navigation.ts
import { getCurrentItem, getItem } from './item' import { isWeb } from './device' export function close() { window.location.href = '/interactive-redirect/v5/items/__self__/back' } export function next() { window.location.href = '/interactive-redirect/v5/items/__self__/next' } export function previous() { window.location.href = '/interactive-redirect/v5/items/__self__/previous' } export function openItem(id, bookmark) { getItem(id).then(item => { var params = {} var url = item.url if (isWeb()) { params['returnurl'] = window.location.href } if (bookmark) { params['bookmark'] = bookmark } url += '?' + $.param(params) window.location.href = `${window.location.protocol}//${window.location.host}${url}` }) } export var open = openItem export function openFolder(id) { getItem(id).then(item => { window.location.href = item.url }) } export function goto() { console.error('goto method is now deprecated. Please use openItem going forward.') } export function browse() { console.error('browse method is now deprecated. Please use openItem going forward.') }
import { getCurrentItem, getItem } from './item' import { isWeb } from './device' export function close() { window.location.href = '/interactive-redirect/v5/items/__self__/back' } export function next() { window.location.href = '/interactive-redirect/v5/items/__self__/next' } export function previous() { window.location.href = '/interactive-redirect/v5/items/__self__/previous' } export function openItem(id, bookmark) { getItem(id).then(item => { var params = {} var url = item.url if (isWeb()) { params['returnurl'] = window.location.href } if (bookmark) { params['bookmark'] = bookmark } url += '&' + $.param(params) window.location.href = `${window.location.protocol}//${window.location.host}${url}` }) } export var open = openItem export function openFolder(id) { getItem(id).then(item => { window.location.href = item.url }) } export function goto() { console.error('goto method is now deprecated. Please use openItem going forward.') } export function browse() { console.error('browse method is now deprecated. Please use openItem going forward.') }
Revert "Safer to assume the api simply returns a relative API and no query pa…"
Revert "Safer to assume the api simply returns a relative API and no query pa…"
TypeScript
apache-2.0
Mediafly/mflyCommands
--- +++ @@ -23,7 +23,7 @@ if (bookmark) { params['bookmark'] = bookmark } - url += '?' + $.param(params) + url += '&' + $.param(params) window.location.href = `${window.location.protocol}//${window.location.host}${url}` })
bbe5325ba51231b14fd763a751ee92a540a839f4
app/javascript/packs/application.ts
app/javascript/packs/application.ts
import start from 'retrospring/common'; import initAnswerbox from 'retrospring/features/answerbox/index'; import initInbox from 'retrospring/features/inbox/index'; import initUser from 'retrospring/features/user'; import initSettings from 'retrospring/features/settings/index'; import initLists from 'retrospring/features/lists'; import initQuestionbox from 'retrospring/features/questionbox'; import initQuestion from 'retrospring/features/questionbox'; start(); document.addEventListener('turbolinks:load', initAnswerbox); document.addEventListener('DOMContentLoaded', initInbox); document.addEventListener('DOMContentLoaded', initUser); document.addEventListener('turbolinks:load', initSettings); document.addEventListener('DOMContentLoaded', initLists); document.addEventListener('DOMContentLoaded', initQuestionbox); document.addEventListener('DOMContentLoaded', initQuestion);
import start from 'retrospring/common'; import initAnswerbox from 'retrospring/features/answerbox/index'; import initInbox from 'retrospring/features/inbox/index'; import initUser from 'retrospring/features/user'; import initSettings from 'retrospring/features/settings/index'; import initLists from 'retrospring/features/lists'; import initQuestionbox from 'retrospring/features/questionbox'; import initQuestion from 'retrospring/features/question'; start(); document.addEventListener('turbolinks:load', initAnswerbox); document.addEventListener('DOMContentLoaded', initInbox); document.addEventListener('DOMContentLoaded', initUser); document.addEventListener('turbolinks:load', initSettings); document.addEventListener('DOMContentLoaded', initLists); document.addEventListener('DOMContentLoaded', initQuestionbox); document.addEventListener('DOMContentLoaded', initQuestion);
Use proper import for question functionality
Use proper import for question functionality
TypeScript
agpl-3.0
Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring
--- +++ @@ -5,7 +5,7 @@ import initSettings from 'retrospring/features/settings/index'; import initLists from 'retrospring/features/lists'; import initQuestionbox from 'retrospring/features/questionbox'; -import initQuestion from 'retrospring/features/questionbox'; +import initQuestion from 'retrospring/features/question'; start(); document.addEventListener('turbolinks:load', initAnswerbox);
0f3de201a3464d787dc004cacbad57321c4ac248
game/hud/src/services/session/layoutItems/Crafting.ts
game/hud/src/services/session/layoutItems/Crafting.ts
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * @Author: JB (jb@codecorsair.com) * @Date: 2017-01-24 14:48:27 * @Last Modified by: Mehuge (mehuge@sorcerer.co.uk) * @Last Modified time: 2017-05-08 17:42:27 */ import { LayoutMode, Edge } from '../../../components/HUDDrag'; import Crafting from '../../../widgets/Crafting'; export default { position: { x: { anchor: 5, offset: -200, }, y: { anchor: Edge.TOP, offset: 120, }, size: { width: 600, height: 450, }, scale: 1, opacity: 1, visibility: false, zOrder: 8, layoutMode: LayoutMode.GRID, }, dragOptions: { lockHeight: true, lockWidth: true, }, component: Crafting, props: {}, };
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * @Author: JB (jb@codecorsair.com) * @Date: 2017-01-24 14:48:27 * @Last Modified by: Mehuge (mehuge@sorcerer.co.uk) * @Last Modified time: 2017-06-14 21:03:07 */ import { LayoutMode, Edge } from '../../../components/HUDDrag'; import Crafting from '../../../widgets/Crafting'; export default { position: { x: { anchor: 5, offset: -200, }, y: { anchor: Edge.TOP, offset: 120, }, size: { width: 600, height: 450, }, scale: 1, opacity: 1, visibility: true, zOrder: 8, layoutMode: LayoutMode.GRID, }, dragOptions: { lockHeight: true, lockWidth: true, }, component: Crafting, props: {}, };
Make sure crafting UI is mounted
Make sure crafting UI is mounted
TypeScript
mpl-2.0
Mehuge/Camelot-Unchained,Ajackster/Camelot-Unchained,saddieeiddas/Camelot-Unchained,CUModSquad/Camelot-Unchained,csegames/Camelot-Unchained,saddieeiddas/Camelot-Unchained,Mehuge/Camelot-Unchained,Mehuge/Camelot-Unchained,csegames/Camelot-Unchained,saddieeiddas/Camelot-Unchained,csegames/Camelot-Unchained,CUModSquad/Camelot-Unchained,CUModSquad/Camelot-Unchained,Ajackster/Camelot-Unchained,Ajackster/Camelot-Unchained
--- +++ @@ -6,7 +6,7 @@ * @Author: JB (jb@codecorsair.com) * @Date: 2017-01-24 14:48:27 * @Last Modified by: Mehuge (mehuge@sorcerer.co.uk) - * @Last Modified time: 2017-05-08 17:42:27 + * @Last Modified time: 2017-06-14 21:03:07 */ import { LayoutMode, Edge } from '../../../components/HUDDrag'; import Crafting from '../../../widgets/Crafting'; @@ -27,7 +27,7 @@ }, scale: 1, opacity: 1, - visibility: false, + visibility: true, zOrder: 8, layoutMode: LayoutMode.GRID, },
7947036af93ff73e1dcee8e3c957333fad040bbb
src/server/api/endpoints/messaging/messages/delete.ts
src/server/api/endpoints/messaging/messages/delete.ts
import $ from 'cafy'; import ID, { transform } from '../../../../../misc/cafy-id'; import Message from '../../../../../models/messaging-message'; import define from '../../../define'; import { publishMessagingStream } from '../../../../../stream'; const ms = require('ms'); export const meta = { stability: 'stable', desc: { 'ja-JP': '指定したメッセージを削除します。', 'en-US': 'Delete a message.' }, requireCredential: true, kind: 'messaging-write', limit: { duration: ms('1hour'), max: 300, minInterval: ms('1sec') }, params: { messageId: { validator: $.type(ID), transform: transform, desc: { 'ja-JP': '対象のメッセージのID', 'en-US': 'Target message ID.' } } } }; export default define(meta, (ps, user) => new Promise(async (res, rej) => { const message = await Message.findOne({ _id: ps.messageId, userId: user._id }); if (message === null) { return rej('message not found'); } await Message.remove({ _id: message._id }); publishMessagingStream(message.userId, message.recipientId, 'deleted', message._id); publishMessagingStream(message.recipientId, message.userId, 'deleted', message._id); res(); }));
import $ from 'cafy'; import ID, { transform } from '../../../../../misc/cafy-id'; import Message from '../../../../../models/messaging-message'; import define from '../../../define'; import { publishMessagingStream } from '../../../../../stream'; const ms = require('ms'); export const meta = { stability: 'stable', desc: { 'ja-JP': '指定したメッセージを削除します。', 'en-US': 'Delete a message.' }, requireCredential: true, kind: 'messaging-write', limit: { duration: ms('1hour'), max: 300, minInterval: ms('1sec') }, params: { messageId: { validator: $.type(ID), transform: transform, desc: { 'ja-JP': '対象のメッセージのID', 'en-US': 'Target message ID.' } } } }; export default define(meta, (ps, user) => new Promise(async (res, rej) => { const message = await Message.findOne({ _id: ps.messageId, userId: user._id }); if (message === null) { return rej('message not found'); } await Message.remove({ _id: message._id }); publishMessagingStream(message.userId, message.recipientId, 'deleted', message._id); publishMessagingStream(message.recipientId, message.userId, 'deleted', message._id); res(); }));
Make one import per line
Make one import per line
TypeScript
mit
syuilo/Misskey,syuilo/Misskey
--- +++ @@ -1,5 +1,5 @@ - -import $ from 'cafy'; import ID, { transform } from '../../../../../misc/cafy-id'; +import $ from 'cafy'; +import ID, { transform } from '../../../../../misc/cafy-id'; import Message from '../../../../../models/messaging-message'; import define from '../../../define'; import { publishMessagingStream } from '../../../../../stream';
57db3f2813d8bd480e4ebb577c4ff9213c439cd5
lib/theming/src/utils.ts
lib/theming/src/utils.ts
import { rgba, lighten, darken } from 'polished'; export const mkColor = (color: string) => ({ color }); // Passing arguments that can't be converted to RGB such as linear-gradient // to library polished's functions such as lighten or darken throws the error // that crashes the entire storybook. It needs to be guarded when arguments // of those functions are from user input. const isColorVarChangeable = (color: string) => { return !!color.match(/(gradient|var)/); }; const colorFactory = (type: string) => (color: string) => { if (type === 'darken') { return isColorVarChangeable(color) ? color : rgba(`${darken(1, color)}`, 0.95); } if (type === 'lighten') { return isColorVarChangeable(color) ? color : rgba(`${lighten(1, color)}`, 0.95); } return color; }; export const lightenColor = colorFactory('lighten'); export const darkenColor = colorFactory('darken');
import { rgba, lighten, darken } from 'polished'; export const mkColor = (color: string) => ({ color }); // Passing arguments that can't be converted to RGB such as linear-gradient // to library polished's functions such as lighten or darken throws the error // that crashes the entire storybook. It needs to be guarded when arguments // of those functions are from user input. const isColorVarChangeable = (color: string) => { return !!color.match(/(gradient|var)/); }; const applyPolished = (type: string, color: string) => { if (type === 'darken') { return rgba(`${darken(1, color)}`, 0.95); } if (type === 'lighten') { return rgba(`${lighten(1, color)}`, 0.95); } return color; }; const colorFactory = (type: string) => (color: string) => { if (isColorVarChangeable(color)) { return color; } // Guard anything that is not working with polished. try { return applyPolished(type, color); } catch (error) { return color; } }; export const lightenColor = colorFactory('lighten'); export const darkenColor = colorFactory('darken');
Refactor for better exception handling.
Refactor for better exception handling.
TypeScript
mit
storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook
--- +++ @@ -10,17 +10,30 @@ return !!color.match(/(gradient|var)/); }; -const colorFactory = (type: string) => (color: string) => { +const applyPolished = (type: string, color: string) => { if (type === 'darken') { - return isColorVarChangeable(color) ? color : rgba(`${darken(1, color)}`, 0.95); + return rgba(`${darken(1, color)}`, 0.95); } if (type === 'lighten') { - return isColorVarChangeable(color) ? color : rgba(`${lighten(1, color)}`, 0.95); + return rgba(`${lighten(1, color)}`, 0.95); } return color; }; +const colorFactory = (type: string) => (color: string) => { + if (isColorVarChangeable(color)) { + return color; + } + + // Guard anything that is not working with polished. + try { + return applyPolished(type, color); + } catch (error) { + return color; + } +}; + export const lightenColor = colorFactory('lighten'); export const darkenColor = colorFactory('darken');
be93c5ae669fed8756d3743cfcb0f64e4371b28e
analysis/shaman/src/shadowlands/conduits/TumblingWaves.tsx
analysis/shaman/src/shadowlands/conduits/TumblingWaves.tsx
import SPELLS from 'common/SPELLS'; import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import SpellUsable from 'parser/shared/modules/SpellUsable'; class TumblingWaves extends Analyzer { static dependencies = { spellUsable: SpellUsable, }; protected spellUsable!: SpellUsable; constructor(options: Options) { super(options); this.active = this.selectedCombatant.hasConduitBySpellID(SPELLS.TUMBLING_WAVES_CONDUIT.id); this.addEventListener( Events.applybuff.by(SELECTED_PLAYER).spell(SPELLS.TUMBLING_WAVES_BUFF), this.onApplyBuff, ); } onApplyBuff() { this.spellUsable.endCooldown(SPELLS.PRIMORDIAL_WAVE_CAST.id); } } export default TumblingWaves;
import SPELLS from 'common/SPELLS'; import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import SpellUsable from 'parser/shared/modules/SpellUsable'; class TumblingWaves extends Analyzer { static dependencies = { spellUsable: SpellUsable, }; protected spellUsable!: SpellUsable; constructor(options: Options) { super(options); this.active = this.selectedCombatant.hasConduitBySpellID(SPELLS.TUMBLING_WAVES_CONDUIT.id); this.addEventListener( Events.applybuff.by(SELECTED_PLAYER).spell(SPELLS.TUMBLING_WAVES_BUFF), this.onApplyBuff, ); } onApplyBuff() { if (this.spellUsable.isOnCooldown(SPELLS.PRIMORDIAL_WAVE_CAST.id)) { this.spellUsable.endCooldown(SPELLS.PRIMORDIAL_WAVE_CAST.id); } } } export default TumblingWaves;
Check if CD of Primordial Wave is on CD just in case.
Check if CD of Primordial Wave is on CD just in case.
TypeScript
agpl-3.0
WoWAnalyzer/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,sMteX/WoWAnalyzer,sMteX/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,sMteX/WoWAnalyzer
--- +++ @@ -22,7 +22,9 @@ } onApplyBuff() { - this.spellUsable.endCooldown(SPELLS.PRIMORDIAL_WAVE_CAST.id); + if (this.spellUsable.isOnCooldown(SPELLS.PRIMORDIAL_WAVE_CAST.id)) { + this.spellUsable.endCooldown(SPELLS.PRIMORDIAL_WAVE_CAST.id); + } } }
017aeab9b515ea1f97939e4f96c153bd21656143
app/app.component.ts
app/app.component.ts
import { Component, ViewChild } from '@angular/core'; import { LayerType } from './core/layer'; import { CityMapComponent } from './city-map/city-map.component' @Component({ selector: 'aba-plan', templateUrl: 'app.component.html' }) export class AppComponent { title = "AbaPlan"; @ViewChild(CityMapComponent) mapComponent:CityMapComponent; public tabs: Array<any> = [ { heading: 'Plan OSM', kind : 'osm' }, { heading: 'Plan de quartier', kind : 'square' }, { heading: 'Plan de ville', kind : 'city' } ]; public activeTab: string = this.tabs[1]; public isActive(tab: any) { return tab === this.activeTab; } public onSelect(tab: any) { this.activeTab = tab; if(this.mapComponent) this.mapComponent.setLayerType(tab); } public onMapInstancied(event : any){ this.onSelect(this.activeTab); } ngAfterViewInit() { // Init default tab to first this.onSelect(this.activeTab); } constructor() { } }
import { Component, ViewChild } from '@angular/core'; import { LayerType } from './core/layer'; import { CityMapComponent } from './city-map/city-map.component' @Component({ selector: 'aba-plan', templateUrl: 'app.component.html' }) export class AppComponent { title = "AbaPlan"; @ViewChild(CityMapComponent) mapComponent:CityMapComponent; public tabs: Array<any> = [ { heading: 'Plan OSM', kind : 'osm' }, { heading: 'Plan de quartier', kind : 'square' }, { heading: 'Plan de ville', kind : 'city' } ]; public activeTab: string = this.tabs[0]; public isActive(tab: any) { return tab === this.activeTab; } public onSelect(tab: any) { this.activeTab = tab; if(this.mapComponent) this.mapComponent.setLayerType(tab); } public onMapInstancied(event : any){ this.onSelect(this.activeTab); } ngAfterViewInit() { // Init default tab to first this.onSelect(this.activeTab); } constructor() { } }
Set default tab to first
Set default tab to first
TypeScript
mit
ABAPlan/abaplan-core,ABAPlan/abaplan-core,ABAPlan/abaplan-core
--- +++ @@ -28,7 +28,7 @@ } ]; - public activeTab: string = this.tabs[1]; + public activeTab: string = this.tabs[0]; public isActive(tab: any) { return tab === this.activeTab;
e3f7196e288ff0e738759621c3484d4e62783c3a
packages/components/components/image/RemoteImage.tsx
packages/components/components/image/RemoteImage.tsx
import { DetailedHTMLProps, ImgHTMLAttributes, useState } from 'react'; import { c } from 'ttag'; import { SHOW_IMAGES } from '@proton/shared/lib/constants'; import { isURL } from '@proton/shared/lib/helpers/validators'; import Button from '../button/Button'; import { useMailSettings } from '../../hooks'; export interface Props extends DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement> { src: string; text?: string; } const RemoteImage = ({ src, text = c('Action').t`Load image`, ...rest }: Props) => { const [{ ShowImages } = { ShowImages: SHOW_IMAGES.NONE }, loading] = useMailSettings(); const [showAnyways, setShowAnyways] = useState(!isURL(src)); const handleClick = () => setShowAnyways(true); if ((!loading && ShowImages & SHOW_IMAGES.REMOTE) || showAnyways) { return <img src={src} referrerPolicy="no-referrer" {...rest} />; } return <Button onClick={handleClick}>{text}</Button>; }; export default RemoteImage;
import { DetailedHTMLProps, ImgHTMLAttributes, useEffect, useState } from 'react'; import { c } from 'ttag'; import { SHOW_IMAGES } from '@proton/shared/lib/constants'; import { isURL } from '@proton/shared/lib/helpers/validators'; import { toImage } from '@proton/shared/lib/helpers/image'; import Button from '../button/Button'; import { useMailSettings, useLoading } from '../../hooks'; import { Loader } from '../loader'; export interface Props extends DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement> { src: string; text?: string; } const RemoteImage = ({ src, text = c('Action').t`Load image`, ...rest }: Props) => { const [{ ShowImages } = { ShowImages: SHOW_IMAGES.NONE }, loadingMailSettings] = useMailSettings(); const [loading, withLoading] = useLoading(); const [showAnyways, setShowAnyways] = useState(false); const [image, setImage] = useState<HTMLImageElement>(); useEffect(() => { const load = async () => { if (!isURL(src)) { return; } try { setImage(await toImage(src)); } catch { // return; } }; void withLoading<void>(load()); }, [src]); const handleClick = () => setShowAnyways(true); if (loading || loadingMailSettings) { return <Loader />; } if (!image) { return <img alt={src} />; } if (ShowImages & SHOW_IMAGES.REMOTE || showAnyways) { // eslint-disable-next-line jsx-a11y/alt-text return <img src={image?.src} referrerPolicy="no-referrer" {...rest} />; } return <Button onClick={handleClick}>{text}</Button>; }; export default RemoteImage;
Improve remote image component with loading and broken state
Improve remote image component with loading and broken state MAILWEB-2785
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -1,23 +1,51 @@ -import { DetailedHTMLProps, ImgHTMLAttributes, useState } from 'react'; +import { DetailedHTMLProps, ImgHTMLAttributes, useEffect, useState } from 'react'; import { c } from 'ttag'; import { SHOW_IMAGES } from '@proton/shared/lib/constants'; import { isURL } from '@proton/shared/lib/helpers/validators'; +import { toImage } from '@proton/shared/lib/helpers/image'; import Button from '../button/Button'; -import { useMailSettings } from '../../hooks'; +import { useMailSettings, useLoading } from '../../hooks'; +import { Loader } from '../loader'; export interface Props extends DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement> { src: string; text?: string; } const RemoteImage = ({ src, text = c('Action').t`Load image`, ...rest }: Props) => { - const [{ ShowImages } = { ShowImages: SHOW_IMAGES.NONE }, loading] = useMailSettings(); - const [showAnyways, setShowAnyways] = useState(!isURL(src)); + const [{ ShowImages } = { ShowImages: SHOW_IMAGES.NONE }, loadingMailSettings] = useMailSettings(); + const [loading, withLoading] = useLoading(); + const [showAnyways, setShowAnyways] = useState(false); + const [image, setImage] = useState<HTMLImageElement>(); + + useEffect(() => { + const load = async () => { + if (!isURL(src)) { + return; + } + try { + setImage(await toImage(src)); + } catch { + // return; + } + }; + void withLoading<void>(load()); + }, [src]); const handleClick = () => setShowAnyways(true); - if ((!loading && ShowImages & SHOW_IMAGES.REMOTE) || showAnyways) { - return <img src={src} referrerPolicy="no-referrer" {...rest} />; + if (loading || loadingMailSettings) { + return <Loader />; } + + if (!image) { + return <img alt={src} />; + } + + if (ShowImages & SHOW_IMAGES.REMOTE || showAnyways) { + // eslint-disable-next-line jsx-a11y/alt-text + return <img src={image?.src} referrerPolicy="no-referrer" {...rest} />; + } + return <Button onClick={handleClick}>{text}</Button>; };
66a931a8c12746d74a81442f033c0927016250f9
index.d.ts
index.d.ts
interface PackageMetadata { name: String; version: String; } interface ApiOptions { regions: String[]; } interface ContentOptions { bucket: String; contentDirectory: String; } interface PublishLambdaOptions { bucket: String; } interface StackConfiguration { } interface StackParameters { } interface StageDeploymentOptions { stage: String; functionName: String; deploymentBucketName: String; deploymentKeyName: String; } interface WebsiteDeploymentOptions { cacheControlRegexMap: Object; contentTypeMappingOverride: Object; } declare class AwsArchitect { constructor(packageMetadata: PackageMetadata, apiOptions: ApiOptions, contentOptions: ContentOptions); publishLambdaArtifactPromise(options: PublishLambdaOptions): Promise<Boolean>; validateTemplate(stackTemplate: Object): Promise<Boolean>; deployTemplate(stackTemplate: Object, stackConfiguration: StackConfiguration, parameters: StackParameters): Promise<Boolean>; deployStagePromise(stage: String, lambdaVersion: String): Promise<Boolean>; removeStagePromise(stage: String): Promise<Boolean>; publishAndDeployStagePromise(options: StageDeploymentOptions): Promise<Boolean>; publishWebsite(version: String, options: WebsiteDeploymentOptions): Promise<Boolean>; run(port: Short; logger: Function): Promise<Boolean>; }
interface PackageMetadata { name: String; version: String; } interface ApiOptions { regions: String[]; } interface ContentOptions { bucket: String; contentDirectory: String; } interface PublishLambdaOptions { bucket: String; } interface StackConfiguration { changeSetName: String; stackName: String; } interface StageDeploymentOptions { stage: String; functionName: String; deploymentBucketName: String; deploymentKeyName: String; } interface WebsiteDeploymentOptions { cacheControlRegexMap: Object; contentTypeMappingOverride: Object; } declare class AwsArchitect { constructor(packageMetadata: PackageMetadata, apiOptions: ApiOptions, contentOptions: ContentOptions); publishLambdaArtifactPromise(options: PublishLambdaOptions): Promise<Object>; validateTemplate(stackTemplate: Object): Promise<Object>; deployTemplate(stackTemplate: Object, stackConfiguration: StackConfiguration, parameters: Object): Promise<Object>; deployStagePromise(stage: String, lambdaVersion: String): Promise<Object>; removeStagePromise(stage: String): Promise<Object>; publishAndDeployStagePromise(options: StageDeploymentOptions): Promise<Object>; publishWebsite(version: String, options: WebsiteDeploymentOptions): Promise<Object>; run(port: Number, logger: Function): Promise<Object>; }
Fix return Promises to match type.
Fix return Promises to match type.
TypeScript
bsd-3-clause
wparad/AWS-Architect,wparad/AWS-Architect
--- +++ @@ -17,11 +17,8 @@ } interface StackConfiguration { - -} - -interface StackParameters { - + changeSetName: String; + stackName: String; } interface StageDeploymentOptions { @@ -38,12 +35,12 @@ declare class AwsArchitect { constructor(packageMetadata: PackageMetadata, apiOptions: ApiOptions, contentOptions: ContentOptions); - publishLambdaArtifactPromise(options: PublishLambdaOptions): Promise<Boolean>; - validateTemplate(stackTemplate: Object): Promise<Boolean>; - deployTemplate(stackTemplate: Object, stackConfiguration: StackConfiguration, parameters: StackParameters): Promise<Boolean>; - deployStagePromise(stage: String, lambdaVersion: String): Promise<Boolean>; - removeStagePromise(stage: String): Promise<Boolean>; - publishAndDeployStagePromise(options: StageDeploymentOptions): Promise<Boolean>; - publishWebsite(version: String, options: WebsiteDeploymentOptions): Promise<Boolean>; - run(port: Short; logger: Function): Promise<Boolean>; + publishLambdaArtifactPromise(options: PublishLambdaOptions): Promise<Object>; + validateTemplate(stackTemplate: Object): Promise<Object>; + deployTemplate(stackTemplate: Object, stackConfiguration: StackConfiguration, parameters: Object): Promise<Object>; + deployStagePromise(stage: String, lambdaVersion: String): Promise<Object>; + removeStagePromise(stage: String): Promise<Object>; + publishAndDeployStagePromise(options: StageDeploymentOptions): Promise<Object>; + publishWebsite(version: String, options: WebsiteDeploymentOptions): Promise<Object>; + run(port: Number, logger: Function): Promise<Object>; }
4d1e183269f77be775f9309c3006c4ce607663a3
src/renderer/app/components/BookmarkItem/index.tsx
src/renderer/app/components/BookmarkItem/index.tsx
import React from 'react'; import { StyledBookmarkItem, Icon, Title } from './styles'; import { Bookmark } from '@/interfaces'; import { observer } from 'mobx-react'; import store from '@app/store'; interface Props { item: Bookmark; } @observer export default class BookmarkItem extends React.Component<Props> { public render() { const { title, favicon } = this.props.item; const icon = store.faviconsStore.favicons[favicon]; return ( <StyledBookmarkItem> <Icon style={{ backgroundImage: `url(${icon})`, marginRight: icon == null ? 0 : 8, minWidth: icon == null ? 0 : 16, }} /> <Title>{title}</Title> </StyledBookmarkItem> ); } }
import React from 'react'; import { StyledBookmarkItem, Icon, Title } from './styles'; import { Bookmark } from '@/interfaces'; import { observer } from 'mobx-react'; import store from '@app/store'; interface Props { item: Bookmark; } @observer export default class BookmarkItem extends React.Component<Props> { public onClick = () => { store.pagesStore.getSelected().url = this.props.item.url; }; public render() { const { title, favicon } = this.props.item; const icon = store.faviconsStore.favicons[favicon]; return ( <StyledBookmarkItem onClick={this.onClick}> <Icon style={{ backgroundImage: `url(${icon})`, marginRight: icon == null ? 0 : 8, minWidth: icon == null ? 0 : 16, }} /> <Title>{title}</Title> </StyledBookmarkItem> ); } }
Add onClick handler for bookmark items in bar
Add onClick handler for bookmark items in bar
TypeScript
apache-2.0
Nersent/Wexond,Nersent/Wexond
--- +++ @@ -10,12 +10,16 @@ @observer export default class BookmarkItem extends React.Component<Props> { + public onClick = () => { + store.pagesStore.getSelected().url = this.props.item.url; + }; + public render() { const { title, favicon } = this.props.item; const icon = store.faviconsStore.favicons[favicon]; return ( - <StyledBookmarkItem> + <StyledBookmarkItem onClick={this.onClick}> <Icon style={{ backgroundImage: `url(${icon})`,
703b5d545db8cd53f028da35f42450a13adabdee
lib/theming/src/utils.ts
lib/theming/src/utils.ts
import { rgba, lighten, darken } from 'polished'; export const mkColor = (color: string) => ({ color }); const isLinearGradient = (color: string) => { return typeof color === 'string' && color.includes('linear-gradient'); }; const colorFactory = (type: string) => (color: string) => { if (type === 'darken') { return isLinearGradient(color) ? color : rgba(`${darken(1, color)}`, 0.95); } if (type === 'lighten') { return isLinearGradient(color) ? color : rgba(`${lighten(1, color)}`, 0.95); } return color; }; export const lightenColor = colorFactory('lighten'); export const darkenColor = colorFactory('darken');
import { rgba, lighten, darken } from 'polished'; export const mkColor = (color: string) => ({ color }); // Passing linear-gradient string to library polished's functions such as // lighten or darken throws the error that crashes the entire storybook. // It needs to be guarded when arguments of those functions are from // user input. const isLinearGradient = (color: string) => { return typeof color === 'string' && color.includes('linear-gradient'); }; const colorFactory = (type: string) => (color: string) => { if (type === 'darken') { return isLinearGradient(color) ? color : rgba(`${darken(1, color)}`, 0.95); } if (type === 'lighten') { return isLinearGradient(color) ? color : rgba(`${lighten(1, color)}`, 0.95); } return color; }; export const lightenColor = colorFactory('lighten'); export const darkenColor = colorFactory('darken');
Add comment on guarding linear-gradient
Add comment on guarding linear-gradient
TypeScript
mit
storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook
--- +++ @@ -2,6 +2,10 @@ export const mkColor = (color: string) => ({ color }); +// Passing linear-gradient string to library polished's functions such as +// lighten or darken throws the error that crashes the entire storybook. +// It needs to be guarded when arguments of those functions are from +// user input. const isLinearGradient = (color: string) => { return typeof color === 'string' && color.includes('linear-gradient'); };
c9861ef2d8f76d622c6ea558e9007a746388c2a3
src/main.ts
src/main.ts
import * as rtl from 'rtl-css-js'; export interface JssRTLOptions { enabled?: boolean; opt?: 'in' | 'out'; } export default function jssRTL({ enabled = true, opt = 'out' }: JssRTLOptions = {}) { return { onProcessStyle(style: any, _: any, sheet: any) { if (!enabled) { if (typeof style.flip === 'boolean') { delete style.flip; } return style; } let flip = opt === 'out'; // If it's set to opt-out, then it should flip by default if (typeof sheet.options.flip === 'boolean') { flip = sheet.options.flip; } if (typeof style.flip === 'boolean') { flip = style.flip; delete style.flip; } if (!flip) { return style; } return rtl(style); }, }; }
import * as rtl from 'rtl-css-js'; const convert = rtl['default'] || rtl; export interface JssRTLOptions { enabled?: boolean; opt?: 'in' | 'out'; } export default function jssRTL({ enabled = true, opt = 'out' }: JssRTLOptions = {}) { return { onProcessStyle(style: any, _: any, sheet: any) { if (!enabled) { if (typeof style.flip === 'boolean') { delete style.flip; } return style; } let flip = opt === 'out'; // If it's set to opt-out, then it should flip by default if (typeof sheet.options.flip === 'boolean') { flip = sheet.options.flip; } if (typeof style.flip === 'boolean') { flip = style.flip; delete style.flip; } if (!flip) { return style; } return convert(style); }, }; }
Fix for cases where esm version of rtl-css-js is hit
Fix for cases where esm version of rtl-css-js is hit
TypeScript
mit
alitaheri/jss-rtl
--- +++ @@ -1,4 +1,6 @@ import * as rtl from 'rtl-css-js'; + +const convert = rtl['default'] || rtl; export interface JssRTLOptions { enabled?: boolean; @@ -31,7 +33,7 @@ return style; } - return rtl(style); + return convert(style); }, }; }
12abbe1398420d746bd9f659a4df86fcbbf95799
app/ng-ui-widgets-category/listpicker/creating-listpicker/creating-listpicker.component.ts
app/ng-ui-widgets-category/listpicker/creating-listpicker/creating-listpicker.component.ts
// >> creating-listpicker-code import { Component } from "@angular/core"; import { ListPicker } from "tns-core-modules/ui/list-picker"; let pokemonList = ["Bulbasaur", "Parasect", "Venonat", "Venomoth", "Diglett", "Dugtrio", "Meowth", "Persian", "Psyduck", "Arcanine", "Poliwrath", "Machoke"]; @Component({ moduleId: module.id, templateUrl: "./creating-listpicker.component.html" }) export class CreatingListPickerComponent { public pokemons: Array<string> = []; public picked: string; constructor() { for (let i = 0; i < pokemonList.length; i++) { this.pokemons.push(pokemonList[i]); } } public selectedIndexChanged(args) { let picker = <ListPicker>args.object; this.picked = this.pokemons[picker.selectedIndex]; } } // << creating-listpicker-code
// >> creating-listpicker-code import { Component } from "@angular/core"; import { ListPicker } from "tns-core-modules/ui/list-picker"; let pokemonList = ["Bulbasaur", "Parasect", "Venonat", "Venomoth", "Diglett", "Dugtrio", "Meowth", "Persian", "Psyduck", "Arcanine", "Poliwrath", "Machoke"]; @Component({ moduleId: module.id, templateUrl: "./creating-listpicker.component.html" }) export class CreatingListPickerComponent { public pokemons: Array<string> = []; public picked: string; constructor() { for (let pokemon of pokemonList) { this.pokemons.push(pokemon); } } public selectedIndexChanged(args) { let picker = <ListPicker>args.object; this.picked = this.pokemons[picker.selectedIndex]; } } // << creating-listpicker-code
Change for loop to typescript for of loop
Change for loop to typescript for of loop Change old simple for loop to typescript for of loop The for of loop is more readable and just better for this use case
TypeScript
apache-2.0
NativeScript/nativescript-sdk-examples-ng,NativeScript/nativescript-sdk-examples-ng,NativeScript/nativescript-sdk-examples-ng,NativeScript/nativescript-sdk-examples-ng
--- +++ @@ -15,8 +15,8 @@ public picked: string; constructor() { - for (let i = 0; i < pokemonList.length; i++) { - this.pokemons.push(pokemonList[i]); + for (let pokemon of pokemonList) { + this.pokemons.push(pokemon); } }
afa545c8aa39cda1f8fac9e9a55bdb6d4e906ebc
console/src/app/common/FileOperations/FileOperations.ts
console/src/app/common/FileOperations/FileOperations.ts
import { saveAs } from 'file-saver'; import { FileFormat } from './FileFormat'; export class FileOperations { readonly UNKNOWN_FORMAT: string = "UNKNOWN"; readonly NON_SET_DELIMITER: string = ""; // Note: File types readonly TEXT_FILE_TYPE: string = "text/plain;charset=utf-8"; readonly JSON_FILE_TYPE: string = "application/json;charset=utf-8"; // Defining empty constructor constructor() {} public saveFile(fileName: String, fileType: FileFormat, data: String, lineDelimiter: string = this.NON_SET_DELIMITER) { data = data.toString(); var textFromFileInLines: string[] = data.split(lineDelimiter); let fileTypeTag: string = this.getFileTypeTag(fileType); let binaryFileData = new Blob(textFromFileInLines, { type: fileTypeTag}); saveAs(binaryFileData, `${fileName}.yml`); } private getFileTypeTag(fileType: FileFormat): string { switch (fileType) { case FileFormat.TEXT: return this.TEXT_FILE_TYPE; case FileFormat.JSON: return this.TEXT_FILE_TYPE; } return this.TEXT_FILE_TYPE; } }
import { saveAs } from 'file-saver'; import { FileFormat } from './FileFormat'; export class FileOperations { readonly UNKNOWN_FORMAT: string = "UNKNOWN"; readonly NON_SET_DELIMITER: string = ""; // Note: File types readonly TEXT_FILE_TYPE: string = "text/plain;charset=utf-8"; readonly JSON_FILE_TYPE: string = "application/json;charset=utf-8"; // Defining empty constructor constructor() {} public saveFile(fileName: String, fileType: FileFormat, data: String, lineDelimiter: string = this.NON_SET_DELIMITER) { data = data.toString(); var textFromFileInLines: string[] = data.split(lineDelimiter); let fileTypeTag: string = this.getFileTypeTag(fileType); let binaryFileData = new Blob(textFromFileInLines, { type: fileTypeTag}); saveAs(binaryFileData, `${fileName}.yml`); } private getFileTypeTag(fileType: FileFormat): string { switch (fileType) { case FileFormat.TEXT: return this.TEXT_FILE_TYPE; case FileFormat.JSON: return this.TEXT_FILE_TYPE; } return this.TEXT_FILE_TYPE; } }
Add EOL symbol at the end of the file.
Add EOL symbol at the end of the file.
TypeScript
mit
emc-mongoose/console,emc-mongoose/console,emc-mongoose/console
8159a54eac47c1f40f294e4a89a51c001555a73e
src/definitions/SkillContext.ts
src/definitions/SkillContext.ts
namespace Skill { export class Context { constructor() { } get = (key: string): string | number => { return "a val"; } set = (key: string, val: string | number): boolean => { return true; } } } export = Skill;
import {Callback, Context} from "aws-lambda"; import {AlexaRequestBody} from "./AlexaService"; namespace Skill { export class Context { constructor(request: AlexaRequestBody, event: Context, callback: Callback, _this?: any) { if (_this) { Object.assign(this, _this); } this.request = request; this.event = event; this.callback = callback; } request: AlexaRequestBody; event: Context; callback: Callback; get(prop): any { console.log(`Fetching prop ${prop}, ${prop in this ? "found" : "not found"}.`); return this[prop]; } set(prop, value): boolean { console.log(`Adding prop ${prop}...`); return this[prop] = value; } delete(prop): boolean { console.log(`Deleting prop ${prop}...`); return delete this[prop]; } } } export = Skill;
Add additional params to skill context.
Add additional params to skill context.
TypeScript
agpl-3.0
deegles/cookietime,deegles/cookietime
--- +++ @@ -1,15 +1,39 @@ +import {Callback, Context} from "aws-lambda"; +import {AlexaRequestBody} from "./AlexaService"; + namespace Skill { export class Context { - constructor() { + constructor(request: AlexaRequestBody, event: Context, callback: Callback, _this?: any) { + if (_this) { + Object.assign(this, _this); + } + this.request = request; + this.event = event; + this.callback = callback; } - get = (key: string): string | number => { - return "a val"; + request: AlexaRequestBody; + + event: Context; + + callback: Callback; + + get(prop): any { + console.log(`Fetching prop ${prop}, ${prop in this ? "found" : "not found"}.`); + return this[prop]; } - set = (key: string, val: string | number): boolean => { - return true; + set(prop, value): boolean { + console.log(`Adding prop ${prop}...`); + + return this[prop] = value; + } + + delete(prop): boolean { + console.log(`Deleting prop ${prop}...`); + + return delete this[prop]; } } }
151ebf0e4a30651e9f12b9f6f72a56b6fb3b59aa
src/image-viewer.directive.ts
src/image-viewer.directive.ts
import { App } from 'ionic-angular'; import { ElementRef, HostListener, Directive, Input } from '@angular/core'; import { ImageViewer } from './image-viewer'; @Directive({ selector: '[imageViewer]' }) export class ImageViewerDirective { @Input('imageViewer') src: string; constructor( private _app: App, private _el: ElementRef ) { } @HostListener('click') onClick(): void { let position = this._el.nativeElement.getBoundingClientRect(); let imageViewer = ImageViewer.create({image: this.src || this._el.nativeElement.src, position: position}); this._app.present(imageViewer, {}); } }
import { App } from 'ionic-angular'; import { ElementRef, HostListener, Directive, Input } from '@angular/core'; import { ImageViewer } from './image-viewer'; @Directive({ selector: '[imageViewer]' }) export class ImageViewerDirective { @Input('imageViewer') src: string; constructor( private _app: App, private _el: ElementRef ) { } @HostListener('click', ['$event']) onClick(event: Event): void { event.stopPropagation(); let position = this._el.nativeElement.getBoundingClientRect(); let imageViewer = ImageViewer.create({image: this.src || this._el.nativeElement.src, position: position}); this._app.present(imageViewer, {}); } }
Stop event propagation on `imageViewer`elements
Stop event propagation on `imageViewer`elements A click on an `imageViewer` should not propagate : if you use an image in a list item, you don't want the click to propagate to the item Closes #40
TypeScript
mit
Riron/ionic-img-viewer,Riron/ionic-img-viewer
--- +++ @@ -15,7 +15,9 @@ private _el: ElementRef ) { } - @HostListener('click') onClick(): void { + @HostListener('click', ['$event']) onClick(event: Event): void { + event.stopPropagation(); + let position = this._el.nativeElement.getBoundingClientRect(); let imageViewer = ImageViewer.create({image: this.src || this._el.nativeElement.src, position: position});
5b6d5fad6bdda64a4696c33ff2ecb3f563beb33e
src/app/contact-detail.component.ts
src/app/contact-detail.component.ts
import { Component, Input } from '@angular/core'; import { Contact } from './contact'; @Component({ selector: 'my-contact-detail', template: ` <div *ngIf="selectedContact"> <h2>{{selectedContact.firstName}} details:</h2> <div> <label>id: </label>{{selectedContact.id}} </div> <div> <label>first name: </label> <input [(ngModel)]="selectedContact.firstName" placeholder="first name"> </div> <div> <label>last name: </label> <input value="{{selectedContact.lastName}}" placeholder="last name"> </div> <div> <label>phone: </label> <input value="{{selectedContact.phone}}" placeholder="phone"> </div> </div> ` }) export class ContactDetailComponent { contact: Contact; }
import { Component, Input } from '@angular/core'; import { Contact } from './contact'; @Component({ selector: 'my-contact-detail', template: ` <div *ngIf="selectedContact"> <h2>{{selectedContact.firstName}} details:</h2> <div> <label>id: </label>{{selectedContact.id}} </div> <div> <label>first name: </label> <input [(ngModel)]="selectedContact.firstName" placeholder="first name"> </div> <div> <label>last name: </label> <input value="{{selectedContact.lastName}}" placeholder="last name"> </div> <div> <label>phone: </label> <input value="{{selectedContact.phone}}" placeholder="phone"> </div> </div> ` }) export class ContactDetailComponent { @Input() contact: Contact; }
Declare 'contact' as an input
refactor: Declare 'contact' as an input [ticket: #2]
TypeScript
mit
armin-es/contact-list-angular-2,armin-es/contact-list-angular-2,armin-es/contact-list-angular-2
--- +++ @@ -28,5 +28,6 @@ }) export class ContactDetailComponent { + @Input() contact: Contact; }
e6e5f0004abe9541b63d4af3a8a2e2537a6085a4
frontend/src/components/Loading.tsx
frontend/src/components/Loading.tsx
import Progress from 'antd/lib/progress'; import * as React from "react"; import {Status} from "../utils/types"; export interface LoadingProps { // TODO: Make "status" a proper type. status: number; } export default class Loading extends React.Component<LoadingProps, never> { render() { const progress = this.props.status / ( Status.Folder | Status.Feed | Status.Article | Status.Favicon); return ( <div className="article-list-empty"> <Progress percent={100 * progress} showInfo={false} status="active" strokeWidth={5}/> </div> ) } }
import Progress from 'antd/lib/progress'; import * as React from "react"; import {Status} from "../utils/types"; export interface LoadingProps { // TODO: Make "status" a proper type. status: number; } export default class Loading extends React.Component<LoadingProps, never> { render() { const progress = this.props.status / ( Status.Folder | Status.Feed | Status.Article | Status.Favicon); return ( <div className="article-list-empty"> <Progress percent={100 * progress} showInfo={false} status="active" strokeColor={{ from: "#ececec", to: "#222", }} strokeWidth={5}/> </div> ) } }
Change loading bar color to a gray gradient.
frontend: Change loading bar color to a gray gradient. This matches the rest of the color scheme of the web UI.
TypeScript
mit
jrupac/goliath,jrupac/goliath,jrupac/goliath,jrupac/goliath,jrupac/goliath
--- +++ @@ -19,6 +19,10 @@ percent={100 * progress} showInfo={false} status="active" + strokeColor={{ + from: "#ececec", + to: "#222", + }} strokeWidth={5}/> </div> )
5ae771321a5f2d801ba521662baf6a73ff22ea83
client/src/app.module.ts
client/src/app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpModule, JsonpModule } from '@angular/http'; import { AppComponent } from './app/app.component'; import { NavbarComponent } from './app/navbar/navbar.component'; import { HomeComponent} from './app/home/home.component'; import { KittensComponent } from './app/kittens/kittens.component'; import { UserListComponent } from './app/users/user-list.component'; import { UserListService } from './app/users/user-list.service'; import { PlantListComponent } from './app/plants/plant-list.component'; import { PlantComponent } from './app/plants/plant.component'; import { PlantListService } from './app/plants/plant-list.service'; import { DialogComponent} from './app/dialog/dialog.component'; import { routing } from './app/app.routes'; import { FormsModule } from '@angular/forms'; import { PipeModule } from './pipe.module'; @NgModule({ imports: [ BrowserModule, HttpModule, JsonpModule, routing, FormsModule, PipeModule ], declarations: [ AppComponent, KittensComponent, HomeComponent, NavbarComponent, UserListComponent, PlantListComponent, PlantComponent ], providers: [ UserListService, PlantListService ], bootstrap: [ AppComponent ] }) export class AppModule {}
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpModule, JsonpModule } from '@angular/http'; import { AppComponent } from './app/app.component'; import { NavbarComponent } from './app/navbar/navbar.component'; import { HomeComponent} from './app/home/home.component'; import { KittensComponent } from './app/kittens/kittens.component'; import { UserListComponent } from './app/users/user-list.component'; import { UserListService } from './app/users/user-list.service'; import { PlantListComponent } from './app/plants/plant-list.component'; import { PlantComponent } from './app/plants/plant.component'; import { PlantListService } from './app/plants/plant-list.service'; import { routing } from './app/app.routes'; import { FormsModule } from '@angular/forms'; import { PipeModule } from './pipe.module'; @NgModule({ imports: [ BrowserModule, HttpModule, JsonpModule, routing, FormsModule, PipeModule ], declarations: [ AppComponent, KittensComponent, HomeComponent, NavbarComponent, UserListComponent, PlantListComponent, PlantComponent ], providers: [ UserListService, PlantListService ], bootstrap: [ AppComponent ] }) export class AppModule {}
Remove import of removed DialogComponent
Remove import of removed DialogComponent
TypeScript
mit
UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2,UMM-CSci-3601-S17/digital-display-garden-iteration-3-dorfner,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2,UMM-CSci-3601-S17/digital-display-garden-iteration-3-dorfner,UMM-CSci-3601-S17/digital-display-garden-iteration-3-dorfner,UMM-CSci-3601-S17/digital-display-garden-iteration-3-dorfner
--- +++ @@ -11,7 +11,6 @@ import { PlantListComponent } from './app/plants/plant-list.component'; import { PlantComponent } from './app/plants/plant.component'; import { PlantListService } from './app/plants/plant-list.service'; -import { DialogComponent} from './app/dialog/dialog.component'; import { routing } from './app/app.routes'; import { FormsModule } from '@angular/forms';
bcec34f9cc47432346fc8d649fe6dd2c40deeabf
src/plugins/zoom/zoom.ts
src/plugins/zoom/zoom.ts
import {Workflow} from "../../"; import {PluginBase} from "../plugin-base"; export class ZoomPlugin extends PluginBase { private svg: SVGSVGElement; private dispose: Function | undefined; registerWorkflow(workflow: Workflow): void { super.registerWorkflow(workflow); this.svg = workflow.svgRoot; this.dispose = this.attachWheelListener(); } attachWheelListener(): () => void { const handler = this.onMouseWheel.bind(this); this.svg.addEventListener("mousewheel", handler, true); return () => this.svg.removeEventListener("mousewheel", handler, true); } onMouseWheel(event: MouseWheelEvent) { const scale = this.workflow.scale; const scaleUpdate = scale - event.deltaY / 500; const zoominOut = scaleUpdate < scale; const zoomingIn = scaleUpdate > scale; if (zoomingIn && this.workflow.maxScale < scaleUpdate) { return; } if (zoominOut && this.workflow.minScale > scaleUpdate) { return; } this.workflow.scaleAtPoint(scaleUpdate, event.clientX, event.clientY); event.stopPropagation(); } destroy(): void { if (typeof this.dispose === "function") { this.dispose(); } this.dispose = undefined; } }
import {Workflow} from "../../"; import {PluginBase} from "../plugin-base"; export class ZoomPlugin extends PluginBase { private svg: SVGSVGElement; private dispose: Function | undefined; registerWorkflow(workflow: Workflow): void { super.registerWorkflow(workflow); this.svg = workflow.svgRoot; this.dispose = this.attachWheelListener(); } attachWheelListener(): () => void { const handler = this.onMouseWheel.bind(this); this.svg.addEventListener("wheel", handler, true); return () => this.svg.removeEventListener("wheel", handler, true); } onMouseWheel(event: MouseWheelEvent) { const scale = this.workflow.scale; const scaleUpdate = scale - event.deltaY / 500; const zoominOut = scaleUpdate < scale; const zoomingIn = scaleUpdate > scale; if (zoomingIn && this.workflow.maxScale < scaleUpdate) { return; } if (zoominOut && this.workflow.minScale > scaleUpdate) { return; } this.workflow.scaleAtPoint(scaleUpdate, event.clientX, event.clientY); event.stopPropagation(); } destroy(): void { if (typeof this.dispose === "function") { this.dispose(); } this.dispose = undefined; } }
Change non-standard deprecated mousewheel event to wheel event
Change non-standard deprecated mousewheel event to wheel event
TypeScript
apache-2.0
rabix/cwl-svg,rabix/cwl-svg,rabix/cwl-svg
--- +++ @@ -14,8 +14,8 @@ attachWheelListener(): () => void { const handler = this.onMouseWheel.bind(this); - this.svg.addEventListener("mousewheel", handler, true); - return () => this.svg.removeEventListener("mousewheel", handler, true); + this.svg.addEventListener("wheel", handler, true); + return () => this.svg.removeEventListener("wheel", handler, true); } onMouseWheel(event: MouseWheelEvent) {
1d286dd3566b97e40cb9338aa204f225d0df9687
polygerrit-ui/app/test/common-test-setup-karma.ts
polygerrit-ui/app/test/common-test-setup-karma.ts
/** * @license * Copyright 2020 Google LLC * SPDX-License-Identifier: Apache-2.0 */ import {testResolver as testResolverImpl} from './common-test-setup'; declare global { interface Window { testResolver: typeof testResolverImpl; } let testResolver: typeof testResolverImpl; } let originalOnBeforeUnload: typeof window.onbeforeunload; suiteSetup(() => { // This suiteSetup() method is called only once before all tests // Can't use window.addEventListener("beforeunload",...) here, // the handler is raised too late. originalOnBeforeUnload = window.onbeforeunload; window.onbeforeunload = function (e: BeforeUnloadEvent) { // If a test reloads a page, we can't prevent it. // However we can print an error and the stack trace with assert.fail try { throw new Error(); } catch (e) { console.error('Page reloading attempt detected.'); if (e instanceof Error) { console.error(e.stack?.toString()); } } if (originalOnBeforeUnload) { originalOnBeforeUnload.call(window, e); } }; }); suiteTeardown(() => { // This suiteTeardown() method is called only once after all tests window.onbeforeunload = originalOnBeforeUnload; }); window.testResolver = testResolverImpl;
/** * @license * Copyright 2020 Google LLC * SPDX-License-Identifier: Apache-2.0 */ import {testResolver as testResolverImpl} from './common-test-setup'; declare global { interface Window { testResolver: typeof testResolverImpl; } let testResolver: typeof testResolverImpl; } window.testResolver = testResolverImpl;
Remove page reload detection in tests
Remove page reload detection in tests Our test runner handles this automatically and fails the test with error code 1. https://imgur.com/a/JTOQPtU Release-Notes: skip Change-Id: Ida8a8ddb0c42a9b2c138d8235c72af79f4487e66
TypeScript
apache-2.0
GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit
--- +++ @@ -12,34 +12,4 @@ let testResolver: typeof testResolverImpl; } -let originalOnBeforeUnload: typeof window.onbeforeunload; - -suiteSetup(() => { - // This suiteSetup() method is called only once before all tests - - // Can't use window.addEventListener("beforeunload",...) here, - // the handler is raised too late. - originalOnBeforeUnload = window.onbeforeunload; - window.onbeforeunload = function (e: BeforeUnloadEvent) { - // If a test reloads a page, we can't prevent it. - // However we can print an error and the stack trace with assert.fail - try { - throw new Error(); - } catch (e) { - console.error('Page reloading attempt detected.'); - if (e instanceof Error) { - console.error(e.stack?.toString()); - } - } - if (originalOnBeforeUnload) { - originalOnBeforeUnload.call(window, e); - } - }; -}); - -suiteTeardown(() => { - // This suiteTeardown() method is called only once after all tests - window.onbeforeunload = originalOnBeforeUnload; -}); - window.testResolver = testResolverImpl;
b674ada8bca18bc2ba0e545d73f79459cc27dd88
src/v2/Apps/ArtistSeries/routes.tsx
src/v2/Apps/ArtistSeries/routes.tsx
import loadable from "@loadable/component" import { graphql } from "react-relay" import { RouteConfig } from "found" // import React from "react" const ArtistSeriesApp = loadable(() => import("./ArtistSeriesApp")) // const ArtistSeriesApp = props => <h1>{props.artistSeries.internalID}</h1> export const routes: RouteConfig[] = [ { path: "/artist-series/:slug", getComponent: () => ArtistSeriesApp, prepare: () => { ArtistSeriesApp.preload() }, query: graphql` query routes_ArtistSeriesQuery($slug: ID!) { artistSeries(id: $slug) { ...ArtistSeriesApp_artistSeries } } `, }, ]
import loadable from "@loadable/component" import { graphql } from "react-relay" import { RouteConfig } from "found" const ArtistSeriesApp = loadable(() => import("./ArtistSeriesApp")) export const routes: RouteConfig[] = [ { path: "/artist-series/:slug", getComponent: () => ArtistSeriesApp, prepare: () => { ArtistSeriesApp.preload() }, query: graphql` query routes_ArtistSeriesQuery($slug: ID!) { artistSeries(id: $slug) { ...ArtistSeriesApp_artistSeries } } `, }, ]
Remove leftover commented out code
Remove leftover commented out code
TypeScript
mit
oxaudo/force,oxaudo/force,oxaudo/force,artsy/force,artsy/force,eessex/force,eessex/force,joeyAghion/force,artsy/force-public,artsy/force-public,eessex/force,joeyAghion/force,joeyAghion/force,joeyAghion/force,oxaudo/force,eessex/force,artsy/force,artsy/force
--- +++ @@ -1,11 +1,8 @@ import loadable from "@loadable/component" import { graphql } from "react-relay" import { RouteConfig } from "found" -// import React from "react" const ArtistSeriesApp = loadable(() => import("./ArtistSeriesApp")) - -// const ArtistSeriesApp = props => <h1>{props.artistSeries.internalID}</h1> export const routes: RouteConfig[] = [ {
bb6d2a89bbeb0fadc50359f35f1d1aff60c6a34f
src/app/shell/Link.tsx
src/app/shell/Link.tsx
import * as React from 'react'; import { DestinyAccount } from '../accounts/destiny-account.service'; import { $transitions, $state } from '../ngimport-more'; import { t } from 'i18next'; export default class Link extends React.Component<{ account?: DestinyAccount; state: string; text?: string; }, { active: boolean; }> { private listener; constructor(props) { super(props); this.state = { active: false }; } componentDidMount() { this.listener = $transitions.onEnter({}, (_transition, state) => { this.setState({ active: (state.name === this.props.state) }); }); } componentWillUnmount() { this.listener(); } render() { const { text, children } = this.props; const { active } = this.state; return ( <a className={active ? 'link active' : 'link'} onClick={this.clicked}>{children}{text && t(text)}</a> ); } private clicked = () => { const { state, account } = this.props; $state.go(state, account); } }
import * as React from 'react'; import { DestinyAccount } from '../accounts/destiny-account.service'; import { $transitions, $state } from '../ngimport-more'; import { t } from 'i18next'; export default class Link extends React.PureComponent<{ account?: DestinyAccount; state: string; text?: string; }, { active: boolean; }> { private listener; constructor(props) { super(props); this.state = { active: false }; } componentDidMount() { this.listener = $transitions.onEnter({}, (_transition, state) => { this.setState({ active: (state.name === this.props.state) }); }); } componentWillUnmount() { this.listener(); } render() { const { text, children } = this.props; const { active } = this.state; return ( <a className={active ? 'link active' : 'link'} onClick={this.clicked}>{children}{text && t(text)}</a> ); } private clicked = () => { const { state, account } = this.props; $state.go(state, account); } }
Make link a pure component
Make link a pure component
TypeScript
mit
chrisfried/DIM,bhollis/DIM,DestinyItemManager/DIM,delphiactual/DIM,bhollis/DIM,DestinyItemManager/DIM,chrisfried/DIM,chrisfried/DIM,DestinyItemManager/DIM,delphiactual/DIM,delphiactual/DIM,DestinyItemManager/DIM,delphiactual/DIM,bhollis/DIM,bhollis/DIM,chrisfried/DIM
--- +++ @@ -3,7 +3,7 @@ import { $transitions, $state } from '../ngimport-more'; import { t } from 'i18next'; -export default class Link extends React.Component<{ +export default class Link extends React.PureComponent<{ account?: DestinyAccount; state: string; text?: string;
b3892c565028a5212300e6f0f46fef99814020dc
spec/regression/helpers.ts
spec/regression/helpers.ts
import {execute, parse} from "graphql"; import {ProxyConfig} from "../../src/config/proxy-configuration"; import {createProxySchema} from "../../src/proxy-schema"; /** * Create a graphql proxy for a configuration and execute a query on it. * @param proxyConfig * @param query * @param variableValues * @returns {Promise<void>} */ export async function testConfigWithQuery(proxyConfig: ProxyConfig, query: string, variableValues: {[name: string]: any}) { const schema = await createProxySchema(proxyConfig); const document = parse(query, {}); const result = await execute(schema, document, {}, {}, variableValues, undefined); return result.data; }
import { execute, parse, validate } from 'graphql'; import {ProxyConfig} from "../../src/config/proxy-configuration"; import {createProxySchema} from "../../src/proxy-schema"; import { assertSuccessfulResponse } from '../../src/endpoints/client'; /** * Create a graphql proxy for a configuration and execute a query on it. * @param proxyConfig * @param query * @param variableValues * @returns {Promise<void>} */ export async function testConfigWithQuery(proxyConfig: ProxyConfig, query: string, variableValues: {[name: string]: any}) { const schema = await createProxySchema(proxyConfig); const document = parse(query, {}); const errors = validate(schema, document); if (errors.length) { throw new Error(JSON.stringify(errors)); } const result = await execute(schema, document, {cariedOnRootValue: true}, {}, variableValues, undefined); assertSuccessfulResponse(result); return result.data; }
Validate queries of regression tests before executing
Validate queries of regression tests before executing
TypeScript
mit
AEB-labs/graphql-weaver,AEB-labs/graphql-weaver
--- +++ @@ -1,6 +1,7 @@ -import {execute, parse} from "graphql"; +import { execute, parse, validate } from 'graphql'; import {ProxyConfig} from "../../src/config/proxy-configuration"; import {createProxySchema} from "../../src/proxy-schema"; +import { assertSuccessfulResponse } from '../../src/endpoints/client'; /** * Create a graphql proxy for a configuration and execute a query on it. @@ -12,6 +13,11 @@ export async function testConfigWithQuery(proxyConfig: ProxyConfig, query: string, variableValues: {[name: string]: any}) { const schema = await createProxySchema(proxyConfig); const document = parse(query, {}); - const result = await execute(schema, document, {}, {}, variableValues, undefined); + const errors = validate(schema, document); + if (errors.length) { + throw new Error(JSON.stringify(errors)); + } + const result = await execute(schema, document, {cariedOnRootValue: true}, {}, variableValues, undefined); + assertSuccessfulResponse(result); return result.data; }
2e6e81599e36eeb58189401d363797fb32e4f3c7
src/types.ts
src/types.ts
import _ = require('lodash'); export interface DotEnsime { name: string scalaVersion: string scalaEdition: string javaHome: string javaFlags: string rootDir: string cacheDir: string compilerJars: string dotEnsimePath: string sourceRoots: [string] } export class EnsimeInstance { rootDir: string; constructor(public dotEnsime: DotEnsime, public client: any, public ui?: any) { } isSourceOf = (path) => _.some(this.dotEnsime.sourceRoots, (sourceRoot) => path.startsWith(sourceRoot)) destroy () { this.client.destroy() if(this.ui) { this.ui.destroy() } } }
import _ = require('lodash'); export interface DotEnsime { name: string scalaVersion: string scalaEdition: string javaHome: string javaFlags: string rootDir: string cacheDir: string compilerJars: string dotEnsimePath: string sourceRoots: [string] } export class EnsimeInstance { rootDir: string; constructor(public dotEnsime: DotEnsime, public client: any, public ui?: any) { this.rootDir = dotEnsime.rootDir; } isSourceOf = (path) => _.some(this.dotEnsime.sourceRoots, (sourceRoot) => path.startsWith(sourceRoot)) destroy () { this.client.destroy() if(this.ui) { this.ui.destroy() } } }
Fix error that rootDir was not set, unabling to stop
Fix error that rootDir was not set, unabling to stop
TypeScript
mit
hedefalk/ensime-node,ensime/ensime-node,Jarlakxen/ensime-node,ensime/ensime-node,Jarlakxen/ensime-node,hedefalk/ensime-node
--- +++ @@ -17,6 +17,7 @@ rootDir: string; constructor(public dotEnsime: DotEnsime, public client: any, public ui?: any) { + this.rootDir = dotEnsime.rootDir; } isSourceOf = (path) => _.some(this.dotEnsime.sourceRoots, (sourceRoot) => path.startsWith(sourceRoot))
3d0a17f13c1e3d4981e26dbabf60eaefcf36771a
src/BetterFolders/icon.tsx
src/BetterFolders/icon.tsx
import {React} from "dium"; import {Settings, FolderData} from "./settings"; export interface ConnectedBetterFolderIconProps { folderId: number; childProps: any; FolderIcon: React.FunctionComponent<any>; } export const ConnectedBetterFolderIcon = ({folderId, ...props}: ConnectedBetterFolderIconProps): JSX.Element => { const data = Settings.useCurrent().folders[folderId]; return <BetterFolderIcon data={data} {...props}/>; }; export interface BetterFolderIconProps { data: FolderData; childProps: any; FolderIcon: React.FunctionComponent<any>; } export const BetterFolderIcon = ({data, childProps, FolderIcon}: BetterFolderIconProps): JSX.Element => { if (FolderIcon) { const result = FolderIcon(childProps); if (data.icon && (childProps.expanded || data.always)) { result.props.children = <div className="betterFolders-customIcon" style={{backgroundImage: `url(${data.icon})`}}/>; } return result; } else { return null; } };
import {React} from "dium"; import {Settings, FolderData} from "./settings"; export interface BetterFolderIconProps { data?: FolderData; childProps: any; FolderIcon: React.FunctionComponent<any>; } export const BetterFolderIcon = ({data, childProps, FolderIcon}: BetterFolderIconProps): JSX.Element => { if (FolderIcon) { const result = FolderIcon(childProps); if (data?.icon && (childProps.expanded || data.always)) { result.props.children = <div className="betterFolders-customIcon" style={{backgroundImage: `url(${data.icon})`}}/>; } return result; } else { return null; } }; export interface ConnectedBetterFolderIconProps { folderId: number; childProps: any; FolderIcon: React.FunctionComponent<any>; } const compareFolderData = (a?: FolderData, b?: FolderData): boolean => a?.icon === b?.icon && a?.always === b?.always; export const ConnectedBetterFolderIcon = ({folderId, ...props}: ConnectedBetterFolderIconProps): JSX.Element => { const data = Settings.useSelector( (current) => current.folders[folderId], [folderId], compareFolderData ); return <BetterFolderIcon data={data} {...props}/>; };
Fix no folder data error
Fix no folder data error
TypeScript
mit
Zerthox/BetterDiscord-Plugins,Zerthox/BetterDiscord-Plugins
--- +++ @@ -1,5 +1,23 @@ import {React} from "dium"; import {Settings, FolderData} from "./settings"; + +export interface BetterFolderIconProps { + data?: FolderData; + childProps: any; + FolderIcon: React.FunctionComponent<any>; +} + +export const BetterFolderIcon = ({data, childProps, FolderIcon}: BetterFolderIconProps): JSX.Element => { + if (FolderIcon) { + const result = FolderIcon(childProps); + if (data?.icon && (childProps.expanded || data.always)) { + result.props.children = <div className="betterFolders-customIcon" style={{backgroundImage: `url(${data.icon})`}}/>; + } + return result; + } else { + return null; + } +}; export interface ConnectedBetterFolderIconProps { folderId: number; @@ -7,25 +25,13 @@ FolderIcon: React.FunctionComponent<any>; } +const compareFolderData = (a?: FolderData, b?: FolderData): boolean => a?.icon === b?.icon && a?.always === b?.always; + export const ConnectedBetterFolderIcon = ({folderId, ...props}: ConnectedBetterFolderIconProps): JSX.Element => { - const data = Settings.useCurrent().folders[folderId]; + const data = Settings.useSelector( + (current) => current.folders[folderId], + [folderId], + compareFolderData + ); return <BetterFolderIcon data={data} {...props}/>; }; - -export interface BetterFolderIconProps { - data: FolderData; - childProps: any; - FolderIcon: React.FunctionComponent<any>; -} - -export const BetterFolderIcon = ({data, childProps, FolderIcon}: BetterFolderIconProps): JSX.Element => { - if (FolderIcon) { - const result = FolderIcon(childProps); - if (data.icon && (childProps.expanded || data.always)) { - result.props.children = <div className="betterFolders-customIcon" style={{backgroundImage: `url(${data.icon})`}}/>; - } - return result; - } else { - return null; - } -};
4cfe424af34ef39ca615f17f3b9d28439598d80c
library/src/game/GameClientModels/AbilityBarState.ts
library/src/game/GameClientModels/AbilityBarState.ts
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import { createDefaultOnUpdated, createDefaultOnReady, Updatable } from './_Updatable'; import engineInit from './_Init'; declare global { interface AbilityBarItem { id: number; keyActionID: number; boundKeyName: string; type: AbilityButtonType; track: AbilityTrack; error: string; timing: Timing; disruption: CurrentMax; } interface AbilityBarStateModel { abilities: ArrayMap<AbilityBarItem>; } type AbilityBarState = AbilityBarStateModel & Updatable; type ImmutableAbilityBarState = DeepImmutable<AbilityBarState>; } export const AbilityBarState_Update = 'abilityBarState.update'; function initDefault(): AbilityBarState { return { abilities: {}, isReady: false, updateEventName: AbilityBarState_Update, onUpdated: createDefaultOnUpdated(AbilityBarState_Update), onReady: createDefaultOnReady(AbilityBarState_Update), }; } /** * Initialize this model with the game engine. */ export default function() { engineInit( AbilityBarState_Update, initDefault, () => _devGame.abilityBarState, (model: AbilityBarState) => { _devGame.abilityBarState = model; }); }
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import { createDefaultOnUpdated, createDefaultOnReady, Updatable } from './_Updatable'; import engineInit from './_Init'; declare global { interface AbilityBarItem { id: number; keyActionID: number; boundKeyName: string; status: AbilityButtonState; type: AbilityButtonType; track: AbilityTrack; error: string; timing: Timing; disruption: CurrentMax; } interface AbilityBarStateModel { abilities: ArrayMap<AbilityBarItem>; } type AbilityBarState = AbilityBarStateModel & Updatable; type ImmutableAbilityBarState = DeepImmutable<AbilityBarState>; } export const AbilityBarState_Update = 'abilityBarState.update'; function initDefault(): AbilityBarState { return { abilities: {}, isReady: false, updateEventName: AbilityBarState_Update, onUpdated: createDefaultOnUpdated(AbilityBarState_Update), onReady: createDefaultOnReady(AbilityBarState_Update), }; } /** * Initialize this model with the game engine. */ export default function() { engineInit( AbilityBarState_Update, initDefault, () => _devGame.abilityBarState, (model: AbilityBarState) => { _devGame.abilityBarState = model; }); }
Add status to AbilityBarItem interface
Add status to AbilityBarItem interface
TypeScript
mpl-2.0
saddieeiddas/Camelot-Unchained,Ajackster/Camelot-Unchained,CUModSquad/Camelot-Unchained,Ajackster/Camelot-Unchained,csegames/Camelot-Unchained,Ajackster/Camelot-Unchained,csegames/Camelot-Unchained,Mehuge/Camelot-Unchained,CUModSquad/Camelot-Unchained,saddieeiddas/Camelot-Unchained,Mehuge/Camelot-Unchained,csegames/Camelot-Unchained,saddieeiddas/Camelot-Unchained,Mehuge/Camelot-Unchained,CUModSquad/Camelot-Unchained
--- +++ @@ -13,7 +13,7 @@ id: number; keyActionID: number; boundKeyName: string; - + status: AbilityButtonState; type: AbilityButtonType; track: AbilityTrack; error: string;
8d7661cf9e1f5493e878ae1ddd4056d10da1adf6
scripts/Actions/InfiniteScroller.ts
scripts/Actions/InfiniteScroller.ts
import { AnimeNotifier } from "../AnimeNotifier" // Load more export function loadMore(arn: AnimeNotifier, button: HTMLButtonElement) { // Prevent firing this event multiple times if(arn.isLoading || button.disabled) { return } arn.loading(true) button.disabled = true let target = arn.app.find("load-more-target") let index = button.dataset.index fetch("/_" + arn.app.currentPath + "/from/" + index) .then(response => { let newIndex = response.headers.get("X-LoadMore-Index") // End of data? if(newIndex === "-1") { button.classList.add("hidden") } else { button.dataset.index = newIndex } return response }) .then(response => response.text()) .then(body => { let tmp = document.createElement(target.tagName) tmp.innerHTML = body let children = [...tmp.childNodes] window.requestAnimationFrame(() => { for(let child of children) { target.appendChild(child) } arn.app.emit("DOMContentLoaded") }) }) .catch(err => arn.statusMessage.showError(err)) .then(() => { arn.loading(false) button.disabled = false }) }
import { AnimeNotifier } from "../AnimeNotifier" // Load more export function loadMore(arn: AnimeNotifier, button: HTMLButtonElement) { // Prevent firing this event multiple times if(arn.isLoading || button.disabled) { return } arn.loading(true) button.disabled = true let target = arn.app.find("load-more-target") let index = button.dataset.index fetch("/_" + arn.app.currentPath + "/from/" + index) .then(response => { let newIndex = response.headers.get("X-LoadMore-Index") // End of data? if(newIndex === "-1") { button.disabled = true button.classList.add("hidden") } else { button.dataset.index = newIndex } return response }) .then(response => response.text()) .then(body => { let tmp = document.createElement(target.tagName) tmp.innerHTML = body let children = [...tmp.childNodes] window.requestAnimationFrame(() => { for(let child of children) { target.appendChild(child) } arn.app.emit("DOMContentLoaded") }) }) .catch(err => arn.statusMessage.showError(err)) .then(() => { arn.loading(false) button.disabled = false }) }
Disable button at end of infinite scrolling
Disable button at end of infinite scrolling
TypeScript
mit
animenotifier/notify.moe,animenotifier/notify.moe,animenotifier/notify.moe
--- +++ @@ -12,18 +12,19 @@ let target = arn.app.find("load-more-target") let index = button.dataset.index - + fetch("/_" + arn.app.currentPath + "/from/" + index) .then(response => { let newIndex = response.headers.get("X-LoadMore-Index") // End of data? if(newIndex === "-1") { + button.disabled = true button.classList.add("hidden") } else { button.dataset.index = newIndex } - + return response }) .then(response => response.text())
3b6ade483f8cdb2d39be0bbfd70e7844220b25c7
app/javascript/retrospring/features/inbox/generate.ts
app/javascript/retrospring/features/inbox/generate.ts
import Rails from '@rails/ujs'; import I18n from 'retrospring/i18n'; import { updateDeleteButton } from './delete'; import { showErrorNotification } from 'utilities/notifications'; export function generateQuestionHandler(): void { Rails.ajax({ url: '/ajax/generate_question', type: 'POST', dataType: 'json', success: (data) => { if (!data.success) return false; document.querySelector('#entries').insertAdjacentHTML('afterbegin', data.render); updateDeleteButton(); }, error: (data, status, xhr) => { console.log(data, status, xhr); showErrorNotification(I18n.translate('frontend.error.message')); } }); }
import { post } from '@rails/request.js'; import I18n from 'retrospring/i18n'; import { updateDeleteButton } from './delete'; import { showErrorNotification } from 'utilities/notifications'; export function generateQuestionHandler(): void { post('/ajax/generate_question') .then(async response => { const data = await response.json; if (!data.success) return false; document.querySelector('#entries').insertAdjacentHTML('afterbegin', data.render); updateDeleteButton(); }) .catch(err => { console.log(err); showErrorNotification(I18n.translate('frontend.error.message')); }); }
Refactor question generating to use request.js
Refactor question generating to use request.js
TypeScript
agpl-3.0
Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring
--- +++ @@ -1,23 +1,21 @@ -import Rails from '@rails/ujs'; +import { post } from '@rails/request.js'; import I18n from 'retrospring/i18n'; import { updateDeleteButton } from './delete'; import { showErrorNotification } from 'utilities/notifications'; export function generateQuestionHandler(): void { - Rails.ajax({ - url: '/ajax/generate_question', - type: 'POST', - dataType: 'json', - success: (data) => { + post('/ajax/generate_question') + .then(async response => { + const data = await response.json; + if (!data.success) return false; document.querySelector('#entries').insertAdjacentHTML('afterbegin', data.render); updateDeleteButton(); - }, - error: (data, status, xhr) => { - console.log(data, status, xhr); - showErrorNotification(I18n.translate('frontend.error.message')); - } - }); + }) + .catch(err => { + console.log(err); + showErrorNotification(I18n.translate('frontend.error.message')); + }); }
dbfde47fcdd069bb5272f022229c5af80405365b
src/reducers/audioSettings.ts
src/reducers/audioSettings.ts
import { EditAudioSource, ChangeVolume, ToggleAudioEnabled } from '../actions/audio'; import { AudioSettings } from '../types'; import { EDIT_AUDIO_SOURCE, CHANGE_VOLUME, TOGGLE_AUDIO_ENABLED } from '../constants'; const initial: AudioSettings = { enabled: true, volume: 0.5, audio1: new Audio( 'http://k003.kiwi6.com/hotlink/vnu75u0sif/file-sounds-765-tweet.ogg' ), audio2: new Audio('http://k003.kiwi6.com/hotlink/85iq6xu5ul/coins.ogg') }; type AudioAction = EditAudioSource | ChangeVolume | ToggleAudioEnabled; export default (state = initial, action: AudioAction) => { let partialState: Partial<AudioSettings> | undefined; switch (action.type) { case EDIT_AUDIO_SOURCE: partialState = { [action.field]: action.value }; break; case CHANGE_VOLUME: partialState = { volume: action.value }; break; case TOGGLE_AUDIO_ENABLED: partialState = { enabled: !state.enabled }; break; default: return state; } return { ...state, ...partialState }; };
import { EditAudioSource, ChangeVolume, ToggleAudioEnabled } from '../actions/audio'; import { AudioSettings } from '../types'; import { EDIT_AUDIO_SOURCE, CHANGE_VOLUME, TOGGLE_AUDIO_ENABLED } from '../constants'; const initial: AudioSettings = { enabled: true, volume: 0.1, audio1: new Audio( 'http://k003.kiwi6.com/hotlink/vnu75u0sif/file-sounds-765-tweet.ogg' ), audio2: new Audio('http://k003.kiwi6.com/hotlink/85iq6xu5ul/coins.ogg') }; type AudioAction = EditAudioSource | ChangeVolume | ToggleAudioEnabled; export default (state = initial, action: AudioAction) => { let partialState: Partial<AudioSettings> | undefined; switch (action.type) { case EDIT_AUDIO_SOURCE: partialState = { [action.field]: action.value }; break; case CHANGE_VOLUME: partialState = { volume: action.value }; break; case TOGGLE_AUDIO_ENABLED: partialState = { enabled: !state.enabled }; break; default: return state; } return { ...state, ...partialState }; };
Change default volume to 0.10.
Change default volume to 0.10.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -12,7 +12,7 @@ const initial: AudioSettings = { enabled: true, - volume: 0.5, + volume: 0.1, audio1: new Audio( 'http://k003.kiwi6.com/hotlink/vnu75u0sif/file-sounds-765-tweet.ogg' ),