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
15c51c740ef4d1511677aefb7081aab930b70701
learnbase/src/main/webapp/ts/main.ts
learnbase/src/main/webapp/ts/main.ts
console.log("tester"); window.onload = function userLogin() : void { fetch('/userlogin').then(response => response.text()).then((pageContent) => { const loginSection = document.getElementById('user-page-content') as HTMLDivElement; loginSection.innerHTML = pageContent; }); } fucntion pageChanger() { const navBar = document.getElementById("myTopnav"); if (navBar.className === "topnav") { navBar.classname += " responsive"; } else { x.className = "topnav"; } }
console.log("tester"); window.onload = function userLogin() : void { fetch('/userlogin').then(response => response.text()).then((pageContent) => { const loginSection = document.getElementById('user-page-content') as HTMLDivElement; loginSection.innerHTML = pageContent; }); } fucntion pageChanger() { const navBar = document.getElementById("myTopnav"); if (navBar.className === "topnav") { navBar.classname += " responsive"; } else { navBar.className = "topnav"; } }
Fix typo in pageChanger function
Fix typo in pageChanger function
TypeScript
apache-2.0
googleinterns/learnbase,googleinterns/learnbase,googleinterns/learnbase,googleinterns/learnbase,googleinterns/learnbase
--- +++ @@ -12,6 +12,6 @@ if (navBar.className === "topnav") { navBar.classname += " responsive"; } else { - x.className = "topnav"; + navBar.className = "topnav"; } }
09c7bfae6275ea4161d359ac523c85b80c036345
src/testing/permissions-restrict.directive.stub.ts
src/testing/permissions-restrict.directive.stub.ts
import { Directive, EventEmitter, Input, Output, TemplateRef, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[ngxPermissionsOnly],[ngxPermissionsExcept]', }) export class NgxPermissionsRestrictStubDirective { @Input() ngxPermissionsOnly: string | string[]; @Input() ngxPermissionsOnlyThen: TemplateRef<any>; @Input() ngxPermissionsOnlyElse: TemplateRef<any>; @Input() ngxPermissionsExcept: string | string[]; @Input() ngxPermissionsExceptElse: TemplateRef<any>; @Input() ngxPermissionsExceptThen: TemplateRef<any>; @Input() ngxPermissionsThen: TemplateRef<any>; @Input() ngxPermissionsElse: TemplateRef<any>; @Output() permissionsAuthorized = new EventEmitter(); @Output() permissionsUnauthorized = new EventEmitter(); constructor(private viewContainer: ViewContainerRef) {} ngOnInit(): void { this.viewContainer.clear(); this.viewContainer.createEmbeddedView(this.getAuthorizedTemplate()); } private getAuthorizedTemplate() { return this.ngxPermissionsOnlyElse || this.ngxPermissionsExceptElse || this.ngxPermissionsElse } }
import { Directive, EventEmitter, Input, Output, TemplateRef, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[ngxPermissionsOnly],[ngxPermissionsExcept]', }) export class NgxPermissionsRestrictStubDirective { @Input() ngxPermissionsOnly: string | string[]; @Input() ngxPermissionsOnlyThen: TemplateRef<any>; @Input() ngxPermissionsOnlyElse: TemplateRef<any>; @Input() ngxPermissionsExcept: string | string[]; @Input() ngxPermissionsExceptElse: TemplateRef<any>; @Input() ngxPermissionsExceptThen: TemplateRef<any>; @Input() ngxPermissionsThen: TemplateRef<any>; @Input() ngxPermissionsElse: TemplateRef<any>; @Output() permissionsAuthorized = new EventEmitter(); @Output() permissionsUnauthorized = new EventEmitter(); constructor(private viewContainer: ViewContainerRef) {} ngOnInit(): void { this.viewContainer.clear(); this.viewContainer.createEmbeddedView(this.getUnAuthorizedTemplate()); } private getUnAuthorizedTemplate() { return this.ngxPermissionsOnlyElse || this.ngxPermissionsExceptElse || this.ngxPermissionsElse } }
Change name to more proper in testing restrict directive
Change name to more proper in testing restrict directive
TypeScript
mit
AlexKhymenko/ngx-permissions,AlexKhymenko/ngx-permissions,AlexKhymenko/ngx-permissions
--- +++ @@ -26,11 +26,11 @@ ngOnInit(): void { this.viewContainer.clear(); - this.viewContainer.createEmbeddedView(this.getAuthorizedTemplate()); + this.viewContainer.createEmbeddedView(this.getUnAuthorizedTemplate()); } - private getAuthorizedTemplate() { + private getUnAuthorizedTemplate() { return this.ngxPermissionsOnlyElse || this.ngxPermissionsExceptElse || this.ngxPermissionsElse
150b61ad6ca0cee6b567f74499ee9e3cec32d550
src/app/components/editor/editor.component.ts
src/app/components/editor/editor.component.ts
import {AfterViewInit, Component, ElementRef, Input, OnDestroy, ViewChild} from '@angular/core'; import {EditorConfig} from '../../models/models'; declare const monaco: any; declare const require: any; @Component({ selector: 'app-editor', template: `<div #view class="monaco-editor" style="height: 85vh;"></div>` }) export class EditorComponent implements AfterViewInit, OnDestroy { @Input() config: EditorConfig; // todo: @Input() height: number; editor: any; @ViewChild('view') view: ElementRef; private _updateLayout: Function; constructor() { this._updateLayout = this.updateView.bind(this); } ngAfterViewInit() { const w: any = <any>window; w.require.config({ paths: { 'vs': 'assets/monaco/vs' } }); w.require(['vs/editor/editor.main'], () => { this.editor = monaco.editor.create(this.view.nativeElement, { readOnly: this.config.readOnly, scrollBeyondLastLine: false, theme: this.config.theme }); w.addEventListener('resize', this._updateLayout); this.editor.setModel( monaco.editor.createModel(this.config.content, this.config.contentType) ) }); } ngOnDestroy(): void { const w: any = <any>window; w.removeEventListener('resize', this._updateLayout); } updateView() { this.editor.layout(); } }
import {AfterViewInit, Component, ElementRef, Input, OnDestroy, ViewChild} from '@angular/core'; import {EditorConfig} from '../../models/models'; declare const monaco: any; declare const require: any; @Component({ selector: 'app-editor', template: `<div #view class="monaco-editor" style="height: 85vh;"></div>` }) export class EditorComponent implements AfterViewInit, OnDestroy { @Input() config: EditorConfig; // todo: @Input() height: number; editor: any; @ViewChild('view') view: ElementRef; private _updateLayout: Function; constructor() { this._updateLayout = this.updateView.bind(this); } ngAfterViewInit() { const w: any = <any>window; w.require.config({ paths: { 'vs': 'assets/monaco/vs' } }); w.require(['vs/editor/editor.main'], () => { this.editor = monaco.editor.create(this.view.nativeElement, { readOnly: this.config.readOnly, scrollBeyondLastLine: false, theme: this.config.theme }); w.addEventListener('resize', this._updateLayout); this.editor.setModel( monaco.editor.createModel(this.config.content, this.config.contentType) ) }); } ngOnDestroy(): void { const w: any = <any>window; w.removeEventListener('resize', this._updateLayout); } updateView() { this.editor.layout(); } getValue(): string { return this.editor.getValue(); } }
Revert ":hammer: Remove unused function"
Revert ":hammer: Remove unused function" This reverts commit b9e7cbe4eef8017f0d8d883890ce6018bba364b0.
TypeScript
mit
tadashi-aikawa/gemini-viewer,tadashi-aikawa/gemini-viewer,tadashi-aikawa/gemini-viewer
--- +++ @@ -47,4 +47,8 @@ updateView() { this.editor.layout(); } + + getValue(): string { + return this.editor.getValue(); + } }
be3ef4da4c52765e00a5ca8be0071416e620c773
src/app/services/actor.service.spec.ts
src/app/services/actor.service.spec.ts
import { Http, RequestOptions, RequestMethod, ResponseOptions, Response } from '@angular/http'; import { MockBackend } from '@angular/http/testing'; import { ActorService } from './actor.service'; import { Actor } from '../models'; describe('Service: Actor', () => { const endpointRegex: RegExp = /\/api\/person$/; let service: ActorService; let mockBackend: MockBackend; let httpWithMockBackend: Http; beforeEach(() => { mockBackend = new MockBackend(); httpWithMockBackend = new Http(mockBackend, new RequestOptions()); service = new ActorService(httpWithMockBackend); }); describe('getActor method', () => { it('should GET an actor from the endpoint', () => { let expectedResponse: Actor = { name: '' }; mockBackend.connections.subscribe(connection => { expect(connection.request.url.toString()).toMatch(endpointRegex); expect(connection.request.method).toEqual(RequestMethod.Get); connection.mockRespond(new Response(new ResponseOptions({ status: 200, body: expectedResponse, }))); }); service.getActor().subscribe(response => expect(response).toEqual(expectedResponse)); }); }); });
import { inject, TestBed } from '@angular/core/testing'; import { Http, RequestMethod, ResponseOptions, Response, ConnectionBackend, BaseRequestOptions } from '@angular/http'; import { MockBackend } from '@angular/http/testing'; import { ActorService } from './actor.service'; import { Actor } from '../models'; describe('Service: Actor', () => { const endpointRegex: RegExp = /\/api\/person$/; beforeEach(() => { TestBed.configureTestingModule({ providers: [ { provide: Http, useFactory: (backend: ConnectionBackend, defaultOptions: BaseRequestOptions) => { return new Http(backend, defaultOptions); }, deps: [MockBackend, BaseRequestOptions] }, { provide: ActorService, useClass: ActorService }, { provide: MockBackend, useClass: MockBackend }, { provide: BaseRequestOptions, useClass: BaseRequestOptions } ] }); }); describe('getActor method', () => { it('should GET an actor from the endpoint', inject([MockBackend, ActorService], (backend: MockBackend, service: ActorService) => { let expectedResponse: Actor = { name: '' }; backend.connections.subscribe(connection => { expect(connection.request.url.toString()).toMatch(endpointRegex); expect(connection.request.method).toEqual(RequestMethod.Get); connection.mockRespond(new Response(new ResponseOptions({ status: 200, body: expectedResponse, }))); }); service.getActor().subscribe(response => { expect(response).toEqual(expectedResponse); }); })); }); });
Switch service testing to TestBed
Switch service testing to TestBed
TypeScript
isc
textbook/known-for-web,textbook/known-for-web,textbook/known-for-web
--- +++ @@ -1,4 +1,12 @@ -import { Http, RequestOptions, RequestMethod, ResponseOptions, Response } from '@angular/http'; +import { inject, TestBed } from '@angular/core/testing'; +import { + Http, + RequestMethod, + ResponseOptions, + Response, + ConnectionBackend, + BaseRequestOptions +} from '@angular/http'; import { MockBackend } from '@angular/http/testing'; import { ActorService } from './actor.service'; @@ -8,21 +16,28 @@ const endpointRegex: RegExp = /\/api\/person$/; - let service: ActorService; - - let mockBackend: MockBackend; - let httpWithMockBackend: Http; - beforeEach(() => { - mockBackend = new MockBackend(); - httpWithMockBackend = new Http(mockBackend, new RequestOptions()); - service = new ActorService(httpWithMockBackend); + TestBed.configureTestingModule({ + providers: [ + { + provide: Http, + useFactory: (backend: ConnectionBackend, defaultOptions: BaseRequestOptions) => { + return new Http(backend, defaultOptions); + }, + deps: [MockBackend, BaseRequestOptions] + }, + { provide: ActorService, useClass: ActorService }, + { provide: MockBackend, useClass: MockBackend }, + { provide: BaseRequestOptions, useClass: BaseRequestOptions } + ] + }); }); describe('getActor method', () => { - it('should GET an actor from the endpoint', () => { + it('should GET an actor from the endpoint', inject([MockBackend, ActorService], (backend: MockBackend, service: ActorService) => { let expectedResponse: Actor = { name: '' }; - mockBackend.connections.subscribe(connection => { + + backend.connections.subscribe(connection => { expect(connection.request.url.toString()).toMatch(endpointRegex); expect(connection.request.method).toEqual(RequestMethod.Get); @@ -32,8 +47,10 @@ }))); }); - service.getActor().subscribe(response => expect(response).toEqual(expectedResponse)); - }); + service.getActor().subscribe(response => { + expect(response).toEqual(expectedResponse); + }); + })); }); });
3b36b54b96397caec5b1e9013f386b082bef62d7
src/app/domotics/domotics.component.ts
src/app/domotics/domotics.component.ts
import { Component, OnInit } from '@angular/core'; import { ConfigService } from '../_services/config.service'; import { timer } from 'rxjs'; import { OpenhabService } from '../_services/openhab.service'; @Component({ selector: 'app-domotics', templateUrl: './domotics.component.html', styleUrls: ['./domotics.component.scss'] }) export class DomoticsComponent implements OnInit { items: any[]; error: any; constructor(private openhab: OpenhabService, private config: ConfigService) { } ngOnInit(): void { timer(0, this.config.configuration.domotics.refreshRate).subscribe(() => this.update()); } update() { this.openhab.getItems(this.config.configuration.domotics.showGroup) .subscribe( data => { this.items = data; this.error = undefined; }, error => this.error = error); }}
import { Component, OnInit } from '@angular/core'; import { ConfigService } from '../_services/config.service'; import { timer } from 'rxjs'; import { OpenhabService } from '../_services/openhab.service'; @Component({ selector: 'app-domotics', templateUrl: './domotics.component.html', styleUrls: ['./domotics.component.scss'] }) export class DomoticsComponent implements OnInit { items: any[]; error: any; constructor(private openhab: OpenhabService, private config: ConfigService) { } ngOnInit(): void { timer(0, this.config.configuration.domotics.refreshRate).subscribe(() => this.update()); } update() { this.openhab.getItems(this.config.configuration.domotics.showGroup) .subscribe( data => { this.items = data .sort((a, b) => (a.label || a.name) > (b.label || b.name) ? 1 : (a.label || a.name) < (b.label || b.name) ? -1 : 0); this.error = undefined; }, error => this.error = error); }}
Sort domotics devices by label/name
Sort domotics devices by label/name
TypeScript
mit
yktoo/infopi,yktoo/infopi,yktoo/infopi,yktoo/infopi
--- +++ @@ -23,7 +23,11 @@ this.openhab.getItems(this.config.configuration.domotics.showGroup) .subscribe( data => { - this.items = data; + this.items = data + .sort((a, b) => + (a.label || a.name) > (b.label || b.name) ? 1 : + (a.label || a.name) < (b.label || b.name) ? -1 : + 0); this.error = undefined; }, error => this.error = error);
a955a107a87c47338dc8b4a1fd5d4fafb7a98dc1
src/components/Search/SearchFields.tsx
src/components/Search/SearchFields.tsx
import * as React from 'react'; import { TextField, Select, Checkbox } from '@shopify/polaris'; interface Props { readonly value: string; readonly onChange: (value: string) => void; } interface SortTypeProps extends Props { readonly options: string[]; } interface CheckBoxProps { readonly onChange: (value: boolean) => void; readonly checked: boolean; } const SearchDelayField = ({ value, onChange }: Props) => { return ( <TextField label="Search Delay" type="number" suffix="seconds" min={10} autoComplete={false} value={value} onChange={onChange} /> ); }; const MinimumRewardField = ({ value, onChange }: Props) => { return ( <TextField label="Minimum Reward" type="number" min={0} prefix="$" autoComplete={false} value={value} onChange={onChange} /> ); }; const SortTypeField = ({ options, onChange }: SortTypeProps) => { return ( <Select label="Sort By" options={options.map((option: string) => ({ label: option, value: option }))} onChange={onChange} /> ); }; const QualifiedBox = ({ checked, onChange }: CheckBoxProps) => { return <Checkbox label="Qualified only" checked={checked} onChange={onChange} />; }; export { SearchDelayField, MinimumRewardField, SortTypeField, QualifiedBox };
import * as React from 'react'; import { TextField, Select, Checkbox } from '@shopify/polaris'; interface Props { readonly value: string; readonly onChange: (value: string) => void; } interface SortTypeProps extends Props { readonly options: string[]; } interface CheckBoxProps { readonly onChange: (value: boolean) => void; readonly checked: boolean; } const SearchDelayField = ({ value, onChange }: Props) => { return ( <TextField label="Search Delay" type="number" suffix="seconds" min={10} autoComplete={false} value={value} onChange={onChange} /> ); }; const MinimumRewardField = ({ value, onChange }: Props) => { return ( <TextField label="Minimum Reward" type="number" min={0} prefix="$" autoComplete={false} value={value} onChange={onChange} /> ); }; const SortTypeField = ({ value, options, onChange }: SortTypeProps) => { return ( <Select label="Sort By" options={options.map((option: string) => ({ label: option, value: option }))} value={value} onChange={onChange} /> ); }; const QualifiedBox = ({ checked, onChange }: CheckBoxProps) => { return <Checkbox label="Qualified only" checked={checked} onChange={onChange} />; }; export { SearchDelayField, MinimumRewardField, SortTypeField, QualifiedBox };
Fix issue where SortTypeField wasn't displaying changes to its value.
Fix issue where SortTypeField wasn't displaying changes to its value.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -43,7 +43,7 @@ ); }; -const SortTypeField = ({ options, onChange }: SortTypeProps) => { +const SortTypeField = ({ value, options, onChange }: SortTypeProps) => { return ( <Select label="Sort By" @@ -51,6 +51,7 @@ label: option, value: option }))} + value={value} onChange={onChange} /> );
43ee699af27b3c8e6d39b8f23cf227a70b67d1a2
client/Commands/components/Toolbar.tsx
client/Commands/components/Toolbar.tsx
import * as React from "react"; import { Button } from "../../Components/Button"; import { Command } from "../Command"; interface ToolbarProps { encounterCommands: Command []; combatantCommands: Command []; } interface ToolbarState { displayWide: boolean; } export class Toolbar extends React.Component<ToolbarProps, ToolbarState> { constructor(props: ToolbarProps) { super(props); this.state = { displayWide: false }; } private toggleWidth = () => { this.setState({ displayWide: !this.state.displayWide }); } public render() { const className = this.state.displayWide ? "toolbar s-wide" : "toolbar s-narrow"; const commandToButton = c => <Button onClick={c.ActionBinding} additionalClassNames={c.ActionBarIcon} />; const encounterCommandButtons = this.props.encounterCommands.filter(c => c.ShowOnActionBar()).map(commandToButton); const combatantCommandButtons = this.props.combatantCommands.filter(c => c.ShowOnActionBar()).map(commandToButton); //TODO: Ensure subscription to ShowOnActionBar changes return <div className={className}> <div className="commands-encounter"> {encounterCommandButtons} </div> <div className="commands-combatant"> {combatantCommandButtons} </div> </div>; } }
import * as React from "react"; import { Button } from "../../Components/Button"; import { Command } from "../Command"; interface ToolbarProps { encounterCommands: Command[]; combatantCommands: Command[]; } interface ToolbarState { displayWide: boolean; widthStyle: string; } export class Toolbar extends React.Component<ToolbarProps, ToolbarState> { private outerElement: HTMLDivElement; constructor(props: ToolbarProps) { super(props); this.state = { displayWide: false, widthStyle: null }; } public componentDidMount() { const width = this.outerElement.offsetWidth - this.outerElement.clientWidth; this.setState({widthStyle: width.toString() + "px"}); } private toggleWidth = () => { this.setState({ displayWide: !this.state.displayWide }); } public render() { const className = this.state.displayWide ? "toolbar s-wide" : "toolbar s-narrow"; const commandToButton = c => <Button onClick={c.ActionBinding} additionalClassNames={c.ActionBarIcon} />; const encounterCommandButtons = this.props.encounterCommands.filter(c => c.ShowOnActionBar()).map(commandToButton); const combatantCommandButtons = this.props.combatantCommands.filter(c => c.ShowOnActionBar()).map(commandToButton); //TODO: Ensure subscription to ShowOnActionBar changes return <div className={className} ref={e => this.outerElement = e}> <div className="scrollframe" style={{ width: this.state.widthStyle }}> <div className="commands-encounter"> {encounterCommandButtons} </div> <div className="commands-combatant"> {combatantCommandButtons} </div> </div> </div>; } }
Apply manual width to scrollframe div
Apply manual width to scrollframe div
TypeScript
mit
cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative
--- +++ @@ -3,20 +3,28 @@ import { Command } from "../Command"; interface ToolbarProps { - encounterCommands: Command []; - combatantCommands: Command []; + encounterCommands: Command[]; + combatantCommands: Command[]; } interface ToolbarState { displayWide: boolean; + widthStyle: string; } export class Toolbar extends React.Component<ToolbarProps, ToolbarState> { + private outerElement: HTMLDivElement; constructor(props: ToolbarProps) { super(props); this.state = { - displayWide: false + displayWide: false, + widthStyle: null }; + } + + public componentDidMount() { + const width = this.outerElement.offsetWidth - this.outerElement.clientWidth; + this.setState({widthStyle: width.toString() + "px"}); } private toggleWidth = () => { @@ -28,14 +36,17 @@ const commandToButton = c => <Button onClick={c.ActionBinding} additionalClassNames={c.ActionBarIcon} />; const encounterCommandButtons = this.props.encounterCommands.filter(c => c.ShowOnActionBar()).map(commandToButton); const combatantCommandButtons = this.props.combatantCommands.filter(c => c.ShowOnActionBar()).map(commandToButton); + //TODO: Ensure subscription to ShowOnActionBar changes - return <div className={className}> - <div className="commands-encounter"> - {encounterCommandButtons} - </div> - <div className="commands-combatant"> - {combatantCommandButtons} + return <div className={className} ref={e => this.outerElement = e}> + <div className="scrollframe" style={{ width: this.state.widthStyle }}> + <div className="commands-encounter"> + {encounterCommandButtons} + </div> + <div className="commands-combatant"> + {combatantCommandButtons} + </div> </div> </div>; }
38374f73a189a19812253487ac463b08943a5aad
client/src/app/models/project.model.ts
client/src/app/models/project.model.ts
import { ProjectWizardData } from './project-wizard-data.model'; export class Project { public projectName: string; public freelancer: string; public client: string; public startDate: number; public endDate: number; public budget: number; public billingMethod: string; public paymentType: string; public paymentTrigger: string; public paymentComments: string; public description: string; public deliverables: string; public jobRequirements: string[]; public location: string; public hoursPerWeek: number; public creatorID?: string; public status?: string; public lastUpdated?: number; public static convert(wizardData: ProjectWizardData): Project { return { projectName: wizardData.project.projectName, freelancer: wizardData.freelancer.kvkNumber, client: wizardData.client.kvkNumber, startDate: +Date.UTC(wizardData.project.startYear, +wizardData.project.startMonth - 1, wizardData.project.startDay), endDate: +Date.UTC(wizardData.project.endYear, +wizardData.project.endMonth - 1, wizardData.project.endDay), budget: +wizardData.project.budget, billingMethod: wizardData.project.paymentMethod, paymentType: wizardData.project.budgetType, paymentTrigger: wizardData.project.paymentTrigger, paymentComments: wizardData.project.paymentInfo, description: wizardData.project.projectDescription, deliverables: '', jobRequirements: [], location: '', hoursPerWeek: 0 }; } }
import { ProjectWizardData } from './project-wizard-data.model'; export class Project { public projectName: string; public freelancer: string; public client: string; public startDate: number; public endDate: number; public budget: number; public billingMethod: string; public paymentType: string; public paymentTrigger: string; public paymentComments: string; public description: string; public deliverables: string; public jobRequirements: string[]; public location: string; public hoursPerWeek: number; public creatorID?: string; public status?: string; public lastUpdated?: number; public static convert(wizardData: ProjectWizardData): Project { return { projectName: wizardData.project.projectName, freelancer: wizardData.freelancer.kvkNumber, client: wizardData.client.kvkNumber, startDate: +Date.UTC(wizardData.project.startYear, +wizardData.project.startMonth - 1, wizardData.project.startDay), endDate: +Date.UTC(wizardData.project.endYear, +wizardData.project.endMonth - 1, wizardData.project.endDay), budget: +wizardData.project.budget, billingMethod: wizardData.project.paymentMethod, paymentType: wizardData.project.budgetType, paymentTrigger: wizardData.project.paymentTrigger, paymentComments: wizardData.project.paymentInfo, description: wizardData.project.projectDescription, deliverables: '', jobRequirements: [], location: '', hoursPerWeek: 40 }; } }
Fix front-end to set non-zero value for hoursPerWeek
Fix front-end to set non-zero value for hoursPerWeek
TypeScript
apache-2.0
IBMZissou/dbh17-zissou,IBMZissou/dbh17-zissou,IBMZissou/dbh17-zissou,IBMZissou/dbh17-zissou,IBMZissou/dbh17-zissou
--- +++ @@ -36,7 +36,7 @@ deliverables: '', jobRequirements: [], location: '', - hoursPerWeek: 0 + hoursPerWeek: 40 }; } }
b9d4ef00c3c36cb1668c668dcffc235dd1a2a95e
app/core/services/api-file.service.ts
app/core/services/api-file.service.ts
import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs'; import 'rxjs/add/operator/map'; import { File } from '../../shared/file'; import { ApiTimeoutService } from './api-timeout.service'; @Injectable() export class ApiFileService { constructor( private http: Http, private apiTimeoutService: ApiTimeoutService, ) {} // public methods get(name: string): Observable<File>{ return this.apiTimeoutService.handleTimeout<File>( this.http .get(`/api/file/${name}`) .map((r: Response) => r.json()._source as File) ); } }
import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs'; import 'rxjs/add/operator/map'; import { File } from '../../shared/file'; import { ApiTimeoutService } from './api-timeout.service'; import { ApiErrorService } from './api-error.service'; @Injectable() export class ApiFileService { constructor( private http: Http, private apiTimeoutService: ApiTimeoutService, private apiErrorService: ApiErrorService, ) {} // public methods get(name: string): Observable<File>{ return this.apiTimeoutService.handleTimeout<File>( this.apiErrorService.handleError( this.http .get(`/api/file/${name}`) ).map((r: Response) => r.json()._source as File) ); } }
Set the ApiFileService to use the ApiErrorService
Set the ApiFileService to use the ApiErrorService
TypeScript
apache-2.0
FAANG/faang-portal-frontend,FAANG/faang-portal-frontend,FAANG/faang-portal-frontend
--- +++ @@ -5,6 +5,7 @@ import { File } from '../../shared/file'; import { ApiTimeoutService } from './api-timeout.service'; +import { ApiErrorService } from './api-error.service'; @Injectable() export class ApiFileService { @@ -12,15 +13,17 @@ constructor( private http: Http, private apiTimeoutService: ApiTimeoutService, + private apiErrorService: ApiErrorService, ) {} // public methods get(name: string): Observable<File>{ return this.apiTimeoutService.handleTimeout<File>( - this.http - .get(`/api/file/${name}`) - .map((r: Response) => r.json()._source as File) + this.apiErrorService.handleError( + this.http + .get(`/api/file/${name}`) + ).map((r: Response) => r.json()._source as File) ); } }
26870fa2e9d99603ccc266a8b62184699ecbd0c8
src/rules/_basic_rule_config.ts
src/rules/_basic_rule_config.ts
export abstract class BasicRuleConfig { /** Is the rule enabled? */ public enabled?: boolean = true; /** List of patterns to exclude */ public exclude?: string[] = []; }
export abstract class BasicRuleConfig { /** Is the rule enabled? */ public enabled?: boolean = true; /** List of patterns to exclude */ public exclude?: string[] = []; /** An explanation for why the rule is enforced */ public reason?: string = ""; }
Add reason attribute to rule config
Add reason attribute to rule config
TypeScript
mit
larshp/abaplint,larshp/abaplint,larshp/abaplint,larshp/abapOpenChecksJS,larshp/abaplint,larshp/abapOpenChecksJS,larshp/abapOpenChecksJS
--- +++ @@ -3,4 +3,6 @@ public enabled?: boolean = true; /** List of patterns to exclude */ public exclude?: string[] = []; + /** An explanation for why the rule is enforced */ + public reason?: string = ""; }
807e07409731749378fc2af19381c2d59c4af150
src/services/setting.service.ts
src/services/setting.service.ts
import { Injectable } from '@angular/core'; import * as fs from 'fs'; let settingPath = ''; export function setSettingPath(path: string) { settingPath = path; } interface Setting { tokens: string[]; hide_buttons: boolean; } @Injectable() export class SettingService { setting: Setting; get tokens(): string[] { return this.setting.tokens; } get hide_buttons(): boolean { return this.setting.hide_buttons; } constructor() { try { this.setting = JSON.parse(fs.readFileSync(settingPath, 'utf8')); console.log(this.setting); } catch (e) { this.setting = {} as Setting; } if (!this.setting.tokens) { this.setting.tokens = ['']; } if (!this.setting.hide_buttons) { this.setting.hide_buttons = false; } } save() { fs.writeFileSync(settingPath, JSON.stringify(this.setting)); } }
import { Injectable } from '@angular/core'; import * as fs from 'fs'; let settingPath = ''; export function setSettingPath(path: string) { settingPath = path; } interface Setting { tokens: string[]; hide_buttons: boolean; } @Injectable() export class SettingService { setting: Setting; get tokens(): string[] { return this.setting.tokens; } get hide_buttons(): boolean { return this.setting.hide_buttons; } constructor() { try { this.setting = JSON.parse(fs.readFileSync(settingPath, 'utf8')); console.log(this.setting); } catch (e) { this.setting = {} as Setting; } if (this.setting.tokens === undefined) { this.setting.tokens = ['']; } if (this.setting.hide_buttons === undefined) { this.setting.hide_buttons = false; } } save() { fs.writeFileSync(settingPath, JSON.stringify(this.setting)); } }
Use undefined to check setting existence
Use undefined to check setting existence
TypeScript
mit
mazun/SlackStream,mazun/SlackStream,mazun/ASlack-Stream,mazun/ASlack-Stream,mazun/SlackStream,mazun/ASlack-Stream,mazun/ASlack-Stream,mazun/SlackStream
--- +++ @@ -31,8 +31,8 @@ this.setting = {} as Setting; } - if (!this.setting.tokens) { this.setting.tokens = ['']; } - if (!this.setting.hide_buttons) { this.setting.hide_buttons = false; } + if (this.setting.tokens === undefined) { this.setting.tokens = ['']; } + if (this.setting.hide_buttons === undefined) { this.setting.hide_buttons = false; } } save() {
ef481d8edce24412eee6430d6564461a9025ce46
src/definition.ts
src/definition.ts
import * as vscode from 'vscode'; import { Index } from './index'; export class DefinitionProvider implements vscode.DefinitionProvider { constructor(private index: Index) { } provideDefinition(document: vscode.TextDocument, position: vscode.Position): vscode.Location { let reference = this.index.queryReferences(document.uri, { position: position })[0]; if (!reference) return null; let section = this.index.query("ALL_FILES", reference.getQuery())[0]; if (!section) return null; return section.location; } }
import * as vscode from 'vscode'; import { Index } from './index'; import { IndexLocator } from './index/index-locator'; export class DefinitionProvider implements vscode.DefinitionProvider { constructor(private indexLocator: IndexLocator) { } provideDefinition(document: vscode.TextDocument, position: vscode.Position): vscode.Location { let reference = this.indexLocator.getIndexForDoc(document).queryReferences(document.uri, { position: position })[0]; if (!reference) return null; let section = this.indexLocator.getIndexForDoc(document).query("ALL_FILES", reference.getQuery())[0]; if (!section) return null; return section.location; } }
Use IndexLocator instead of Index
DefinitionProvider: Use IndexLocator instead of Index
TypeScript
mpl-2.0
hashicorp/vscode-terraform,mauve/vscode-terraform,hashicorp/vscode-terraform,mauve/vscode-terraform,mauve/vscode-terraform,hashicorp/vscode-terraform,mauve/vscode-terraform
--- +++ @@ -1,15 +1,16 @@ import * as vscode from 'vscode'; import { Index } from './index'; +import { IndexLocator } from './index/index-locator'; export class DefinitionProvider implements vscode.DefinitionProvider { - constructor(private index: Index) { } + constructor(private indexLocator: IndexLocator) { } provideDefinition(document: vscode.TextDocument, position: vscode.Position): vscode.Location { - let reference = this.index.queryReferences(document.uri, { position: position })[0]; + let reference = this.indexLocator.getIndexForDoc(document).queryReferences(document.uri, { position: position })[0]; if (!reference) return null; - let section = this.index.query("ALL_FILES", reference.getQuery())[0]; + let section = this.indexLocator.getIndexForDoc(document).query("ALL_FILES", reference.getQuery())[0]; if (!section) return null; return section.location;
532ae3cb91b229531b851f1ef23fd8f669ff4d8d
ui/src/constants.ts
ui/src/constants.ts
export const NAVBAR_HEIGHT = 56; export const SIDEBAR_WIDTH = 500;
export const NAVBAR_HEIGHT = 56; export const SIDEBAR_WIDTH = 400;
Set sidebar width to 400px
Set sidebar width to 400px
TypeScript
apache-2.0
dainst/idai-field-web,dainst/idai-field-web,dainst/idai-field-web
--- +++ @@ -1,2 +1,2 @@ export const NAVBAR_HEIGHT = 56; -export const SIDEBAR_WIDTH = 500; +export const SIDEBAR_WIDTH = 400;
3e8c3c0c307bde48722f9ccd30c813d25b3f10db
app/app.component.ts
app/app.component.ts
import { Component } from '@angular/core'; export class Hero { id: number; name: string; } @Component({ selector: 'my-app', template: '<h1>{{title}}</h1><h2>{{hero.name}} details!</h2>' }) export class AppComponent { title = 'Tour of Heroes'; hero : Hero = { id: 1, name: 'windstorm' }; }
import { Component } from '@angular/core'; export class Hero { id: number; name: string; } @Component({ selector: 'my-app', template:` <h1>{{title}}</h1> <h2>{{hero.name}} details!</h2> <div><label>id: </label>{{hero.id}}</div> <div> <label>name: </label> <input value="{{hero.name}}" placeholder="name"> </div> ` }) export class AppComponent { title = 'Tour of Heroes'; hero : Hero = { id: 1, name: 'windstorm' }; }
Change the quotes around the template to back-ticks
Change the quotes around the template to back-ticks
TypeScript
mit
ffacon/quickstart-ng2,ffacon/quickstart-ng2,ffacon/quickstart-ng2
--- +++ @@ -7,7 +7,15 @@ @Component({ selector: 'my-app', - template: '<h1>{{title}}</h1><h2>{{hero.name}} details!</h2>' + template:` + <h1>{{title}}</h1> + <h2>{{hero.name}} details!</h2> + <div><label>id: </label>{{hero.id}}</div> + <div> + <label>name: </label> + <input value="{{hero.name}}" placeholder="name"> + </div> + ` }) export class AppComponent {
aad32876fcaea679ccd813de583bd5d0e5c6e7d8
types/shelljs-exec-proxy/shelljs-exec-proxy-tests.ts
types/shelljs-exec-proxy/shelljs-exec-proxy-tests.ts
import * as shell from 'shelljs-exec-proxy'; shell.git.status(); // $ExpectType ExecOutputReturnValue shell.git.add('.'); // $ExpectType ExecOutputReturnValue shell.git.commit('-am', 'Fixed issue #1'); // $ExpectType ExecOutputReturnValue shell.git.push('origin', 'master'); // $ExpectType ExecOutputReturnValue shell.cd('string'); // $ExpectType void shell.cd(123); // $ExpectError
import * as shell from 'shelljs-exec-proxy'; shell.git.status(); // $ExpectType ExecOutputReturnValue shell.git.add('.'); // $ExpectType ExecOutputReturnValue shell.git.commit('-am', 'Fixed issue #1'); // $ExpectType ExecOutputReturnValue shell.git.push('origin', 'master'); // $ExpectType ExecOutputReturnValue shell.cd('string'); // $ExpectType ShellString shell.cd(123); // $ExpectError
Fix expected return type error
Fix expected return type error
TypeScript
mit
georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,mcliment/DefinitelyTyped,markogresak/DefinitelyTyped,dsebastien/DefinitelyTyped
--- +++ @@ -5,5 +5,5 @@ shell.git.commit('-am', 'Fixed issue #1'); // $ExpectType ExecOutputReturnValue shell.git.push('origin', 'master'); // $ExpectType ExecOutputReturnValue -shell.cd('string'); // $ExpectType void +shell.cd('string'); // $ExpectType ShellString shell.cd(123); // $ExpectError
5469ff61d2b35a19f1089632aecd11b6481da674
src/xrm-mock/encoding/encoding.mock.ts
src/xrm-mock/encoding/encoding.mock.ts
export class EncodingMock implements Xrm.Encoding { public xmlAttributeEncode(arg: string): string { throw new Error("Not implemented"); } public xmlEncode(arg: string): string { throw new Error("Not implemented"); } }
export class EncodingMock implements Xrm.Encoding { public xmlAttributeEncode(arg: string): string { throw new Error("Not implemented"); } public xmlEncode(arg: string): string { throw new Error("Not implemented"); } public htmlAttributeEncode(arg: string): string { throw new Error("Not implemented"); } public htmlDecode(arg: string): string { throw new Error("Not implemented"); } public htmlEncode(arg: string): string { throw new Error("Not implemented"); } }
Add missing functions in Xrm.Encoding
Add missing functions in Xrm.Encoding
TypeScript
mit
camelCaseDave/xrm-mock,camelCaseDave/xrm-mock
--- +++ @@ -5,4 +5,16 @@ public xmlEncode(arg: string): string { throw new Error("Not implemented"); } + + public htmlAttributeEncode(arg: string): string { + throw new Error("Not implemented"); + } + + public htmlDecode(arg: string): string { + throw new Error("Not implemented"); + } + + public htmlEncode(arg: string): string { + throw new Error("Not implemented"); + } }
ed341ef2a5ee045c839d722b6562297b802ba130
src/client/index.ts
src/client/index.ts
import { setup } from '@cycle/run' import { makeHTTPDriver } from '@cycle/http' import { makeDOMDriver } from '@cycle/dom' import { makeHistoryDriver } from '@cycle/history' import { timeDriver } from '@cycle/time' import switchPath from 'switch-path' import ClientRoutes from './routes' import Main from './main' // register ServiceWorker require('offline-plugin/runtime').install() const { rerunner, restartable } = require('cycle-restart') // define a function to generate a drivers object const getDrivers = () => ({ DOM: restartable(makeDOMDriver('#main'), {pauseSinksWhileReplaying: false}), HTTP: restartable(makeHTTPDriver()), History: makeHistoryDriver(), Time: timeDriver }) // configure rerunner with desired drivers. Rerunner will automatically add Time const run = rerunner(setup, getDrivers) // run the app! run(Main) // handle HMR change events if (module['hot']) { module['hot'].accept('./main', () => { const reloaded = require('./main').default // call run again with the new app source run(reloaded) }) }
import { setup } from '@cycle/run' import { makeHTTPDriver } from '@cycle/http' import { makeDOMDriver } from '@cycle/dom' import { makeHistoryDriver } from '@cycle/history' import { timeDriver } from '@cycle/time' import ClientRoutes from './routes' import Main from './main' // register ServiceWorker require('offline-plugin/runtime').install() const { rerunner, restartable } = require('cycle-restart') // define a function to generate a drivers object const getDrivers = () => ({ DOM: restartable(makeDOMDriver('#main'), {pauseSinksWhileReplaying: false}), HTTP: restartable(makeHTTPDriver()), History: restartable(makeHistoryDriver()), Time: timeDriver }) // configure rerunner with desired drivers. Rerunner will automatically add Time const run = rerunner(setup, getDrivers) // run the app! run(Main) // handle HMR change events if (module['hot']) { module['hot'].accept('./main', () => { const reloaded = require('./main').default // call run again with the new app source run(reloaded) }) }
Remove unused import, make History driver restartable
Remove unused import, make History driver restartable
TypeScript
mit
wyqydsyq/unicycle,wyqydsyq/unicycle
--- +++ @@ -3,7 +3,6 @@ import { makeDOMDriver } from '@cycle/dom' import { makeHistoryDriver } from '@cycle/history' import { timeDriver } from '@cycle/time' -import switchPath from 'switch-path' import ClientRoutes from './routes' import Main from './main' @@ -17,7 +16,7 @@ const getDrivers = () => ({ DOM: restartable(makeDOMDriver('#main'), {pauseSinksWhileReplaying: false}), HTTP: restartable(makeHTTPDriver()), - History: makeHistoryDriver(), + History: restartable(makeHistoryDriver()), Time: timeDriver })
bfc5394cff33130efbdea50ccf03f697db154dc8
src/components/random-number.tsx
src/components/random-number.tsx
import { Component, Prop, State, Listen } from '@stencil/core'; @Component({ tag: 'random-number' }) export class RandomNumber { @State() randomNumber: number; @Prop() min: number; @Prop() max: number; componentDidLoad() { this.randomNumber = Math.floor(Math.random()*(this.max- this.min+1)+ this.min); } @Listen('updateComponent') updateNumberHandler() { this.randomNumber = Math.floor(Math.random()*(this.max- this.min+1)+ this.min); } render() { return ( <p> {this.randomNumber} </p> ); } }
import { Component, Prop, State, Listen } from '@stencil/core'; @Component({ tag: 'random-number' }) export class RandomNumber { @State() randomNumber: number; @Prop() min: number; @Prop() max: number; componentDidLoad() { this.randomNumber = Math.floor(Math.random()*(this.max- this.min+1)+ this.min); } @Listen('updateComponent') updateNumberHandler() { this.randomNumber = Math.floor(Math.random()*(this.max- this.min+1)+ this.min); } render() { return ( this.randomNumber ); } }
Remove styling form random number
Remove styling form random number
TypeScript
mit
TheNerdicCoder/stencil-demo,TheNerdicCoder/stencil-demo,TheNerdicCoder/stencil-demo
--- +++ @@ -21,9 +21,7 @@ render() { return ( - <p> - {this.randomNumber} - </p> + this.randomNumber ); } }
25f452da764fe289f745f712f29daf525e4ec2b5
test/helpers.ts
test/helpers.ts
import { GitProcess, IGitResult } from '../lib' // NOTE: bump these versions to the latest stable releases export const gitVersion = '2.26.0' export const gitLfsVersion = '2.7.2' const temp = require('temp').track() export async function initialize(repositoryName: string): Promise<string> { const testRepoPath = temp.mkdirSync(`desktop-git-test-${repositoryName}`) await GitProcess.exec(['init'], testRepoPath) await GitProcess.exec(['config', 'user.email', '"some.user@email.com"'], testRepoPath) await GitProcess.exec(['config', 'user.name', '"Some User"'], testRepoPath) return testRepoPath } export function verify(result: IGitResult, callback: (result: IGitResult) => void) { try { callback(result) } catch (e) { console.log('error encountered while verifying; poking at response from Git:') console.log(` - exitCode: ${result.exitCode}`) console.log(` - stdout: ${result.stdout.trim()}`) console.log(` - stderr: ${result.stderr.trim()}`) console.log() throw e } }
import { GitProcess, IGitResult } from '../lib' // NOTE: bump these versions to the latest stable releases export const gitVersion = '2.26.' export const gitLfsVersion = '2.7.2' const temp = require('temp').track() export async function initialize(repositoryName: string): Promise<string> { const testRepoPath = temp.mkdirSync(`desktop-git-test-${repositoryName}`) await GitProcess.exec(['init'], testRepoPath) await GitProcess.exec(['config', 'user.email', '"some.user@email.com"'], testRepoPath) await GitProcess.exec(['config', 'user.name', '"Some User"'], testRepoPath) return testRepoPath } export function verify(result: IGitResult, callback: (result: IGitResult) => void) { try { callback(result) } catch (e) { console.log('error encountered while verifying; poking at response from Git:') console.log(` - exitCode: ${result.exitCode}`) console.log(` - stdout: ${result.stdout.trim()}`) console.log(` - stderr: ${result.stderr.trim()}`) console.log() throw e } }
Make git version on test less restrictive
Make git version on test less restrictive
TypeScript
mit
desktop/dugite,desktop/dugite,desktop/dugite
--- +++ @@ -1,7 +1,7 @@ import { GitProcess, IGitResult } from '../lib' // NOTE: bump these versions to the latest stable releases -export const gitVersion = '2.26.0' +export const gitVersion = '2.26.' export const gitLfsVersion = '2.7.2' const temp = require('temp').track()
9ce86e4d0c16dda7b4db1d6e81cf4f5dc863341d
src/tests/compiler/literal/regularExpressionLiteralTests.ts
src/tests/compiler/literal/regularExpressionLiteralTests.ts
import {expect} from "chai"; import {VariableStatement, RegularExpressionLiteral} from "./../../../compiler"; import {getInfoFromText} from "./../testHelpers"; function getInfoFromTextWithInitializer(text: string) { const obj = getInfoFromText<VariableStatement>(text); const initializer = obj.firstChild.getDeclarations()[0].getInitializerOrThrow() as RegularExpressionLiteral; return { ...obj, initializer }; } describe(nameof(RegularExpressionLiteral), () => { describe(nameof<RegularExpressionLiteral>(n => n.getLiteralValue), () => { function doTest(text: string, pattern: string, flags: string) { const {initializer} = getInfoFromTextWithInitializer(text); const regExpr = initializer.getLiteralValue(); expect(regExpr.source).to.equal(pattern); expect(regExpr.flags).to.equal(flags); } it("should get the correct literal text when there are flags", () => { doTest("const t = /testing/gi", "testing", "gi"); }); it("should get the correct literal text when there are no flags", () => { doTest("const t = /testing/", "testing", ""); }); }); });
import {expect} from "chai"; import {VariableStatement, RegularExpressionLiteral} from "./../../../compiler"; import {getInfoFromText} from "./../testHelpers"; function getInfoFromTextWithInitializer(text: string) { const obj = getInfoFromText<VariableStatement>(text); const initializer = obj.firstChild.getDeclarations()[0].getInitializerOrThrow() as RegularExpressionLiteral; return { ...obj, initializer }; } describe(nameof(RegularExpressionLiteral), () => { describe(nameof<RegularExpressionLiteral>(n => n.getLiteralValue), () => { function doTest(text: string, pattern: string, flags: string) { const {initializer} = getInfoFromTextWithInitializer(text); const regExpr = initializer.getLiteralValue(); expect(regExpr.source).to.equal(pattern); expect(regExpr.flags).to.equal(flags); } it("should get the correct literal text when there are flags", () => { doTest("const t = /testing/gi;", "testing", "gi"); }); it("should get the correct literal text when there are no flags", () => { doTest("const t = /testing/;", "testing", ""); }); }); });
Fix linux only failing test.
Fix linux only failing test.
TypeScript
mit
dsherret/ts-simple-ast
--- +++ @@ -18,11 +18,11 @@ } it("should get the correct literal text when there are flags", () => { - doTest("const t = /testing/gi", "testing", "gi"); + doTest("const t = /testing/gi;", "testing", "gi"); }); it("should get the correct literal text when there are no flags", () => { - doTest("const t = /testing/", "testing", ""); + doTest("const t = /testing/;", "testing", ""); }); }); });
481e648d592d529ad2e1850cd000a5e6ae876d6b
packages/userscript/source/index.ts
packages/userscript/source/index.ts
import devSavegame from "./fixtures/savegame"; import devSettings from "./fixtures/settings"; import { Options } from "./options/Options"; import { SettingsStorage } from "./options/SettingsStorage"; import { cinfo } from "./tools/Log"; import { isNil } from "./tools/Maybe"; import { SavegameLoader } from "./tools/SavegameLoader"; import { UserScript } from "./UserScript"; (async () => { const kittenGame = await UserScript.waitForGame(); // For development convenience, load a lategame save to give us more test options. if (!isNil(devSavegame)) { await new SavegameLoader(kittenGame).load(devSavegame); } const userScript = await UserScript.getDefaultInstance(); // @ts-expect-error Manipulating global containers is naughty, be we want to expose the script host. window.kittenScientists = userScript; cinfo("Looking for legacy settings..."); const legacySettings = SettingsStorage.getLegacySettings(); if (legacySettings === null) { cinfo("No legacy settings found. Default settings will be used."); } if (!isNil(devSettings)) { const options = Options.parseLegacyOptions(devSettings); userScript.injectOptions(options); } userScript.run(); })();
import devSavegame from "./fixtures/savegame"; import devSettings from "./fixtures/settings"; import { Options } from "./options/Options"; import { SettingsStorage } from "./options/SettingsStorage"; import { cinfo } from "./tools/Log"; import { isNil } from "./tools/Maybe"; import { SavegameLoader } from "./tools/SavegameLoader"; import { UserScript } from "./UserScript"; (async () => { const kittenGame = await UserScript.waitForGame(); // For development convenience, load a lategame save to give us more test options. if (!isNil(devSavegame)) { await new SavegameLoader(kittenGame).load(devSavegame); } const userScript = await UserScript.getDefaultInstance(); // @ts-expect-error Manipulating global containers is naughty, be we want to expose the script host. window.kittenScientists = userScript; cinfo("Looking for legacy settings..."); const legacySettings = SettingsStorage.getLegacySettings(); if (legacySettings === null) { cinfo("No legacy settings found. Default settings will be used."); } if (!isNil(devSettings)) { const options = Options.parseLegacyOptions(devSettings); userScript.injectOptions(options); } else if (!isNil(legacySettings)) { const options = Options.parseLegacyOptions(legacySettings); userScript.injectOptions(options); } userScript.run(); })();
Use legacy settings, if available
feat: Use legacy settings, if available
TypeScript
mit
oliversalzburg/cbc-kitten-scientists,oliversalzburg/cbc-kitten-scientists,oliversalzburg/cbc-kitten-scientists
--- +++ @@ -29,6 +29,9 @@ if (!isNil(devSettings)) { const options = Options.parseLegacyOptions(devSettings); userScript.injectOptions(options); + } else if (!isNil(legacySettings)) { + const options = Options.parseLegacyOptions(legacySettings); + userScript.injectOptions(options); } userScript.run();
e45faa86d33f295a34e389c8da27b69fc7d9dc2c
app/src/ui/banners/banner.tsx
app/src/ui/banners/banner.tsx
import * as React from 'react' import { Octicon, OcticonSymbol } from '../octicons' interface IBannerProps { readonly id?: string readonly timeout?: number readonly dismissable?: boolean readonly onDismissed: () => void } export class Banner extends React.Component<IBannerProps, {}> { private timeoutId: NodeJS.Timer | null = null public render() { return ( <div id={this.props.id} className="banner"> <div className="contents">{this.props.children}</div> {this.renderCloseButton()} </div> ) } private renderCloseButton() { const { dismissable } = this.props if (dismissable === undefined || dismissable === false) { return null } return ( <div className="close"> <a onClick={this.props.onDismissed}> <Octicon symbol={OcticonSymbol.x} /> </a> </div> ) } public componentDidMount = () => { if (this.props.timeout !== undefined) { this.timeoutId = setTimeout(() => { this.props.onDismissed() }, this.props.timeout) } } public componentWillUnmount = () => { if (this.props.timeout !== undefined && this.timeoutId !== null) { clearTimeout(this.timeoutId) } } }
import * as React from 'react' import { Octicon, OcticonSymbol } from '../octicons' interface IBannerProps { readonly id?: string readonly timeout?: number readonly dismissable?: boolean readonly onDismissed: () => void } export class Banner extends React.Component<IBannerProps, {}> { private timeoutId: number | null = null public render() { return ( <div id={this.props.id} className="banner"> <div className="contents">{this.props.children}</div> {this.renderCloseButton()} </div> ) } private renderCloseButton() { const { dismissable } = this.props if (dismissable === undefined || dismissable === false) { return null } return ( <div className="close"> <a onClick={this.props.onDismissed}> <Octicon symbol={OcticonSymbol.x} /> </a> </div> ) } public componentDidMount = () => { if (this.props.timeout !== undefined) { this.timeoutId = window.setTimeout(() => { this.props.onDismissed() }, this.props.timeout) } } public componentWillUnmount = () => { if (this.props.timeout !== undefined && this.timeoutId !== null) { window.clearTimeout(this.timeoutId) } } }
Use the Window setTimeout instead of the Node setTimeout
Use the Window setTimeout instead of the Node setTimeout Co-Authored-By: Rafael Oleza <2cf5b502deae2e387c60721eb8244c243cb5c4e1@users.noreply.github.com>
TypeScript
mit
desktop/desktop,kactus-io/kactus,desktop/desktop,shiftkey/desktop,j-f1/forked-desktop,artivilla/desktop,artivilla/desktop,say25/desktop,j-f1/forked-desktop,artivilla/desktop,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,kactus-io/kactus,shiftkey/desktop,desktop/desktop,shiftkey/desktop,artivilla/desktop,desktop/desktop,j-f1/forked-desktop,shiftkey/desktop,say25/desktop,say25/desktop,kactus-io/kactus
--- +++ @@ -9,7 +9,7 @@ } export class Banner extends React.Component<IBannerProps, {}> { - private timeoutId: NodeJS.Timer | null = null + private timeoutId: number | null = null public render() { return ( @@ -37,7 +37,7 @@ public componentDidMount = () => { if (this.props.timeout !== undefined) { - this.timeoutId = setTimeout(() => { + this.timeoutId = window.setTimeout(() => { this.props.onDismissed() }, this.props.timeout) } @@ -45,7 +45,7 @@ public componentWillUnmount = () => { if (this.props.timeout !== undefined && this.timeoutId !== null) { - clearTimeout(this.timeoutId) + window.clearTimeout(this.timeoutId) } } }
344d472f70b9fc3976852baa03381278ab3c6981
spec/api/APIv2.spec.ts
spec/api/APIv2.spec.ts
/// <reference path="../../typings/jasmine/jasmine.d.ts" /> /// <reference path="../../typings/when/when.d.ts" /> import * as when from "when"; import {APIv2, IAPINavIm} from "../../src/API"; describe("APIv2", () => { var apiV2: APIv2; beforeEach(() => { apiV2 = new APIv2("clientId") }); it("exists", () => { expect(apiV2).toBeDefined(); }); it("calls h", (done) => { spyOn(apiV2.nav, "callApi").and.returnValue(when(null)); let h: string = "hash"; apiV2.nav.h(h).then((response: IAPINavIm) => { expect(apiV2.nav.callApi).toHaveBeenCalledWith("nav/h/" + h); done(); }); }); it("calls im", (done) => { spyOn(apiV2.nav, "callApi").and.returnValue(when(null)); let im: string = "key"; apiV2.nav.im(im).then((response: IAPINavIm) => { expect(apiV2.nav.callApi).toHaveBeenCalledWith("nav/im/" + im); done(); }); }); });
/// <reference path="../../typings/jasmine/jasmine.d.ts" /> /// <reference path="../../typings/when/when.d.ts" /> import * as when from "when"; import {APIv2, IAPINavIm, IAPIImOr} from "../../src/API"; describe("APIv2", () => { var apiV2: APIv2; beforeEach(() => { apiV2 = new APIv2("clientId") }); it("exists", () => { expect(apiV2).toBeDefined(); }); it("calls im or", (done) => { spyOn(apiV2.im, "callApi").and.returnValue(when(null)); let im: string = "key"; apiV2.im.callOr(im).then((response: IAPIImOr) => { expect(apiV2.im.callApi).toHaveBeenCalledWith("im/" + im + "/or"); done(); }); }); it("calls nav h", (done) => { spyOn(apiV2.nav, "callApi").and.returnValue(when(null)); let h: string = "hash"; apiV2.nav.h(h).then((response: IAPINavIm) => { expect(apiV2.nav.callApi).toHaveBeenCalledWith("nav/h/" + h); done(); }); }); it("calls nav im", (done) => { spyOn(apiV2.nav, "callApi").and.returnValue(when(null)); let im: string = "key"; apiV2.nav.im(im).then((response: IAPINavIm) => { expect(apiV2.nav.callApi).toHaveBeenCalledWith("nav/im/" + im); done(); }); }); });
Test that API im or is called correctly.
Test that API im or is called correctly.
TypeScript
mit
mapillary/mapillary-js,mapillary/mapillary-js
--- +++ @@ -3,7 +3,7 @@ import * as when from "when"; -import {APIv2, IAPINavIm} from "../../src/API"; +import {APIv2, IAPINavIm, IAPIImOr} from "../../src/API"; describe("APIv2", () => { var apiV2: APIv2; @@ -16,7 +16,18 @@ expect(apiV2).toBeDefined(); }); - it("calls h", (done) => { + it("calls im or", (done) => { + spyOn(apiV2.im, "callApi").and.returnValue(when(null)); + + let im: string = "key"; + apiV2.im.callOr(im).then((response: IAPIImOr) => { + expect(apiV2.im.callApi).toHaveBeenCalledWith("im/" + im + "/or"); + + done(); + }); + }); + + it("calls nav h", (done) => { spyOn(apiV2.nav, "callApi").and.returnValue(when(null)); let h: string = "hash"; @@ -27,7 +38,7 @@ }); }); - it("calls im", (done) => { + it("calls nav im", (done) => { spyOn(apiV2.nav, "callApi").and.returnValue(when(null)); let im: string = "key";
114ebb69497a5a6fdc004334c1b81d6006a3a3ac
app/components/resources/state/resources-view-state.ts
app/components/resources/state/resources-view-state.ts
import {IdaiFieldDocument} from 'idai-components-2/idai-field-model'; import {NavigationPathInternal} from './navigation-path-internal'; /** * @author Thomas Kleinke */ export interface ResourcesViewState { mainTypeDocument?: IdaiFieldDocument; types?: string[]; // query types in overview q: string; // query string in overview layerIds: {[mainTypeDocumentId: string]: string[]}; navigationPaths: {[mainTypeDocumentId: string]: NavigationPathInternal}; } export class ResourcesViewState { public static default() { return { q: '', mode: 'map', navigationPaths: {}, layerIds: {} }; }; public static complete(viewState: ResourcesViewState) { if (!viewState.layerIds) viewState.layerIds = {}; viewState.navigationPaths = {}; viewState.q = ''; } }
import {IdaiFieldDocument} from 'idai-components-2/idai-field-model'; import {NavigationPathInternal} from './navigation-path-internal'; /** * @author Thomas Kleinke */ export interface ResourcesViewState { mainTypeDocument?: IdaiFieldDocument; types?: string[]; // query types in overview q: string; // query string in overview layerIds: {[mainTypeDocumentId: string]: string[]}; navigationPaths: {[mainTypeDocumentId: string]: NavigationPathInternal}; } export class ResourcesViewState { public static default() { return { q: '', mode: 'map', navigationPaths: {}, layerIds: {} }; }; public static complete(viewState: ResourcesViewState) { if (!viewState.layerIds || Array.isArray(viewState.layerIds)) { viewState.layerIds = {}; } viewState.navigationPaths = {}; viewState.q = ''; } }
Check layerIds for wrong type
Check layerIds for wrong type
TypeScript
apache-2.0
codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client
--- +++ @@ -30,7 +30,10 @@ public static complete(viewState: ResourcesViewState) { - if (!viewState.layerIds) viewState.layerIds = {}; + if (!viewState.layerIds || Array.isArray(viewState.layerIds)) { + viewState.layerIds = {}; + } + viewState.navigationPaths = {}; viewState.q = ''; }
dab981de5a27e1fc81946ec1cdfa5f042763f40c
src/Parsing/Outline/OutlineParserArgs.ts
src/Parsing/Outline/OutlineParserArgs.ts
import { OutlineSyntaxNode } from '../../SyntaxNodes/OutlineSyntaxNode' import { HeadingLeveler } from './HeadingLeveler' import { UpConfig } from '../../UpConfig' export interface OutlineParserArgs { text: string headingLeveler: HeadingLeveler config: UpConfig then: (resultNodes: OutlineSyntaxNode[], lengthParsed: number) => void }
import { OutlineSyntaxNode } from '../../SyntaxNodes/OutlineSyntaxNode' import { LineConsumer } from './LineConsumer' import { HeadingLeveler } from './HeadingLeveler' import { UpConfig } from '../../UpConfig' export interface OutlineParserArgs { consumer: LineConsumer headingLeveler: HeadingLeveler config: UpConfig then: (resultNodes: OutlineSyntaxNode[], lengthParsed: number) => void }
Make outline parsers accept LineConsumers
[Broken] Make outline parsers accept LineConsumers
TypeScript
mit
start/up,start/up
--- +++ @@ -1,10 +1,11 @@ import { OutlineSyntaxNode } from '../../SyntaxNodes/OutlineSyntaxNode' +import { LineConsumer } from './LineConsumer' import { HeadingLeveler } from './HeadingLeveler' import { UpConfig } from '../../UpConfig' export interface OutlineParserArgs { - text: string + consumer: LineConsumer headingLeveler: HeadingLeveler config: UpConfig then: (resultNodes: OutlineSyntaxNode[], lengthParsed: number) => void
ac1caa79abc2be43881b248e2292ed5385843e8e
src/utils/returnHit.ts
src/utils/returnHit.ts
import axios from 'axios'; import { API_URL } from '../constants'; import { stringToDomElement } from './parsing'; export const sendReturnHitRequest = async (hitId: string) => { try { const response = await axios.get( `${API_URL}/mturk/return?hitId=${hitId}&inPipeline=false` ); const rawHtml: string = response.data; return validateHitReturn(rawHtml); } catch (e) { return 'error'; } }; export type HitReturnStatus = 'repeat' | 'success' | 'error'; const validateHitReturn = (html: string): HitReturnStatus => { const table = stringToDomElement(html); const alertBox = table.querySelector('#alertboxHeader') return !!alertBox ? validateAlertBoxText(alertBox) : 'error'; }; const validateAlertBoxText = (el: Element | undefined): HitReturnStatus => { if (el === undefined) { return 'error'; } const text = (el as HTMLSpanElement).innerText.trim(); switch (text) { case 'The HIT has been returned.': return 'success'; case 'You have already returned this HIT.': return 'repeat'; default: return 'error'; } };
import axios from 'axios'; import { API_URL } from '../constants'; import { stringToDomElement } from './parsing'; export const sendReturnHitRequest = async (hitId: string) => { try { const response = await axios.get( `${API_URL}/mturk/return?hitId=${hitId}&inPipeline=false` ); const rawHtml: string = response.data; return validateHitReturn(rawHtml); } catch (e) { return 'error'; } }; export type HitReturnStatus = 'repeat' | 'success' | 'error'; const validateHitReturn = (html: string): HitReturnStatus => { const table = stringToDomElement(html); const noAssignedHitsContainer = table.querySelector('td.error_title'); if (!!noAssignedHitsContainer) { return 'success'; } const alertBox = table.querySelector('#alertboxHeader'); return !!alertBox ? validateAlertBoxText(alertBox) : 'error'; }; const validateAlertBoxText = (el: Element | undefined): HitReturnStatus => { if (el === undefined) { return 'error'; } const text = (el as HTMLSpanElement).innerText.trim(); switch (text) { case 'The HIT has been returned.': return 'success'; case 'You have already returned this HIT.': return 'repeat'; default: return 'error'; } };
Fix issue of returning the last HIT in a queue displaying an error.
Fix issue of returning the last HIT in a queue displaying an error.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -18,7 +18,13 @@ const validateHitReturn = (html: string): HitReturnStatus => { const table = stringToDomElement(html); - const alertBox = table.querySelector('#alertboxHeader') + const noAssignedHitsContainer = table.querySelector('td.error_title'); + + if (!!noAssignedHitsContainer) { + return 'success'; + } + + const alertBox = table.querySelector('#alertboxHeader'); return !!alertBox ? validateAlertBoxText(alertBox) : 'error'; };
2bad14b0ade7fd94ef549401e609b3167bb1aa5c
src/models/helpers/sbg-expression-lib.ts
src/models/helpers/sbg-expression-lib.ts
export const sbgHelperLibrary = ` var setMetadata = function(file, metadata) { if (!('metadata' in file)) file['metadata'] = metadata; else { for (var key in metadata) { file['metadata'][key] = metadata[key]; } } return file }; var inheritMetadata = function(o1, o2) { var commonMetadata = {}; if (!Array.isArray(o2)) { o2 = [o2] } for (var i = 0; i < o2.length; i++) { var example = o2[i]['metadata']; for (var key in example) { if (i == 0) commonMetadata[key] = example[key]; else { if (!(commonMetadata[key] == example[key])) { delete commonMetadata[key] } } } } if (!Array.isArray(o1)) { o1 = setMetadata(o1, commonMetadata) } else { for (var i = 0; i < o1.length; i++) { o1[i] = setMetadata(o1[i], commonMetadata) } } return o1; };`;
export const sbgHelperLibrary = ` var setMetadata = function(file, metadata) { if (!('metadata' in file)) { file['metadata'] = {} } for (var key in metadata) { file['metadata'][key] = metadata[key]; } return file }; var inheritMetadata = function(o1, o2) { var commonMetadata = {}; if (!Array.isArray(o2)) { o2 = [o2] } for (var i = 0; i < o2.length; i++) { var example = o2[i]['metadata']; for (var key in example) { if (i == 0) commonMetadata[key] = example[key]; else { if (!(commonMetadata[key] == example[key])) { delete commonMetadata[key] } } } } if (!Array.isArray(o1)) { o1 = setMetadata(o1, commonMetadata) } else { for (var i = 0; i < o1.length; i++) { o1[i] = setMetadata(o1[i], commonMetadata) } } return o1; };`;
Fix inheriting metadata in array outputs
Fix inheriting metadata in array outputs
TypeScript
apache-2.0
rabix/cwl-ts,rabix/cwl-ts,rabix/cwl-ts
--- +++ @@ -1,11 +1,10 @@ export const sbgHelperLibrary = ` var setMetadata = function(file, metadata) { - if (!('metadata' in file)) - file['metadata'] = metadata; - else { - for (var key in metadata) { - file['metadata'][key] = metadata[key]; - } + if (!('metadata' in file)) { + file['metadata'] = {} + } + for (var key in metadata) { + file['metadata'][key] = metadata[key]; } return file };
9aa4bb66f2cb494b53b0021c1ef7ae3ae0224e1c
src/ts/view/counter.ts
src/ts/view/counter.ts
namespace YJMCNT { /** * CounterView */ export class CounterView extends Core.View { counter:Counter; constructor() { super(); this.counter = new Counter(); this.counter.addObserver(this); } render() { var counter = document.createElement("div"); var countView = document.createElement("span"); countView.classList.add("count"); countView.innerText = "count: "+this.counter.show().toString(); var countUpButton:HTMLButtonElement = document.createElement("button"); countUpButton.innerHTML = "Up"; countUpButton.classList.add("countUp"); counter.appendChild(countView); counter.appendChild(countUpButton); return counter; } update() { this.notifyObservers(); } } }
namespace YJMCNT { /** * CounterView */ export class CounterView extends Core.View { counter:Counter; constructor() { super(); this.counter = new Counter(); this.counter.addObserver(this); } render() { var counter = document.createElement("div"); var countView = document.createElement("span"); countView.classList.add("count"); countView.innerText = "count: "+this.counter.show().toString(); var countUpButton:HTMLButtonElement = document.createElement("button"); countUpButton.innerHTML = "Up"; countUpButton.classList.add("countUp"); var countDownButton:HTMLButtonElement = document.createElement("button"); countDownButton.innerHTML = "Down"; countDownButton.classList.add("countDown"); counter.appendChild(countView); counter.appendChild(countUpButton); counter.appendChild(countDownButton); return counter; } update() { this.notifyObservers(); } } }
Add count down button (not work)
Add count down button (not work)
TypeScript
mit
yajamon/chrome-ext-counter,yajamon/chrome-ext-counter,yajamon/chrome-ext-counter
--- +++ @@ -20,8 +20,13 @@ countUpButton.innerHTML = "Up"; countUpButton.classList.add("countUp"); + var countDownButton:HTMLButtonElement = document.createElement("button"); + countDownButton.innerHTML = "Down"; + countDownButton.classList.add("countDown"); + counter.appendChild(countView); counter.appendChild(countUpButton); + counter.appendChild(countDownButton); return counter; } update() {
49b792d1ad98a51d5930df48cda8e5734c5781ec
ui/src/app/runtime/model/runtime-app.ts
ui/src/app/runtime/model/runtime-app.ts
import { RuntimeAppInstance } from './runtime-app-instance'; import { Page } from '../../shared/model'; /** * Runtime application model that corresponds to AppStatusResource from SCDF server. * * @author Ilayaperumal Gopinathan */ export class RuntimeApp { public deploymentId: string; public state: string; public instances: any; public appInstances: any; constructor(deploymentId: string, state: string, instances: any, appInstances: RuntimeAppInstance[]) { this.deploymentId = deploymentId; this.state = state; this.instances = instances; this.appInstances = appInstances; } public static fromJSON(input): RuntimeApp { let instances = []; if (input.instances._embedded.appInstanceStatusResourceList) { instances = input.instances._embedded.appInstanceStatusResourceList; } return new RuntimeApp(input.deploymentId, input.state, input.instances, instances); } public static pageFromJSON(input): Page<RuntimeApp> { const page = Page.fromJSON<RuntimeApp>(input); if (input && input._embedded && input._embedded.appStatusResourceList) { page.items = input._embedded.appStatusResourceList.map((item) => { if (!!item.instances._embedded && !!item.instances._embedded.appInstanceStatusResourceList) { item.appInstances = item.instances._embedded.appInstanceStatusResourceList; } else { item.appInstances = []; } return item; }); } return page; } }
import { RuntimeAppInstance } from './runtime-app-instance'; import { Page } from '../../shared/model'; /** * Runtime application model that corresponds to AppStatusResource from SCDF server. * * @author Ilayaperumal Gopinathan */ export class RuntimeApp { public deploymentId: string; public state: string; public instances: any; public appInstances: any; constructor(deploymentId: string, state: string, instances: any, appInstances: RuntimeAppInstance[]) { this.deploymentId = deploymentId; this.state = state; this.instances = instances; this.appInstances = appInstances; } public static fromJSON(input): RuntimeApp { let instances = []; if (!!input.instances && !!input.instances._embedded && !!input.instances._embedded.appInstanceStatusResourceList) { instances = input.instances._embedded.appInstanceStatusResourceList; } return new RuntimeApp(input.deploymentId, input.state, input.instances, instances); } public static pageFromJSON(input): Page<RuntimeApp> { const page = Page.fromJSON<RuntimeApp>(input); if (input && input._embedded && input._embedded.appStatusResourceList) { page.items = input._embedded.appStatusResourceList.map((item) => { if (!!item.instances && !!item.instances._embedded && !!item.instances._embedded.appInstanceStatusResourceList) { item.appInstances = item.instances._embedded.appInstanceStatusResourceList; } else { item.appInstances = []; } return item; }); } return page; } }
Update runtime app model parsing
Update runtime app model parsing
TypeScript
apache-2.0
BoykoAlex/spring-cloud-dataflow-ui,cppwfs/spring-cloud-dataflow-ui,cppwfs/spring-cloud-dataflow-ui,BoykoAlex/spring-cloud-dataflow-ui,spring-cloud/spring-cloud-dataflow-ui,spring-cloud/spring-cloud-dataflow-ui,cppwfs/spring-cloud-dataflow-ui,cppwfs/spring-cloud-dataflow-ui,spring-cloud/spring-cloud-dataflow-ui,spring-cloud/spring-cloud-dataflow-ui,BoykoAlex/spring-cloud-dataflow-ui,BoykoAlex/spring-cloud-dataflow-ui
--- +++ @@ -25,7 +25,7 @@ public static fromJSON(input): RuntimeApp { let instances = []; - if (input.instances._embedded.appInstanceStatusResourceList) { + if (!!input.instances && !!input.instances._embedded && !!input.instances._embedded.appInstanceStatusResourceList) { instances = input.instances._embedded.appInstanceStatusResourceList; } return new RuntimeApp(input.deploymentId, input.state, input.instances, instances); @@ -35,7 +35,7 @@ const page = Page.fromJSON<RuntimeApp>(input); if (input && input._embedded && input._embedded.appStatusResourceList) { page.items = input._embedded.appStatusResourceList.map((item) => { - if (!!item.instances._embedded && !!item.instances._embedded.appInstanceStatusResourceList) { + if (!!item.instances && !!item.instances._embedded && !!item.instances._embedded.appInstanceStatusResourceList) { item.appInstances = item.instances._embedded.appInstanceStatusResourceList; } else { item.appInstances = [];
fe984c25c2ae2ea8d21e5fc65dd89ac93c6494b7
front/components/store/reducers/index.ts
front/components/store/reducers/index.ts
import * as Actions from '../actions/types'; import ActionType = Actions.ActionType; export default function reduce(state: AppState = { containers: [], hosts: [] }, action: ActionType): AppState { switch (action.type) { case 'add-container': return Object.assign( {}, state, { containers: [...state.containers, action.container] } ) case 'add-host': return Object.assign( {}, state, { hosts: [...state.hosts, action.host] } ) case 'remove-host': return Object.assign( {}, state, { hosts: state.hosts.filter(c => c.id !== action.id) } ) case 'remove-container': return Object.assign( {}, state, { containers: state.containers.filter(c => c.id !== action.id) } ) default: return state; } }
import * as Actions from '../actions/types'; import ActionType = Actions.ActionType; export default function reduce(state: AppState = { containers: [], hosts: [] }, action: ActionType): AppState { switch (action.type) { case 'add-container': return Object.assign( {}, state, { containers: addEntity(state.containers, action.container) } ); case 'add-host': return Object.assign( {}, state, { hosts: addEntity(state.hosts, action.host) } ); case 'remove-host': return Object.assign( {}, state, { hosts: state.hosts.filter(c => c.id !== action.id) } ); case 'remove-container': return Object.assign( {}, state, { containers: state.containers.filter(c => c.id !== action.id) } ); default: return state; } } type Id = { id?: string | number } /** * Destructive * Add or update */ function addEntity<T extends Id>(entities: Array<T>, entity: T) { const existing = entities.find(c => c.id === entity.id); if (existing) { Object.assign(existing, entity); return entities; } return entities.concat(entity); } function removeEntity<T extends Id>(state: AppState, entities: Array<T>, entityId: string | number) { const filtered = entities.filter(entity => entity.id !== entityId); return filtered; }
Update entity if already exists in store
Update entity if already exists in store
TypeScript
mit
paypac/node-concierge,paypac/node-concierge,the-concierge/concierge,the-concierge/concierge,paypac/node-concierge,paypac/node-concierge,the-concierge/concierge
--- +++ @@ -7,27 +7,51 @@ return Object.assign( {}, state, - { containers: [...state.containers, action.container] } - ) + { containers: addEntity(state.containers, action.container) } + ); + case 'add-host': return Object.assign( {}, state, - { hosts: [...state.hosts, action.host] } - ) + { hosts: addEntity(state.hosts, action.host) } + ); + case 'remove-host': return Object.assign( {}, state, { hosts: state.hosts.filter(c => c.id !== action.id) } - ) + ); + case 'remove-container': return Object.assign( {}, state, { containers: state.containers.filter(c => c.id !== action.id) } - ) + ); + default: return state; } } + +type Id = { id?: string | number } + +/** + * Destructive + * Add or update + */ +function addEntity<T extends Id>(entities: Array<T>, entity: T) { + const existing = entities.find(c => c.id === entity.id); + if (existing) { + Object.assign(existing, entity); + return entities; + } + return entities.concat(entity); +} + +function removeEntity<T extends Id>(state: AppState, entities: Array<T>, entityId: string | number) { + const filtered = entities.filter(entity => entity.id !== entityId); + return filtered; +}
ae18815f96933a7fcf98dda9ac7ea0de2ef22cba
src/app/core/error-handler/app-error-handler.service.ts
src/app/core/error-handler/app-error-handler.service.ts
import { Injectable, ErrorHandler } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import { environment } from '@env/environment'; import { NotificationService } from '../notifications/notification.service'; import { NotificationStyles } from '../notifications/notification-styles'; /** Application-wide error handler that adds a UI notification to the error handling * provided by the default Angular ErrorHandler. */ @Injectable() export class AppErrorHandler extends ErrorHandler { constructor(private notificationsService: NotificationService) { super(); } handleError(error: Error | HttpErrorResponse) { let displayMessage = 'An error occurred.'; if (!environment.production) { displayMessage += ' See console for details.'; } this.notificationsService.error(displayMessage); super.handleError(error); } }
import { Injectable, ErrorHandler } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import { environment } from '@env/environment'; import { NotificationService } from '../notifications/notification.service'; /** Application-wide error handler that adds a UI notification to the error handling * provided by the default Angular ErrorHandler. */ @Injectable() export class AppErrorHandler extends ErrorHandler { constructor(private notificationsService: NotificationService) { super(); } handleError(error: Error | HttpErrorResponse) { let displayMessage = 'An error occurred.'; if (!environment.production) { displayMessage += ' See console for details.'; } this.notificationsService.error(displayMessage); super.handleError(error); } }
Remove non existing import NotificationStyles
fix: Remove non existing import NotificationStyles Remove a non existing import in the error handler service for NotificationStyles. Can cause an error when typescript compiling the application.
TypeScript
mit
tomastrajan/angular-ngrx-material-starter,tomastrajan/angular-ngrx-material-starter,tomastrajan/angular-ngrx-material-starter,tomastrajan/angular-ngrx-material-starter
--- +++ @@ -2,7 +2,6 @@ import { HttpErrorResponse } from '@angular/common/http'; import { environment } from '@env/environment'; import { NotificationService } from '../notifications/notification.service'; -import { NotificationStyles } from '../notifications/notification-styles'; /** Application-wide error handler that adds a UI notification to the error handling * provided by the default Angular ErrorHandler.
4264ecfadc997194d47df4724f922f242c044b20
test/test-no-metadata.ts
test/test-no-metadata.ts
import {assert} from 'chai'; import * as mm from '../src'; import * as path from 'path'; const t = assert; it("should reject files that can't be parsed", async () => { const filePath = path.join(__dirname, 'samples', __filename); // Run with default options try { await mm.parseFile(filePath); assert.fail('Should reject a file which cannot be parsed'); } catch(err) { assert.isDefined(err); assert.isDefined(err.message); } });
import {assert} from 'chai'; import * as mm from '../src'; import * as path from 'path'; it("should reject files that can't be parsed", async () => { const filePath = path.join(__dirname, 'samples', __filename); // Run with default options try { await mm.parseFile(filePath); assert.fail('Should reject a file which cannot be parsed'); } catch (err) { assert.isDefined(err); assert.isDefined(err.message); } });
Remove unused import & fix lint error
Remove unused import & fix lint error
TypeScript
mit
Borewit/music-metadata,Borewit/music-metadata
--- +++ @@ -1,8 +1,6 @@ import {assert} from 'chai'; import * as mm from '../src'; import * as path from 'path'; - -const t = assert; it("should reject files that can't be parsed", async () => { @@ -12,7 +10,7 @@ try { await mm.parseFile(filePath); assert.fail('Should reject a file which cannot be parsed'); - } catch(err) { + } catch (err) { assert.isDefined(err); assert.isDefined(err.message); }
f254b169fd0c6d2682d68a4cc4b6a00332ba38ef
polygerrit-ui/app/styles/gr-icon-styles.ts
polygerrit-ui/app/styles/gr-icon-styles.ts
/** * @license * Copyright 2022 Google LLC * SPDX-License-Identifier: Apache-2.0 */ import {css} from 'lit'; export const iconStyles = css` iron-icon { display: inline-block; vertical-align: top; width: 20px; height: 20px; } /* expected to be used in a 20px line-height inline context */ iron-icon.size-16 { width: 16px; height: 16px; position: relative; top: 2px; } .material-icon { color: var(--deemphasized-text-color); font-family: 'Material Symbols Outlined'; font-weight: normal; font-style: normal; font-size: 20px; line-height: 1; letter-spacing: normal; text-transform: none; display: inline-block; white-space: nowrap; word-wrap: normal; direction: ltr; font-variation-settings: 'FILL' 0; vertical-align: top; } .material-icon.filled { font-variation-settings: 'FILL' 1; } `;
/** * @license * Copyright 2022 Google LLC * SPDX-License-Identifier: Apache-2.0 */ import {css} from 'lit'; export const iconStyles = css` iron-icon { display: inline-block; vertical-align: top; width: 20px; height: 20px; } /* expected to be used in a 20px line-height inline context */ iron-icon.size-16 { width: 16px; height: 16px; position: relative; top: 2px; } .material-icon { color: var(--deemphasized-text-color); font-family: var(--icon-font-family, 'Material Symbols Outlined'); font-weight: normal; font-style: normal; font-size: 20px; line-height: 1; letter-spacing: normal; text-transform: none; display: inline-block; white-space: nowrap; word-wrap: normal; direction: ltr; font-variation-settings: 'FILL' 0; vertical-align: top; } .material-icon.filled { font-variation-settings: 'FILL' 1; } `;
Make the icon-font-family for icons be a CSS var.
Make the icon-font-family for icons be a CSS var. This is necessary for our internal tool as it uses a different font-family. Release-Notes: skip Change-Id: I65c404387804a246539c41ef9d01f0208176db48
TypeScript
apache-2.0
GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit
--- +++ @@ -22,7 +22,7 @@ .material-icon { color: var(--deemphasized-text-color); - font-family: 'Material Symbols Outlined'; + font-family: var(--icon-font-family, 'Material Symbols Outlined'); font-weight: normal; font-style: normal; font-size: 20px;
b9c64ef470c645c045f6390438c4e6c27554aef1
ts/editor/loadAce.ts
ts/editor/loadAce.ts
import * as fs from 'fs'; let path = 'node_modules/ace-builds/src-noconflict/ace.js'; try { fs.accessSync(path); } catch (e) { // rethrow if no min fs.accessSync(path = 'node_modules/ace-builds/src-min-noconflict/ace.js'); } const script = document.createElement('script'); script.src = path; document.body.appendChild(script);
import * as fs from 'fs'; let path = 'node_modules/ace-builds/src-noconflict/ace.js'; try { fs.accessSync(path); } catch (e) { path = 'node_modules/ace-builds/src-min-noconflict/ace.js'; } const script = document.createElement('script'); script.src = path; document.body.appendChild(script);
Fix error loading ace when in production
Fix error loading ace when in production
TypeScript
mit
qsctr/java-editor,qsctr/java-editor,qsctr/java-editor
--- +++ @@ -5,8 +5,7 @@ try { fs.accessSync(path); } catch (e) { - // rethrow if no min - fs.accessSync(path = 'node_modules/ace-builds/src-min-noconflict/ace.js'); + path = 'node_modules/ace-builds/src-min-noconflict/ace.js'; } const script = document.createElement('script');
e2d6282934ecdc2d5a0096cd329663169e40335c
ui/src/SearchBar.tsx
ui/src/SearchBar.tsx
import React, { FormEvent, CSSProperties } from 'react'; import InputGroup from 'react-bootstrap/InputGroup'; import FormControl from 'react-bootstrap/FormControl'; import Button from 'react-bootstrap/Button'; import Form from 'react-bootstrap/Form'; import Icon from '@mdi/react'; import { mdiMagnify } from '@mdi/js'; const inputGroupStyle: CSSProperties = { zIndex: 1, position: 'absolute', width: '300px', margin: '1em' } export default ({ onSubmit }: { onSubmit: (query: string) => void}) => { let query = ''; const submit = (event: FormEvent) => { event.preventDefault(); onSubmit(query); } return ( <Form onSubmit={submit}> <InputGroup style={inputGroupStyle}> <FormControl autoFocus placeholder="Suchen ..." aria-label="Suchbegriff" onChange={(event: any) => query = event.target.value} /> <InputGroup.Append> <Button variant="secondary" type="submit"> <Icon path={mdiMagnify} size={0.8}/> </Button> </InputGroup.Append> </InputGroup> </Form> ); }
import React, { useState, FormEvent, CSSProperties } from 'react'; import InputGroup from 'react-bootstrap/InputGroup'; import FormControl from 'react-bootstrap/FormControl'; import Button from 'react-bootstrap/Button'; import Form from 'react-bootstrap/Form'; import Icon from '@mdi/react'; import { mdiMagnify } from '@mdi/js'; const inputGroupStyle: CSSProperties = { zIndex: 1, position: 'absolute', width: '300px', margin: '1em' } export default ({ onSubmit }: { onSubmit: (query: string) => void}) => { const [query, setQuery] = useState(''); const submit = (event: FormEvent) => { event.preventDefault(); onSubmit(query); } return ( <Form onSubmit={submit}> <InputGroup style={inputGroupStyle}> <FormControl autoFocus placeholder="Suchen ..." aria-label="Suchbegriff" onChange={(event: any) => setQuery(event.target.value)} /> <InputGroup.Append> <Button variant="secondary" type="submit"> <Icon path={mdiMagnify} size={0.8}/> </Button> </InputGroup.Append> </InputGroup> </Form> ); }
Move query to state again
Move query to state again Using a function scope variable caused strange effects for example when resending the form
TypeScript
apache-2.0
dainst/idai-field-web,dainst/idai-field-web,dainst/idai-field-web
--- +++ @@ -1,4 +1,4 @@ -import React, { FormEvent, CSSProperties } from 'react'; +import React, { useState, FormEvent, CSSProperties } from 'react'; import InputGroup from 'react-bootstrap/InputGroup'; import FormControl from 'react-bootstrap/FormControl'; import Button from 'react-bootstrap/Button'; @@ -17,7 +17,7 @@ export default ({ onSubmit }: { onSubmit: (query: string) => void}) => { - let query = ''; + const [query, setQuery] = useState(''); const submit = (event: FormEvent) => { event.preventDefault(); @@ -31,7 +31,7 @@ autoFocus placeholder="Suchen ..." aria-label="Suchbegriff" - onChange={(event: any) => query = event.target.value} + onChange={(event: any) => setQuery(event.target.value)} /> <InputGroup.Append> <Button variant="secondary" type="submit">
7845f2936e41b5dd33ed94924c8bd1e9f608d9b2
src/extension/safari-extension/Routes.tsx
src/extension/safari-extension/Routes.tsx
import React from 'react' import { Switch, Route } from 'react-router-dom' import ExtensionLogin from 'extension/src/components/ExtensionLogin' import Blocks from 'v2/components/Bookmarklet/components/Blocks' import EditBlock from 'v2/components/Bookmarklet/components/EditBlock' import Extension from 'v2/components/Bookmarklet/components/Extension' import withLoginStatus from 'v2/hocs/WithLoginStatus' interface RoutesProps { isLoggedIn: boolean } const Routes: React.FC<RoutesProps> = ({ isLoggedIn }) => ( <Extension> <Switch> {!isLoggedIn && <Route path="/" component={ExtensionLogin} />} {isLoggedIn && ( <React.Fragment> <Route path="/edit" component={EditBlock} /> <Route path="/" render={() => <Blocks isSafari />} /> </React.Fragment> )} </Switch> </Extension> ) export default withLoginStatus(Routes)
import React from 'react' import { Switch, Route } from 'react-router-dom' import ExtensionLogin from 'extension/src/components/ExtensionLogin' import Blocks from 'v2/components/Bookmarklet/components/Blocks' import EditBlock from 'v2/components/Bookmarklet/components/EditBlock' import Extension from 'v2/components/Bookmarklet/components/Extension' import withLoginStatus from 'v2/hocs/WithLoginStatus' interface RoutesProps { isLoggedIn: boolean } const Routes: React.FC<RoutesProps> = ({ isLoggedIn }) => ( <Extension> <Switch> {!isLoggedIn && <Route path="/" component={ExtensionLogin} />} {isLoggedIn && ( <React.Fragment> <Route path="/edit" render={() => <EditBlock isSafari />} /> <Route path="/" render={renderProps => { // We manually have to check this here because the // initial safari extension pathname is always // randomized if (renderProps.location.pathname !== '/edit') { return <Blocks isSafari /> } return null }} /> </React.Fragment> )} </Switch> </Extension> ) export default withLoginStatus(Routes)
Fix route for edit block
Fix route for edit block
TypeScript
mit
aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell
--- +++ @@ -19,8 +19,20 @@ {isLoggedIn && ( <React.Fragment> - <Route path="/edit" component={EditBlock} /> - <Route path="/" render={() => <Blocks isSafari />} /> + <Route path="/edit" render={() => <EditBlock isSafari />} /> + <Route + path="/" + render={renderProps => { + // We manually have to check this here because the + // initial safari extension pathname is always + // randomized + if (renderProps.location.pathname !== '/edit') { + return <Blocks isSafari /> + } + + return null + }} + /> </React.Fragment> )} </Switch>
d5ee7dc00342fdefb12fcea0aa7ed2f9c10463c0
source/services/guid/guid.service.ts
source/services/guid/guid.service.ts
import { OpaqueToken, Provider } from '@angular/core'; import * as uuid from 'uuid'; export interface IGuidService { time(): string; random(): string; } class GuidService implements IGuidService { time(): string { return uuid.v1(); } random(): string { return uuid.v4(); } } export const guid: IGuidService = new GuidService(); export const guidToken: OpaqueToken = new OpaqueToken('Service for generating guids'); export const GUID_PROVIDER: Provider = new Provider(guidToken, { useClass: GuidService, });
import { OpaqueToken, Provider } from '@angular/core'; import * as uuid from 'node-uuid'; export interface IGuidService { time(): string; random(): string; } class GuidService implements IGuidService { time(): string { return uuid.v1(); } random(): string { return uuid.v4(); } } export const guid: IGuidService = new GuidService(); export const guidToken: OpaqueToken = new OpaqueToken('Service for generating guids'); export const GUID_PROVIDER: Provider = new Provider(guidToken, { useClass: GuidService, });
Use node-uuid to eliminate the dependency on crypto (node)
Use node-uuid to eliminate the dependency on crypto (node)
TypeScript
mit
RenovoSolutions/TypeScript-Angular-Utilities,SamGraber/TypeScript-Angular-Utilities,SamGraber/TypeScript-Angular-Utilities,RenovoSolutions/TypeScript-Angular-Utilities
--- +++ @@ -1,6 +1,6 @@ import { OpaqueToken, Provider } from '@angular/core'; -import * as uuid from 'uuid'; +import * as uuid from 'node-uuid'; export interface IGuidService { time(): string;
3f4763cefd5e8b040e4623b1521c12bedf17571e
src/app/index.tsx
src/app/index.tsx
// This is the entry point for the renderer process. // // Here we disable a few electron settings and mount the root component. import React from "react" import ReactDOM from "react-dom" import { AppLayout as RootComponent } from "./root-component" import { webFrame } from "electron" import { css } from "glamor" /** * CSS reset */ import "glamor/reset" /** * Electron-focused CSS resets */ css.global("html, body", { // turn off text highlighting userSelect: "none", // reset the cursor pointer cursor: "default", // font font: "caption", // text rendering WebkitFontSmoothing: "subpixel-antialiased", textRendering: "optimizeLegibility", }) /** * Zooming resets */ webFrame.setVisualZoomLevelLimits(1, 1) webFrame.setLayoutZoomLevelLimits(0, 0) /** * Drag and drop resets */ document.addEventListener("dragover", event => event.preventDefault()) document.addEventListener("drop", event => event.preventDefault()) // mount the root component import "../styles/uikit.css" ReactDOM.render(<RootComponent />, document.getElementById("root"), () => {})
// This is the entry point for the renderer process. // // Here we disable a few electron settings and mount the root component. import React from "react" import ReactDOM from "react-dom" import { AppLayout as RootComponent } from "./root-component" import { webFrame } from "electron" /** * CSS reset */ /** * Electron-focused CSS resets */ /** * Zooming resets */ webFrame.setVisualZoomLevelLimits(1, 1) webFrame.setLayoutZoomLevelLimits(0, 0) /** * Drag and drop resets */ document.addEventListener("dragover", event => event.preventDefault()) document.addEventListener("drop", event => event.preventDefault()) // mount the root component ReactDOM.render(<RootComponent />, document.getElementById("root"), () => {})
Remove CSS resets in renderer
Remove CSS resets in renderer
TypeScript
agpl-3.0
briandk/transcriptase,briandk/transcriptase
--- +++ @@ -5,30 +5,14 @@ import ReactDOM from "react-dom" import { AppLayout as RootComponent } from "./root-component" import { webFrame } from "electron" -import { css } from "glamor" /** * CSS reset */ -import "glamor/reset" /** * Electron-focused CSS resets */ -css.global("html, body", { - // turn off text highlighting - userSelect: "none", - - // reset the cursor pointer - cursor: "default", - - // font - font: "caption", - - // text rendering - WebkitFontSmoothing: "subpixel-antialiased", - textRendering: "optimizeLegibility", -}) /** * Zooming resets @@ -43,6 +27,5 @@ document.addEventListener("drop", event => event.preventDefault()) // mount the root component -import "../styles/uikit.css" ReactDOM.render(<RootComponent />, document.getElementById("root"), () => {})
660db27017f740f4ee851b5bf8bc742e1ada2b43
src/app/app.component.spec.ts
src/app/app.component.spec.ts
import {async, TestBed} from "@angular/core/testing"; import {AppComponent} from "./app.component"; import {MdSidenavModule, MdSnackBarModule} from "@angular/material"; import {MainToolbarComponent} from "./main-toolbar/main-toolbar.component"; import {AccountButtonComponent} from "./account-button/account-button.component"; import {HintsComponent} from "./hints/hints.component"; import {SlickModule} from "ngx-slick"; import {HotkeyModule} from "angular2-hotkeys"; describe('AppComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [MdSidenavModule, SlickModule.forRoot(), HotkeyModule.forRoot(), MdSnackBarModule], declarations: [ AppComponent, MainToolbarComponent, AccountButtonComponent, HintsComponent ], }).compileComponents(); })); it('should create the app', async(() => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); })); });
import {async, TestBed} from "@angular/core/testing"; import {AppComponent} from "./app.component"; import {MdSidenavModule, MdSnackBarModule} from "@angular/material"; import {MainToolbarComponent} from "./main-toolbar/main-toolbar.component"; import {AccountButtonComponent} from "./account-button/account-button.component"; import {HintsComponent} from "./hints/hints.component"; import {SlickModule} from "ngx-slick"; import {HotkeyModule} from "angular2-hotkeys"; import {GraphComponent} from "./graph/graph.component"; describe('AppComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [MdSidenavModule, SlickModule.forRoot(), HotkeyModule.forRoot(), MdSnackBarModule], declarations: [ AppComponent, MainToolbarComponent, AccountButtonComponent, HintsComponent, GraphComponent ], }).compileComponents(); })); it('should create the app', async(() => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); })); });
Add import in unit test
app: Add import in unit test
TypeScript
mit
lukaszkostrzewa/graphy,lukaszkostrzewa/graphy,lukaszkostrzewa/graphy
--- +++ @@ -7,13 +7,14 @@ import {HintsComponent} from "./hints/hints.component"; import {SlickModule} from "ngx-slick"; import {HotkeyModule} from "angular2-hotkeys"; +import {GraphComponent} from "./graph/graph.component"; describe('AppComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [MdSidenavModule, SlickModule.forRoot(), HotkeyModule.forRoot(), MdSnackBarModule], declarations: [ - AppComponent, MainToolbarComponent, AccountButtonComponent, HintsComponent + AppComponent, MainToolbarComponent, AccountButtonComponent, HintsComponent, GraphComponent ], }).compileComponents(); }));
8cecd36684e84051e131639e4ce9d06e15d25735
src/core/utils.ts
src/core/utils.ts
/** * Deep clone object * @param object Object to clone * @returns The cloned object */ export function clone <T>(object: T): T { var out, v, key out = Array.isArray(object) ? [] : {} for (key in object) { v = object[key] out[key] = (typeof v === 'object') ? clone (v) : v } return out }
import { Context, deepmerge } from '.' /** * Deep clone object * @param object Object to clone * @returns The cloned object */ export function clone <T>(object: T): T { var out, v, key out = Array.isArray(object) ? [] : {} for (key in object) { v = object[key] out[key] = (typeof v === 'object') ? clone (v) : v } return out } export const isServer = typeof window === 'undefined' export const isBrowser = !isServer export const hydrateState = <S>(ctx: Context<S>) => { if ((window as any).ssrInitialized) { let components = (window as any).ssrComponents let name for (name in components) { ctx.components[name].state = deepmerge(ctx.components[name].state, components[name].state) } } }
Add `isServer` and `hydrateState` helpers for prerendering and SSR
Add `isServer` and `hydrateState` helpers for prerendering and SSR
TypeScript
mit
FractalBlocks/Fractal,FractalBlocks/Fractal,FractalBlocks/Fractal
--- +++ @@ -1,3 +1,4 @@ +import { Context, deepmerge } from '.' /** * Deep clone object @@ -13,3 +14,17 @@ } return out } + +export const isServer = typeof window === 'undefined' + +export const isBrowser = !isServer + +export const hydrateState = <S>(ctx: Context<S>) => { + if ((window as any).ssrInitialized) { + let components = (window as any).ssrComponents + let name + for (name in components) { + ctx.components[name].state = deepmerge(ctx.components[name].state, components[name].state) + } + } +}
4ec2109c8d961d7384721708a6d8a982d66cb986
src/js/store/appSettings/reducers.ts
src/js/store/appSettings/reducers.ts
import { AppSettings, AppSettingsTypes, OVERWRITE_SETTINGS } from './types'; const initialState: AppSettings = { webmap: 'e691172598f04ea8881cd2a4adaa45ba', title: 'GFW Mapbuilder', subtitle: 'Make maps that matter', logoUrl: 'https://my.gfw-mapbuilder.org/img/gfw-logo.png', logoLinkUrl: 'https://www.gfw-mapbuilder.org/', language: 'en' }; export function appSettingsReducer( state = initialState, action: AppSettingsTypes ): AppSettings { switch (action.type) { case OVERWRITE_SETTINGS: return { ...state, ...action.payload }; default: return state; } }
import { AppSettings, AppSettingsTypes, OVERWRITE_SETTINGS } from './types'; const initialState: AppSettings = { webmap: '512eef95997b4e7486cdbdc45078739d', title: 'GFW Mapbuilder', subtitle: 'Make maps that matter', logoUrl: 'https://my.gfw-mapbuilder.org/img/gfw-logo.png', logoLinkUrl: 'https://www.gfw-mapbuilder.org/', language: 'en' }; export function appSettingsReducer( state = initialState, action: AppSettingsTypes ): AppSettings { switch (action.type) { case OVERWRITE_SETTINGS: return { ...state, ...action.payload }; default: return state; } }
Update webmap id with our testing id that has a few diff layers
Update webmap id with our testing id that has a few diff layers
TypeScript
mit
wri/gfw-mapbuilder,wri/gfw-mapbuilder,wri/gfw-mapbuilder
--- +++ @@ -1,7 +1,7 @@ import { AppSettings, AppSettingsTypes, OVERWRITE_SETTINGS } from './types'; const initialState: AppSettings = { - webmap: 'e691172598f04ea8881cd2a4adaa45ba', + webmap: '512eef95997b4e7486cdbdc45078739d', title: 'GFW Mapbuilder', subtitle: 'Make maps that matter', logoUrl: 'https://my.gfw-mapbuilder.org/img/gfw-logo.png',
92fc60aedda42478163ce3cf95bcc6e49f558af9
CeraonUI/src/Components/NavigationBar.tsx
CeraonUI/src/Components/NavigationBar.tsx
import * as React from 'react'; import {Menu, Input} from 'semantic-ui-react'; import UserSessionInfo from '../State/Identity/UserSessionInfo'; import NavigationBarState from '../State/NavigationBarState'; export interface NavigationBarProps extends React.Props<NavigationBar> { navigationBarState: NavigationBarState; userSessionInfo: UserSessionInfo; } export default class NavigationBar extends React.Component<NavigationBarProps, any> { constructor() { super(); } render() { return ( <Menu> <Menu.Item header>Ceraon</Menu.Item> <Menu.Item> <Input className="icon" icon="search" placeholder="Search..."/> </Menu.Item> <Menu.Item position="right"> <Menu.Item>Create Account</Menu.Item> </Menu.Item> </Menu> ) } }
import * as React from 'react'; import {Menu, Input} from 'semantic-ui-react'; import UserSessionInfo from '../State/Identity/UserSessionInfo'; import NavigationBarState from '../State/NavigationBarState'; import LoginForm from './LoginForm'; import CeraonDispatcher from '../Store/CeraonDispatcher'; import CreateLoginAction from '../Actions/LoginAction'; export interface NavigationBarProps extends NavigationBarState, React.Props<NavigationBar> { } export default class NavigationBar extends React.Component<NavigationBarProps, any> { constructor() { super(); this.onCreateAccount = this.onCreateAccount.bind(this); this.onSearchTextInput = this.onSearchTextInput.bind(this); this.onLogin = this.onLogin.bind(this); } onCreateAccount() { } onSearchTextInput() { } onLogin(username: string, password: string) { CeraonDispatcher(CreateLoginAction(username, password)); } render() { return ( <Menu fixed="top"> <Menu.Item header>{this.props.navigationTitle}</Menu.Item> { this.props.showSearchBox ? ( <Menu.Item> <Input className='icon' icon='search' placeholder='Search...' onChange={this.onSearchTextInput}/> </Menu.Item> ) : (<div/>)} <Menu.Item position='right'/> { this.props.showLoginUI ? ( <Menu.Item> <LoginForm direction="horizontal" onLogin={this.onLogin}/> </Menu.Item> ) : (<div/>)} { this.props.showCreateAccountButton ? ( <Menu.Item onClick={this.onCreateAccount}>Create Account</Menu.Item> ) : (<div/>)} { this.props.showLoggedInText ? ( <Menu.Item>{this.props.loggedInText}</Menu.Item> ) : (<div/>)} { this.props.showSettingsDropdown ? ( <Menu.Item>SettingsDropdown</Menu.Item> ) : (<div/>)} </Menu> ); } }
Add more functionality to navigation bar
Add more functionality to navigation bar
TypeScript
bsd-3-clause
Rdbaker/Mealbound,Rdbaker/Mealbound,Rdbaker/Mealbound,Rdbaker/Mealbound,Rdbaker/Mealbound
--- +++ @@ -2,28 +2,59 @@ import {Menu, Input} from 'semantic-ui-react'; import UserSessionInfo from '../State/Identity/UserSessionInfo'; import NavigationBarState from '../State/NavigationBarState'; +import LoginForm from './LoginForm'; +import CeraonDispatcher from '../Store/CeraonDispatcher'; +import CreateLoginAction from '../Actions/LoginAction'; -export interface NavigationBarProps extends React.Props<NavigationBar> { - navigationBarState: NavigationBarState; - userSessionInfo: UserSessionInfo; +export interface NavigationBarProps extends NavigationBarState, React.Props<NavigationBar> { } export default class NavigationBar extends React.Component<NavigationBarProps, any> { - constructor() { - super(); - } + constructor() { + super(); - render() { - return ( - <Menu> - <Menu.Item header>Ceraon</Menu.Item> - <Menu.Item> - <Input className="icon" icon="search" placeholder="Search..."/> - </Menu.Item> - <Menu.Item position="right"> - <Menu.Item>Create Account</Menu.Item> - </Menu.Item> - </Menu> - ) - } + this.onCreateAccount = this.onCreateAccount.bind(this); + this.onSearchTextInput = this.onSearchTextInput.bind(this); + this.onLogin = this.onLogin.bind(this); + } + + onCreateAccount() { + + } + + onSearchTextInput() { + + } + + onLogin(username: string, password: string) { + CeraonDispatcher(CreateLoginAction(username, password)); + } + + render() { + return ( + <Menu fixed="top"> + <Menu.Item header>{this.props.navigationTitle}</Menu.Item> + { this.props.showSearchBox ? ( + <Menu.Item> + <Input className='icon' icon='search' placeholder='Search...' onChange={this.onSearchTextInput}/> + </Menu.Item> + ) : (<div/>)} + <Menu.Item position='right'/> + { this.props.showLoginUI ? ( + <Menu.Item> + <LoginForm direction="horizontal" onLogin={this.onLogin}/> + </Menu.Item> + ) : (<div/>)} + { this.props.showCreateAccountButton ? ( + <Menu.Item onClick={this.onCreateAccount}>Create Account</Menu.Item> + ) : (<div/>)} + { this.props.showLoggedInText ? ( + <Menu.Item>{this.props.loggedInText}</Menu.Item> + ) : (<div/>)} + { this.props.showSettingsDropdown ? ( + <Menu.Item>SettingsDropdown</Menu.Item> + ) : (<div/>)} + </Menu> + ); + } }
19801ada9bee3ecd137c466c6e4a9f20de10aedb
applications/calendar/src/app/components/events/MoreFullDayEvent.tsx
applications/calendar/src/app/components/events/MoreFullDayEvent.tsx
import React, { CSSProperties, Ref } from 'react'; import { classnames } from 'react-components'; interface Props { style: CSSProperties; more: number; eventRef?: Ref<HTMLDivElement>; isSelected: boolean; } // NOTE: Can not be a button to satisfy auto close, and to be the same as the normal events const MoreFullDayEvent = ({ style, more, eventRef, isSelected }: Props) => { return ( <div style={style} className=" calendar-dayeventcell absolute " > <div className={classnames([ 'calendar-dayeventcell-inner calendar-dayeventcell-inner--isNotAllDay calendar-dayeventcell-inner--isLoaded ellipsis inline-flex alignleft w100 pl0-5 pr0-5', isSelected && 'calendar-dayeventcell-inner--isSelected', ])} ref={eventRef} > <span data-test-id="calendar-view:more-events-collapsed" className="mtauto mbauto"> {more} more </span> </div> </div> ); }; export default MoreFullDayEvent;
import React, { CSSProperties, Ref } from 'react'; import { classnames } from 'react-components'; interface Props { style: CSSProperties; more: number; eventRef?: Ref<HTMLDivElement>; isSelected: boolean; } // NOTE: Can not be a button to satisfy auto close, and to be the same as the normal events const MoreFullDayEvent = ({ style, more, eventRef, isSelected }: Props) => { return ( <div style={style} className=" calendar-dayeventcell absolute " > <div className={classnames([ 'calendar-dayeventcell-inner isNotAllDay isLoaded ellipsis inline-flex alignleft w100 pl0-5 pr0-5', isSelected && 'isSelected', ])} ref={eventRef} > <span data-test-id="calendar-view:more-events-collapsed" className="mtauto mbauto"> {more} more </span> </div> </div> ); }; export default MoreFullDayEvent;
Fix "more" button for new styles
Fix "more" button for new styles
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -19,8 +19,8 @@ > <div className={classnames([ - 'calendar-dayeventcell-inner calendar-dayeventcell-inner--isNotAllDay calendar-dayeventcell-inner--isLoaded ellipsis inline-flex alignleft w100 pl0-5 pr0-5', - isSelected && 'calendar-dayeventcell-inner--isSelected', + 'calendar-dayeventcell-inner isNotAllDay isLoaded ellipsis inline-flex alignleft w100 pl0-5 pr0-5', + isSelected && 'isSelected', ])} ref={eventRef} >
d7058c12bc19d5bd037e3d21dc80ed27b2a38d31
app/src/ui/updates/update-available.tsx
app/src/ui/updates/update-available.tsx
import * as React from 'react' import { LinkButton } from '../lib/link-button' import { updateStore } from '../lib/update-store' import { Octicon, OcticonSymbol } from '../octicons' interface IUpdateAvailableProps { readonly onDismissed: () => void } /** * A component which tells the user an update is available and gives them the * option of moving into the future or being a luddite. */ export class UpdateAvailable extends React.Component<IUpdateAvailableProps, void> { public render() { return ( <div id='update-available' onSubmit={this.updateNow} > <Octicon symbol={OcticonSymbol.desktopDownload} /> <span> An updated version of GitHub Desktop is avalble and will be installed at the next launch. See what's new or <LinkButton onClick={this.updateNow}>restart now </LinkButton>. </span> <a className='close' onClick={this.dismiss}> <Octicon symbol={OcticonSymbol.x} /> </a> </div> ) } private updateNow = () => { updateStore.quitAndInstallUpdate() } private dismiss = () => { this.props.onDismissed() } }
import * as React from 'react' import { LinkButton } from '../lib/link-button' import { updateStore } from '../lib/update-store' import { Octicon, OcticonSymbol } from '../octicons' interface IUpdateAvailableProps { readonly updateAvailble: boolean } interface IUpdateAvailableState { readonly isActive: boolean, } /** * A component which tells the user an update is available and gives them the * option of moving into the future or being a luddite. */ export class UpdateAvailable extends React.Component<IUpdateAvailableProps, IUpdateAvailableState> { public constructor(props: IUpdateAvailableProps) { super(props) this.state = { isActive: this.props.updateAvailble, } } public render() { return ( <div id='update-available' className={this.state.isActive ? 'active' : ''} onSubmit={this.updateNow} > <Octicon className='icon' symbol={OcticonSymbol.desktopDownload} /> <span> An updated version of GitHub Desktop is avalble and will be installed at the next launch. See what's new or <LinkButton onClick={this.updateNow}>restart now </LinkButton>. </span> <a className='close' onClick={this.dismiss}> <Octicon symbol={OcticonSymbol.x} /> </a> </div> ) } private updateNow = () => { updateStore.quitAndInstallUpdate() } private dismiss = () => { this.setState({ isActive: false, }) } }
Add state to manage visibility of update banner
Add state to manage visibility of update banner
TypeScript
mit
j-f1/forked-desktop,hjobrien/desktop,BugTesterTest/desktops,gengjiawen/desktop,kactus-io/kactus,shiftkey/desktop,hjobrien/desktop,j-f1/forked-desktop,say25/desktop,j-f1/forked-desktop,desktop/desktop,artivilla/desktop,say25/desktop,BugTesterTest/desktops,gengjiawen/desktop,gengjiawen/desktop,BugTesterTest/desktops,say25/desktop,artivilla/desktop,BugTesterTest/desktops,kactus-io/kactus,gengjiawen/desktop,shiftkey/desktop,artivilla/desktop,artivilla/desktop,say25/desktop,kactus-io/kactus,hjobrien/desktop,j-f1/forked-desktop,shiftkey/desktop,kactus-io/kactus,desktop/desktop,hjobrien/desktop,desktop/desktop,desktop/desktop,shiftkey/desktop
--- +++ @@ -4,21 +4,36 @@ import { Octicon, OcticonSymbol } from '../octicons' interface IUpdateAvailableProps { - readonly onDismissed: () => void + readonly updateAvailble: boolean +} + +interface IUpdateAvailableState { + readonly isActive: boolean, } /** * A component which tells the user an update is available and gives them the * option of moving into the future or being a luddite. */ -export class UpdateAvailable extends React.Component<IUpdateAvailableProps, void> { +export class UpdateAvailable extends React.Component<IUpdateAvailableProps, IUpdateAvailableState> { + public constructor(props: IUpdateAvailableProps) { + super(props) + + this.state = { + isActive: this.props.updateAvailble, + } + } + public render() { return ( <div id='update-available' + className={this.state.isActive ? 'active' : ''} onSubmit={this.updateNow} > - <Octicon symbol={OcticonSymbol.desktopDownload} /> + <Octicon + className='icon' + symbol={OcticonSymbol.desktopDownload} /> <span> An updated version of GitHub Desktop is avalble and will be installed at the next launch. See what's new or <LinkButton onClick={this.updateNow}>restart now </LinkButton>. @@ -38,6 +53,8 @@ } private dismiss = () => { - this.props.onDismissed() + this.setState({ + isActive: false, + }) } }
be9ac553de4c95272a3951282233ef7471ba95fe
MonitoredSocket.ts
MonitoredSocket.ts
import net = require("net"); /** * Represents a given host and port. Handles checking whether a host * is up or not, as well as if it is accessible on the given port. */ class MonitoredSocket { /** * Returns whether the host can be accessed on its port. */ public isUp: boolean; private socket: net.Socket; constructor( public endpoint: string, public port: number ) { this.socket = new net.Socket(); } connect(successCallback: { (sock: MonitoredSocket): void }, failCallback: { (sock: MonitoredSocket): void }): void { this.socket.connect( this.port, this.endpoint, this.onConnectSuccess.bind(this, successCallback) ); this.socket.on("error", this.onConnectFailure.bind(this, failCallback)); } onConnectSuccess(callback: {(sock: MonitoredSocket): void }) { this.isUp = true; // We're good! Close the socket this.socket.end(); callback(this); } onConnectFailure(callback: {(sock: MonitoredSocket): void }) { this.isUp = false; // Cleanup this.socket.destroy(); callback(this); } toString(): string { return this.endpoint + ":" + this.port; } serialize(): string { return JSON.stringify(this); } } export = MonitoredSocket;
import net = require("net"); /** * Represents a given host and port. Handles checking whether a host * is up or not, as well as if it is accessible on the given port. */ class MonitoredSocket { /** * Returns whether the host can be accessed on its port. */ public isUp: boolean; private socket: net.Socket; constructor( public endpoint: string, public port: number ) { this.socket = new net.Socket(); } connect(successCallback: { (sock: MonitoredSocket, conn?: any): void }, failCallback: { (sock: MonitoredSocket, conn?: any): void }): void { this.socket.connect( this.port, this.endpoint, this.onConnectSuccess.bind(this, successCallback) ); this.socket.on("error", this.onConnectFailure.bind(this, failCallback)); } onConnectSuccess(callback: { (sock: MonitoredSocket, conn?: any): void }) { this.isUp = true; // We're good! Close the socket this.socket.end(); callback(this); } onConnectFailure(callback: { (sock: MonitoredSocket, conn?: any): void }) { this.isUp = false; // Cleanup this.socket.destroy(); callback(this); } toString(): string { return this.endpoint + ":" + this.port; } serialize(): string { return JSON.stringify(this); } } export = MonitoredSocket;
Add optional connection param to callbacks
Add optional connection param to callbacks
TypeScript
mit
OzuYatamutsu/is-my-server-up,OzuYatamutsu/is-my-server-up,OzuYatamutsu/is-my-server-up
--- +++ @@ -18,8 +18,8 @@ this.socket = new net.Socket(); } - connect(successCallback: { (sock: MonitoredSocket): void }, - failCallback: { (sock: MonitoredSocket): void }): void { + connect(successCallback: { (sock: MonitoredSocket, conn?: any): void }, + failCallback: { (sock: MonitoredSocket, conn?: any): void }): void { this.socket.connect( this.port, this.endpoint, @@ -29,7 +29,7 @@ this.socket.on("error", this.onConnectFailure.bind(this, failCallback)); } - onConnectSuccess(callback: {(sock: MonitoredSocket): void }) { + onConnectSuccess(callback: { (sock: MonitoredSocket, conn?: any): void }) { this.isUp = true; // We're good! Close the socket @@ -38,7 +38,7 @@ callback(this); } - onConnectFailure(callback: {(sock: MonitoredSocket): void }) { + onConnectFailure(callback: { (sock: MonitoredSocket, conn?: any): void }) { this.isUp = false; // Cleanup
3f22797c158be281f8deb333cff7d9208459e704
src/utils/privateClassNames.ts
src/utils/privateClassNames.ts
import { classNamePrefix } from "./consts"; export const sortArrowClassName = classNamePrefix + "sortArrow"; export const activeSortArrowClassName = classNamePrefix + "sortArrow--active"; export const ascendantSortArrowClassName = classNamePrefix + "sortArrow--ascendant"; export const descendantSortArrowClassName = classNamePrefix + "sortArrow--descendant"; export const selectionCellClassName = classNamePrefix + "selectionCell";
import { classNamePrefix } from "./consts"; export const sortArrowClassName = classNamePrefix + "sortArrow"; export const activeSortArrowClassName = classNamePrefix + "sortArrow--active"; export const ascendantSortArrowClassName = classNamePrefix + "sortArrow--ascendant"; export const descendantSortArrowClassName = classNamePrefix + "sortArrow--descendant"; export const selectionCellClassName = classNamePrefix + "selectionCell"; export const stickyHeaderClassName = classNamePrefix + "stickyHeader";
Create privateClassName for the sticky header
feat: Create privateClassName for the sticky header
TypeScript
mit
vhfmag/react-data-table,vhfmag/react-data-table,vhfmag/react-data-table
--- +++ @@ -6,3 +6,4 @@ export const descendantSortArrowClassName = classNamePrefix + "sortArrow--descendant"; export const selectionCellClassName = classNamePrefix + "selectionCell"; +export const stickyHeaderClassName = classNamePrefix + "stickyHeader";
e037fa061174c3e74af6515f487d8b39b19f2f0f
src/app/search-results/search-results.tsx
src/app/search-results/search-results.tsx
import * as React from 'react'; import * as Aggregate from './search-results-aggregate/search-results-aggregate'; import * as Person from './search-results-person/search-results-person' import { Row, Col } from 'react-bootstrap' export const SearchResults = (props) => { // Be nice to revist the tag aggregations with morelike, and get rid of the check. return ( <div> <Row className="show-grid"> {props.resultData.aggregations ? <Aggregate.SearchResultsAggregate onSubmit={props.onSubmit} addTag={props.addTag} tagAggs={props.resultData.aggregations.tagAggs as any}/> : <Col md={2}></Col> } <Person.SearchResultsPerson onSubmit={props.onSubmit} persons={props.resultData.hits.hits} total={props.resultData.hits.total}/> </Row> <Row> {props.resultData.hits.total ? <button onClick={() => {props.loadMore(props.resultData.hits.hits.length)}} className="btn btn-primary btn-block">Load More</button>: ""} </Row> </div> ); }
import * as React from 'react'; import * as Aggregate from './search-results-aggregate/search-results-aggregate'; import * as Person from './search-results-person/search-results-person' import { Row, Col } from 'react-bootstrap' export const SearchResults = (props) => { // Be nice to revist the tag aggregations with morelike, and get rid of the check. return ( <div> <Row className="show-grid"> {props.resultData.aggregations ? <Aggregate.SearchResultsAggregate onSubmit={props.onSubmit} addTag={props.addTag} tagAggs={props.resultData.aggregations.tagAggs as any}/> : <Col md={2}></Col> } <Person.SearchResultsPerson onSubmit={props.onSubmit} persons={props.resultData.hits.hits} total={props.resultData.hits.total}/> </Row> <Row> {props.resultData.hits.total > props.resultData.hits.hits.length? <button onClick={() => {props.loadMore(props.resultData.hits.hits.length)}} className="btn btn-primary btn-block">Load More</button>: ""} </Row> </div> ); }
Add the removal of the button if there are no more
Add the removal of the button if there are no more
TypeScript
mit
JoshuaToth/person-data-viewer,JoshuaToth/person-data-viewer,JoshuaToth/person-data-viewer
--- +++ @@ -15,7 +15,7 @@ <Person.SearchResultsPerson onSubmit={props.onSubmit} persons={props.resultData.hits.hits} total={props.resultData.hits.total}/> </Row> <Row> - {props.resultData.hits.total ? <button onClick={() => {props.loadMore(props.resultData.hits.hits.length)}} className="btn btn-primary btn-block">Load More</button>: ""} + {props.resultData.hits.total > props.resultData.hits.hits.length? <button onClick={() => {props.loadMore(props.resultData.hits.hits.length)}} className="btn btn-primary btn-block">Load More</button>: ""} </Row> </div> );
a4d0c9b3967e8a526bce79ba8a2f33c4b70bbcf9
src/app/dashboards/card.simple.component.ts
src/app/dashboards/card.simple.component.ts
import { Component, EventEmitter, Output, Input } from '@angular/core'; @Component({ selector: 'app-sac-card', templateUrl: 'card.simple.component.html', styleUrls: ['card.simple.component.css'], }) export class CardComponent { @Input() cardImage: string; @Input() title: string; @Input() bodyText: string; @Input() origin: string; @Input() originUrl: string; @Input() tempRating: number; @Output() headerClick = new EventEmitter(); @Output() readMoreClick = new EventEmitter(); getProgressLabel(value: number): string { if (value < 0.1) { return '<10%'; } else { return `${this.getProgressValue(value)}%`; } } getProgressValue(value: number): string { if (value < 0.1) { return '10'; } else { return (value * 100).toFixed(0); } } getProgressType(value: number): string { if (value > 0.75) { return 'success'; } else if (value > 0.5) { return 'info'; } else if (value > 0.1) { return 'warning'; } else { return 'default'; } } headerClicked() { this.headerClick.emit(); } readMoreClicked() { this.readMoreClick.emit(); } getFirstWords(str: string, number: number) { return str.split(/\W/, number).join(' '); } }
import { Component, EventEmitter, Output, Input } from '@angular/core'; @Component({ selector: 'app-sac-card', templateUrl: 'card.simple.component.html', styleUrls: ['card.simple.component.css'], }) export class CardComponent { @Input() cardImage: string; @Input() title: string; @Input() bodyText: string; @Input() origin: string; @Input() originUrl: string; @Input() tempRating: number; @Output() headerClick = new EventEmitter(); @Output() readMoreClick = new EventEmitter(); getProgressLabel(value: number): string { if (value < 0.1) { return '<10%'; } else { return `${this.getProgressValue(value)}%`; } } getProgressValue(value: number): string { if (value < 0.1) { return '10'; } else { return (value * 100).toFixed(0); } } headerClicked() { this.headerClick.emit(); } readMoreClicked() { this.readMoreClick.emit(); } getFirstWords(str: string, number: number) { return str.split(/\W/, number).join(' '); } private getProgressType(value: number): string { if (value > 0.75) { return 'success'; } else if (value > 0.5) { return 'info'; } else if (value > 0.1) { return 'warning'; } else { return 'default'; } } }
Revert "build error fixed introduced with 59c064e"
Revert "build error fixed introduced with 59c064e" This reverts commit ea741f69cf7bd9dcdc81aa0ed923acff8d4589d9.
TypeScript
apache-2.0
ZGIS/smart-portal-webgui,ZGIS/smart-portal-webgui,ZGIS/smart-portal-webgui,ZGIS/smart-portal-webgui,ZGIS/smart-portal-webgui
--- +++ @@ -36,18 +36,6 @@ } } - getProgressType(value: number): string { - if (value > 0.75) { - return 'success'; - } else if (value > 0.5) { - return 'info'; - } else if (value > 0.1) { - return 'warning'; - } else { - return 'default'; - } - } - headerClicked() { this.headerClick.emit(); } @@ -60,4 +48,15 @@ return str.split(/\W/, number).join(' '); } + private getProgressType(value: number): string { + if (value > 0.75) { + return 'success'; + } else if (value > 0.5) { + return 'info'; + } else if (value > 0.1) { + return 'warning'; + } else { + return 'default'; + } + } }
4a85c84da21425368c22a3c59aaa6af8a89f757b
welcome/index.ts
welcome/index.ts
import axios from 'axios'; const welcomeScrapboxUrl = `https://scrapbox.io/api/pages/tsg/welcome`; import {WebClient, RTMClient} from '@slack/client'; interface SlackInterface { rtmClient: RTMClient, webClient: WebClient, } export default async ({rtmClient: rtm, webClient: slack}: SlackInterface) => { const general = await slack.conversations.list({exclude_archived: true, limit: 1000}) .then((list: any) => list.channels.find(({is_general}: {is_general: boolean}) => is_general).id); rtm.on('member_joined_channel', async (event: any) => { if (event.channel !== general) { return; } const {data} = await axios.get(welcomeScrapboxUrl, {headers: {Cookie: `connect.sid=${process.env.SCRAPBOX_SID}`}}); const text = [`<@${event.user}>`, ...data.lines.map(({text}: {text: string}) => text).slice(1)].join('\n'); slack.chat.postMessage({channel: general, text, link_names: true}); }); };
import axios from 'axios'; const welcomeScrapboxUrl = `https://scrapbox.io/api/pages/tsg/welcome`; import {WebClient, RTMClient} from '@slack/client'; interface SlackInterface { rtmClient: RTMClient, webClient: WebClient, } export default async ({rtmClient: rtm, webClient: slack}: SlackInterface) => { const general = await slack.conversations.list({exclude_archived: true, limit: 1000}) .then((list: any) => list.channels.find(({is_general}: {is_general: boolean}) => is_general).id); rtm.on('member_joined_channel', async (event: any) => { if (event.channel !== general) { return; } const {data} = await axios.get(welcomeScrapboxUrl, {headers: {Cookie: `connect.sid=${process.env.SCRAPBOX_SID}`}}); const text = [`<@${event.user}>`, ...data.lines.map(({text}: {text: string}) => text).slice(1)].join('\n'); slack.chat.postMessage({ channel: general, text, link_names: true, icon_emoji: ':jp3bgy:', username: 'JP3BGY', }); }); };
Use JP3BPY's name and icon to welcome nwecomers
welcome: Use JP3BPY's name and icon to welcome nwecomers
TypeScript
mit
tsg-ut/slackbot,tsg-ut/slackbot,tsg-ut/slackbot,tsg-ut/slackbot,tsg-ut/slackbot,tsg-ut/slackbot
--- +++ @@ -20,6 +20,12 @@ const {data} = await axios.get(welcomeScrapboxUrl, {headers: {Cookie: `connect.sid=${process.env.SCRAPBOX_SID}`}}); const text = [`<@${event.user}>`, ...data.lines.map(({text}: {text: string}) => text).slice(1)].join('\n'); - slack.chat.postMessage({channel: general, text, link_names: true}); + slack.chat.postMessage({ + channel: general, + text, + link_names: true, + icon_emoji: ':jp3bgy:', + username: 'JP3BGY', + }); }); };
f6c8be81e8757f88c0b6d8d8b4fc528e106f3358
typescript-marionette-v2/src/RootModel.ts
typescript-marionette-v2/src/RootModel.ts
// The following has to be added to the bottom of typings/global/backbone.localstorage/index.d.ts. // TODO: Figure out how to avoid this or add a pull request fixing this. // declare module "backbone.localstorage" { // export = Backbone.LocalStorage; // } import Filter from "./Filter" import Store = require("backbone.localstorage") import TodoCollection from "./TodoCollection" export default class RootModel extends Backbone.Model { defaults() { return { todos: TodoCollection, todosFilter: Filter.All } } localStorage = new Store("todos-typescript-marionette-v2") get filter(): Filter { return this.get("filter") } set filter(filter: Filter) { this.set("fitler", filter) } // TODO: Filtering a collection does not return a new collection, but an array. // get filteredTodos(): TodoCollection { // const filtered = this.todos.filter(todo => { // switch (this.filter) { // case Filter.Active: // return !todo.completed // case Filter.All: // return true // case Filter.Completed: // return todo.completed // default: // throw Error("Unknown filter state.") // } // }) // return filtered // } get todos(): TodoCollection { return this.get("todos") } set todos(todos: TodoCollection) { this.set("todos", todos) } }
// The following has to be added to the bottom of typings/global/backbone.localstorage/index.d.ts. // TODO: Figure out how to avoid this or add a pull request fixing this. // declare module "backbone.localstorage" { // export = Backbone.LocalStorage; // } import Filter from "./Filter" import Store = require("backbone.localstorage") import TodoCollection from "./TodoCollection" export default class RootModel extends Backbone.Model { defaults() { return { todos: TodoCollection, todosFilter: Filter.All } } localStorage = new Store("todos-typescript-marionette-v2") get filter(): Filter { return this.get("filter") } set filter(filter: Filter) { this.set("fitler", filter) } get todos(): TodoCollection { return this.get("todos") } set todos(todos: TodoCollection) { this.set("todos", todos) } }
Remove filter since it returns an array
Remove filter since it returns an array
TypeScript
unlicense
janaagaard75/framework-investigations,janaagaard75/framework-investigations,janaagaard75/framework-investigations,janaagaard75/framework-investigations
--- +++ @@ -25,27 +25,6 @@ this.set("fitler", filter) } - // TODO: Filtering a collection does not return a new collection, but an array. - // get filteredTodos(): TodoCollection { - // const filtered = this.todos.filter(todo => { - // switch (this.filter) { - // case Filter.Active: - // return !todo.completed - - // case Filter.All: - // return true - - // case Filter.Completed: - // return todo.completed - - // default: - // throw Error("Unknown filter state.") - // } - // }) - - // return filtered - // } - get todos(): TodoCollection { return this.get("todos") }
66666eba32f395242a0245b73a05d3598375597b
examples/components/with-handle.tsx
examples/components/with-handle.tsx
import React, { useState } from "react"; import { ReactSortable } from "../../src"; import styled from "styled-components"; import { threes, Item } from "../util"; export function WithHandle() { const [list, setList] = useState(threes); return ( <ReactSortable handle=".handle" animation={150} list={list} setList={setList} > {list.map(item => ( <Item key={item.id}> <Handle className="handle" /> <span>{item.name}</span> </Item> ))} </ReactSortable> ); } const Handle = styled.div` width: 1.5rem; height: inherit; background: #ffff; margin-right: 1rem; border-radius: 0.4rem; :hover { background-color: #fffa; } `;
import React, { useState } from "react"; import { ReactSortable } from "../../src"; import styled from "styled-components"; import { threes, Item } from "../util"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; export function WithHandle() { const [list, setList] = useState(threes); return ( <ReactSortable handle=".handle" animation={150} list={list} setList={setList} > {list.map(item => ( <CustomItem key={item.id}> <FontAwesomeIcon className="handle" icon="grip-lines" /> <Span>{item.name}</Span> </CustomItem> ))} </ReactSortable> ); } const CustomItem = styled(Item)` align-items: center; & > * { margin: auto unset; } `; const Span = styled.span` margin-left: .5rem; `;
Replace handle with font awesome handle
Replace handle with font awesome handle
TypeScript
mit
cheton/react-sortable
--- +++ @@ -2,7 +2,7 @@ import { ReactSortable } from "../../src"; import styled from "styled-components"; import { threes, Item } from "../util"; - +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; export function WithHandle() { const [list, setList] = useState(threes); @@ -14,22 +14,22 @@ setList={setList} > {list.map(item => ( - <Item key={item.id}> - <Handle className="handle" /> - <span>{item.name}</span> - </Item> + <CustomItem key={item.id}> + <FontAwesomeIcon className="handle" icon="grip-lines" /> + <Span>{item.name}</Span> + </CustomItem> ))} </ReactSortable> ); } -const Handle = styled.div` - width: 1.5rem; - height: inherit; - background: #ffff; - margin-right: 1rem; - border-radius: 0.4rem; - :hover { - background-color: #fffa; +const CustomItem = styled(Item)` + align-items: center; + & > * { + margin: auto unset; } `; + +const Span = styled.span` + margin-left: .5rem; +`;
1677778e44fd15d37047fdfd485594c4123c3dab
src/v2/Apps/_Preferences2/__tests__/PreferencesApp.jest.tsx
src/v2/Apps/_Preferences2/__tests__/PreferencesApp.jest.tsx
import { render, screen, fireEvent } from "@testing-library/react" import { PreferencesApp } from "../PreferencesApp" describe("PreferencesApp", () => { it("renders the preference center", () => { render(<PreferencesApp></PreferencesApp>) expect(screen.getByText("Preferences Center")).toBeInTheDocument() }) it("allows user to uncheck all boxes with unsubscribe all", () => { render(<PreferencesApp></PreferencesApp>) let checkboxes = screen.getAllByRole("checkbox") let unsubscribeFromAllCheckbox = checkboxes[checkboxes.length - 1] // Unsubscribe from all defaults to checked, so we click it twice! fireEvent.click(unsubscribeFromAllCheckbox) fireEvent.click(unsubscribeFromAllCheckbox) expect(screen.getAllByRole("checkbox")[checkboxes.length - 1]).toBeChecked() checkboxes.pop() checkboxes.forEach(checkbox => { expect(checkbox).not.toBeChecked() }) }) })
import { render, screen, fireEvent } from "@testing-library/react" import { PreferencesApp } from "../PreferencesApp" describe("PreferencesApp", () => { it("renders the preference center", () => { render(<PreferencesApp></PreferencesApp>) expect(screen.getByText("Preferences Center")).toBeInTheDocument() }) it("allows user to uncheck all boxes with unsubscribe from all", () => { render(<PreferencesApp></PreferencesApp>) expect(screen.getByText("Subscribe to all")).toBeInTheDocument() let checkboxes = screen.getAllByRole("checkbox") let unsubscribeFromAllCheckbox = checkboxes.pop()! fireEvent.click(checkboxes[3]) fireEvent.click(checkboxes[4]) fireEvent.click(unsubscribeFromAllCheckbox) expect(unsubscribeFromAllCheckbox).toBeChecked() checkboxes?.forEach(checkbox => { expect(checkbox).not.toBeChecked() }) }) it("unchecks unsubscribe/subscribe all when other checkboxes are checked", () => { render(<PreferencesApp></PreferencesApp>) expect(screen.getByText("Unsubscribe from all")).toBeInTheDocument() let checkboxes = screen.getAllByRole("checkbox") let subscribeToAllCheckbox = checkboxes[0] let unsubscribeFromAllCheckbox = checkboxes.pop() fireEvent.click(checkboxes[3]) expect(subscribeToAllCheckbox).not.toBeChecked() expect(unsubscribeFromAllCheckbox).not.toBeChecked() }) it("allows user to check all boxes with subscribe to all", () => { render(<PreferencesApp></PreferencesApp>) expect(screen.getByText("Unsubscribe from all")).toBeInTheDocument() let checkboxes = screen.getAllByRole("checkbox") let subscribeToAllCheckbox = checkboxes[0] let unsubscribeFromAllCheckbox = checkboxes.pop() fireEvent.click(subscribeToAllCheckbox) expect(subscribeToAllCheckbox).toBeChecked() expect(unsubscribeFromAllCheckbox).not.toBeChecked() checkboxes.forEach(checkbox => { expect(checkbox).toBeChecked() }) }) })
Expand testing for the preference center
chore: Expand testing for the preference center
TypeScript
mit
artsy/force,artsy/force,artsy/force,artsy/force
--- +++ @@ -8,22 +8,58 @@ expect(screen.getByText("Preferences Center")).toBeInTheDocument() }) - it("allows user to uncheck all boxes with unsubscribe all", () => { + it("allows user to uncheck all boxes with unsubscribe from all", () => { render(<PreferencesApp></PreferencesApp>) + expect(screen.getByText("Subscribe to all")).toBeInTheDocument() + let checkboxes = screen.getAllByRole("checkbox") - let unsubscribeFromAllCheckbox = checkboxes[checkboxes.length - 1] + let unsubscribeFromAllCheckbox = checkboxes.pop()! - // Unsubscribe from all defaults to checked, so we click it twice! - fireEvent.click(unsubscribeFromAllCheckbox) + fireEvent.click(checkboxes[3]) + fireEvent.click(checkboxes[4]) + fireEvent.click(unsubscribeFromAllCheckbox) - expect(screen.getAllByRole("checkbox")[checkboxes.length - 1]).toBeChecked() + expect(unsubscribeFromAllCheckbox).toBeChecked() - checkboxes.pop() - - checkboxes.forEach(checkbox => { + checkboxes?.forEach(checkbox => { expect(checkbox).not.toBeChecked() }) }) + + it("unchecks unsubscribe/subscribe all when other checkboxes are checked", () => { + render(<PreferencesApp></PreferencesApp>) + + expect(screen.getByText("Unsubscribe from all")).toBeInTheDocument() + + let checkboxes = screen.getAllByRole("checkbox") + let subscribeToAllCheckbox = checkboxes[0] + let unsubscribeFromAllCheckbox = checkboxes.pop() + + fireEvent.click(checkboxes[3]) + + expect(subscribeToAllCheckbox).not.toBeChecked() + expect(unsubscribeFromAllCheckbox).not.toBeChecked() + }) + + it("allows user to check all boxes with subscribe to all", () => { + render(<PreferencesApp></PreferencesApp>) + + expect(screen.getByText("Unsubscribe from all")).toBeInTheDocument() + + let checkboxes = screen.getAllByRole("checkbox") + let subscribeToAllCheckbox = checkboxes[0] + let unsubscribeFromAllCheckbox = checkboxes.pop() + + fireEvent.click(subscribeToAllCheckbox) + + expect(subscribeToAllCheckbox).toBeChecked() + + expect(unsubscribeFromAllCheckbox).not.toBeChecked() + + checkboxes.forEach(checkbox => { + expect(checkbox).toBeChecked() + }) + }) })
0a2475655fc8f11a848b7a2c948a9bffad1c4c91
src/browser/shared/workspace.service.ts
src/browser/shared/workspace.service.ts
import { Inject, Injectable, InjectionToken, OnDestroy, Optional } from '@angular/core'; import { from, Observable } from 'rxjs'; import { GEEKS_DIARY_DIR_PATH, NOTES_DIR_PATH, WORKSPACE_DIR_PATH } from '../../core/workspace'; import { IpcActionClient } from '../../libs/ipc'; export class WorkspaceConfig { rootDirPath?: string = WORKSPACE_DIR_PATH; geeksDiaryDirPath?: string = GEEKS_DIARY_DIR_PATH; notesDirPath?: string = NOTES_DIR_PATH; } export const WORKSPACE_DEFAULT_CONFIG = new InjectionToken<WorkspaceConfig>('WorkspaceConfig'); @Injectable() export class WorkspaceService implements OnDestroy { readonly configs: WorkspaceConfig; private ipcClient = new IpcActionClient('workspace'); constructor( @Optional() @Inject(WORKSPACE_DEFAULT_CONFIG) config: WorkspaceConfig, ) { this.configs = { ...(new WorkspaceConfig()), ...config, }; } ngOnDestroy(): void { this.ipcClient.destroy(); } initWorkspace(): Observable<void> { return from(this.ipcClient.performAction('initWorkspace')); } }
import { Inject, Injectable, InjectionToken, OnDestroy, Optional } from '@angular/core'; import { from, Observable } from 'rxjs'; import { ASSETS_DIR_PATH, GEEKS_DIARY_DIR_PATH, NOTES_DIR_PATH, WORKSPACE_DIR_PATH } from '../../core/workspace'; import { IpcActionClient } from '../../libs/ipc'; export class WorkspaceConfig { rootDirPath?: string = WORKSPACE_DIR_PATH; geeksDiaryDirPath?: string = GEEKS_DIARY_DIR_PATH; notesDirPath?: string = NOTES_DIR_PATH; assetsDirPath?: string = ASSETS_DIR_PATH; } export const WORKSPACE_DEFAULT_CONFIG = new InjectionToken<WorkspaceConfig>('WorkspaceConfig'); @Injectable() export class WorkspaceService implements OnDestroy { readonly configs: WorkspaceConfig; private ipcClient = new IpcActionClient('workspace'); constructor( @Optional() @Inject(WORKSPACE_DEFAULT_CONFIG) config: WorkspaceConfig, ) { this.configs = { ...(new WorkspaceConfig()), ...config, }; } ngOnDestroy(): void { this.ipcClient.destroy(); } initWorkspace(): Observable<void> { return from(this.ipcClient.performAction('initWorkspace')); } }
Add assets directory path config option
Add assets directory path config option
TypeScript
mit
seokju-na/geeks-diary,seokju-na/geeks-diary,seokju-na/geeks-diary
--- +++ @@ -1,6 +1,6 @@ import { Inject, Injectable, InjectionToken, OnDestroy, Optional } from '@angular/core'; import { from, Observable } from 'rxjs'; -import { GEEKS_DIARY_DIR_PATH, NOTES_DIR_PATH, WORKSPACE_DIR_PATH } from '../../core/workspace'; +import { ASSETS_DIR_PATH, GEEKS_DIARY_DIR_PATH, NOTES_DIR_PATH, WORKSPACE_DIR_PATH } from '../../core/workspace'; import { IpcActionClient } from '../../libs/ipc'; @@ -8,6 +8,7 @@ rootDirPath?: string = WORKSPACE_DIR_PATH; geeksDiaryDirPath?: string = GEEKS_DIARY_DIR_PATH; notesDirPath?: string = NOTES_DIR_PATH; + assetsDirPath?: string = ASSETS_DIR_PATH; }
d2a1af471b071f2cc8d7940ec887609577a3be8d
src/jsonapi/jsonapi-response.model.ts
src/jsonapi/jsonapi-response.model.ts
import { JSONAPIResourceObject } from './jsonapi-resource-object.model'; export class JSONAPIResponse<T extends JSONAPIResourceObject | JSONAPIResourceObject[]> { public data: T; public included: JSONAPIResourceObject[]; public constructor(json: {data: any, included?: any}) { this.data = json.data; this.included = json.included; } public toPayload(): T { return this.data; } public toIncluded(): JSONAPIResourceObject | JSONAPIResourceObject[] { return this.included; } public toIncludedByType<U extends JSONAPIResourceObject>(type: string): U[] { return <U[]>this.included.filter((include: JSONAPIResourceObject) => include.type === type); } public toJSON(): {data: T, included?: JSONAPIResourceObject | JSONAPIResourceObject[]} { if (this.included) { return {data: this.data, included: this.included}; } else { return {data: this.data}; } } }
import { JSONAPIResourceObject } from './jsonapi-resource-object.model'; export class JSONAPIResponse<T extends JSONAPIResourceObject | JSONAPIResourceObject[]> { public data: T; public included: JSONAPIResourceObject[]; public constructor(json: {data: any, included?: any}) { this.data = json.data; this.included = json.included; } public toPayload(): T { return this.data; } public toIncluded(): JSONAPIResourceObject | JSONAPIResourceObject[] { return this.included; } public toIncludedByType<U extends JSONAPIResourceObject>(type: string): U[] { if (!this.included) { return []; } return <U[]>this.included.filter((include: JSONAPIResourceObject) => include.type === type); } public toJSON(): {data: T, included?: JSONAPIResourceObject | JSONAPIResourceObject[]} { if (this.included) { return {data: this.data, included: this.included}; } else { return {data: this.data}; } } }
Return empty array when include not defined
Return empty array when include not defined
TypeScript
mit
ValueMiner/ng2-valueminer-connector,ValueMiner/ng2-valueminer-connector
--- +++ @@ -18,7 +18,10 @@ } public toIncludedByType<U extends JSONAPIResourceObject>(type: string): U[] { - return <U[]>this.included.filter((include: JSONAPIResourceObject) => include.type === type); + if (!this.included) { + return []; + } + return <U[]>this.included.filter((include: JSONAPIResourceObject) => include.type === type); } public toJSON(): {data: T, included?: JSONAPIResourceObject | JSONAPIResourceObject[]} {
5bc0a365f0ac29df2feb22e611d691b2eceda386
src/app/shared/footer/footer.component.ts
src/app/shared/footer/footer.component.ts
import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-footer', templateUrl: './footer.component.html', styleUrls: ['./footer.component.sass'] }) export class FooterComponent { constructor(private router: Router) { } relativePos() { let links = [ '/snippet/:id', '/snippets', '/sign-up' ]; if (this.router.url === '/snippets' || this.router.url === '/sign-up') { return true; } else { return false; } } }
import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-footer', templateUrl: './footer.component.html', styleUrls: ['./footer.component.sass'] }) export class FooterComponent { constructor(private router: Router) { } relativePos() { let links = [ '/snippet/:id', '/snippets', '/sign-up' ]; if (this.router.url === '/snippets' || this.router.url === '/profile' || this.router.url === '/sign-up') { return true; } else { return false; } } }
Add profile to relative pos
Add profile to relative pos
TypeScript
apache-2.0
SamuelM333/snippet-sniper-frontend,SamuelM333/snippet-sniper-frontend,SamuelM333/snippet-sniper-frontend
--- +++ @@ -18,7 +18,9 @@ '/sign-up' ]; - if (this.router.url === '/snippets' || this.router.url === '/sign-up') { + if (this.router.url === '/snippets' || + this.router.url === '/profile' || + this.router.url === '/sign-up') { return true; } else { return false; } }
15e9312625c10b488ad49f648b95796d7d6ef5f0
lib/run-effects.ts
lib/run-effects.ts
import { OpaqueToken, Provider } from '@angular/core'; import { flatten } from './util'; import { CONNECT_EFFECTS_PROVIDER } from './effects'; import { STATE_UPDATES_PROVIDER } from './state-updates'; export const BOOTSTRAP_EFFECTS = new OpaqueToken('@ngrx/effects Bootstrap Effects'); export function runEffects(...effects: any[]) { const allEffects = flatten(effects).map(effect => new Provider(BOOTSTRAP_EFFECTS, { useClass: effect, multi: true })); return [ ...allEffects, CONNECT_EFFECTS_PROVIDER, STATE_UPDATES_PROVIDER ]; }
import { OpaqueToken, Provider } from '@angular/core'; import { flatten } from './util'; import { CONNECT_EFFECTS_PROVIDER, BOOTSTRAP_EFFECTS } from './effects'; import { STATE_UPDATES_PROVIDER } from './state-updates'; export function runEffects(...effects: any[]) { const allEffects = flatten(effects).map(effect => new Provider(BOOTSTRAP_EFFECTS, { useClass: effect, multi: true })); return [ ...allEffects, CONNECT_EFFECTS_PROVIDER, STATE_UPDATES_PROVIDER ]; }
Fix import for bootstrap effects token
Fix import for bootstrap effects token
TypeScript
mit
ngrx/effects,ngrx/effects
--- +++ @@ -1,10 +1,9 @@ import { OpaqueToken, Provider } from '@angular/core'; import { flatten } from './util'; -import { CONNECT_EFFECTS_PROVIDER } from './effects'; +import { CONNECT_EFFECTS_PROVIDER, BOOTSTRAP_EFFECTS } from './effects'; import { STATE_UPDATES_PROVIDER } from './state-updates'; -export const BOOTSTRAP_EFFECTS = new OpaqueToken('@ngrx/effects Bootstrap Effects'); export function runEffects(...effects: any[]) { const allEffects = flatten(effects).map(effect => new Provider(BOOTSTRAP_EFFECTS, {
e8d055daa6b34881915d6cf39715da668f907db6
src/key-value-storage/LocalForageProxy.ts
src/key-value-storage/LocalForageProxy.ts
import * as localForage from 'localforage'; import {IKeyValueStorageProxy} from './KeyValueStorageProxy'; import {ISerializer} from '../serializers/serializer'; export class LocalForageProxy implements IKeyValueStorageProxy { private localForageStore: LocalForage; private serializer: ISerializer; constructor(serializer: ISerializer) { this.serializer = serializer; this.localForageStore = localForage.createInstance({ driver: <any[]>[localForage.WEBSQL, localForage.INDEXEDDB, localForage.LOCALSTORAGE] }); } public getKeys(): Promise<string[]> { return this.localForageStore.keys(); } public getItem<T>(key: string) { return this.localForageStore.getItem<T>(key) .then((value: T) => { if (this.serializer === JSON) { return value; } else { if (value) { return this.serializer.parse(<any>value); } else { return null; } } }); } public setItem<T>(key: string, value: T) { let processedValue: any = value; if (this.serializer !== JSON) { processedValue = this.serializer.stringify(value); } else { processedValue = value; } return this.localForageStore.setItem(key, processedValue); } public removeItem(key: string): Promise<void> { return this.localForageStore.removeItem(key) .then(() => { return Promise.resolve(null); }); } }
import * as localForage from 'localforage'; import {IKeyValueStorageProxy} from './KeyValueStorageProxy'; import {ISerializer} from '../serializers/serializer'; export class LocalForageProxy implements IKeyValueStorageProxy { private localForageStore: LocalForage; private serializer: ISerializer; constructor(serializer: ISerializer) { this.serializer = serializer; this.localForageStore = localForage.createInstance({ driver: <any[]>[localForage.INDEXEDDB, localForage.WEBSQL, localForage.LOCALSTORAGE] }); } public getKeys(): Promise<string[]> { return this.localForageStore.keys(); } public getItem<T>(key: string) { return this.localForageStore.getItem<T>(key) .then((value: T) => { if (this.serializer === JSON) { return value; } else { if (value) { return this.serializer.parse(<any>value) as T; } else { return null; } } }); } public setItem<T>(key: string, value: T) { let processedValue: any = value; if (this.serializer !== JSON) { processedValue = this.serializer.stringify(value); } else { processedValue = value; } return this.localForageStore.setItem(key, processedValue); } public removeItem(key: string): Promise<void> { return this.localForageStore.removeItem(key) .then(() => { return Promise.resolve(null); }); } }
Fix typing issue that fails in the latest TS version
Fix typing issue that fails in the latest TS version
TypeScript
apache-2.0
bencompton/io-source
--- +++ @@ -11,7 +11,7 @@ this.serializer = serializer; this.localForageStore = localForage.createInstance({ - driver: <any[]>[localForage.WEBSQL, localForage.INDEXEDDB, localForage.LOCALSTORAGE] + driver: <any[]>[localForage.INDEXEDDB, localForage.WEBSQL, localForage.LOCALSTORAGE] }); } @@ -26,7 +26,7 @@ return value; } else { if (value) { - return this.serializer.parse(<any>value); + return this.serializer.parse(<any>value) as T; } else { return null; }
c1ba2fa6f6f7e30f7b069f09a3532c542886c09e
coffee-chats/src/main/webapp/src/components/GroupListPage.tsx
coffee-chats/src/main/webapp/src/components/GroupListPage.tsx
import React from "react"; import {Box, Container, Grid, TextField} from "@material-ui/core"; import {GroupCard} from "./GroupCard"; export function GroupListPage() { return ( <Box mt={4}> <Container maxWidth="md"> <Grid container spacing={2}> <Grid item xs={12}> <TextField fullWidth variant="outlined" label="Search your groups"/> </Grid> {["Board Games Dublin", "Book Club", "Mountain Climbers @ Home"].map(name => <Grid item xs={12}> <GroupCard name={name}/> </Grid> )} </Grid> </Container> </Box> ); }
import React from "react"; import {Box, Container, Fab, Grid, Icon, TextField} from "@material-ui/core"; import {GroupCard} from "./GroupCard"; import {makeStyles} from "@material-ui/core/styles"; const useStyles = makeStyles((theme) => ({ extendedIcon: { marginRight: theme.spacing(.5), }, shrink: { flexGrow: 0 } })); export function GroupListPage() { const classes = useStyles(); return ( <Box mt={4}> <Container maxWidth="md"> <Grid container spacing={2}> <Grid item xs> <TextField fullWidth variant="outlined" label="Search your groups"/> </Grid> <Grid item xs className={classes.shrink}> <Fab variant="extended" color="primary"> <Icon className={classes.extendedIcon}>add</Icon> create </Fab> </Grid> {["Board Games Dublin", "Book Club", "Mountain Climbers @ Home"].map(name => <Grid item xs={12} key={name}> <GroupCard name={name}/> </Grid> )} </Grid> </Container> </Box> ); }
Add a create group button
Add a create group button
TypeScript
apache-2.0
googleinterns/step250-2020,googleinterns/step250-2020,googleinterns/step250-2020,googleinterns/step250-2020
--- +++ @@ -1,20 +1,40 @@ import React from "react"; -import {Box, Container, Grid, TextField} from "@material-ui/core"; +import {Box, Container, Fab, Grid, Icon, TextField} from "@material-ui/core"; import {GroupCard} from "./GroupCard"; +import {makeStyles} from "@material-ui/core/styles"; + +const useStyles = makeStyles((theme) => ({ + extendedIcon: { + marginRight: theme.spacing(.5), + }, + shrink: { + flexGrow: 0 + } +})); export function GroupListPage() { + const classes = useStyles(); + return ( <Box mt={4}> <Container maxWidth="md"> <Grid container spacing={2}> - <Grid item xs={12}> + <Grid item xs> <TextField fullWidth variant="outlined" label="Search your groups"/> </Grid> + <Grid item xs className={classes.shrink}> + <Fab + variant="extended" + color="primary"> + <Icon className={classes.extendedIcon}>add</Icon> + create + </Fab> + </Grid> {["Board Games Dublin", "Book Club", "Mountain Climbers @ Home"].map(name => - <Grid item xs={12}> + <Grid item xs={12} key={name}> <GroupCard name={name}/> </Grid> )}
cb5936c7f9738311ab2d8cab7fa7267bbe63a400
src/app/comingSoon/comingSoon.component.ts
src/app/comingSoon/comingSoon.component.ts
import {AfterViewInit} from "@angular/core"; import {Component} from "@angular/core"; import {Router} from "@angular/router"; @Component({ selector: 'comming-soon', templateUrl: './comingSoon.component.html' }) export class ComingSoonComponent implements AfterViewInit { constructor(private router:Router) { } getName() { if(this.router.isActive('guides', true)) return "guides"; else if(this.router.isActive('policies', true)) return "policies"; else if(this.router.isActive('showcase', true)) return "research projects to showcase"; return ""; } ngAfterViewInit() { window.scrollTo(0, 0); } }
import {AfterViewInit, OnInit} from "@angular/core"; import {Component} from "@angular/core"; import {Router, ActivatedRoute} from "@angular/router"; import {SearchService} from "../app.search.service"; @Component({ selector: 'comming-soon', templateUrl: './comingSoon.component.html' }) export class ComingSoonComponent implements OnInit, AfterViewInit { routeParamsSub: any; constructor(private router:Router, private searchService:SearchService, private route: ActivatedRoute) { } ngOnInit() { this.routeParamsSub = this.route.params.subscribe(params => { this.searchService.updateSearchParameters(undefined, {}, true); }); } getName() { if(this.router.isActive('guides', true)) return "guides"; else if(this.router.isActive('policies', true)) return "policies"; else if(this.router.isActive('showcase', true)) return "research projects to showcase"; return ""; } ngAfterViewInit() { window.scrollTo(0, 0); } ngOnDestroy() { this.routeParamsSub.unsubscribe(); } }
Update search parameters so that search values reset.
Update search parameters so that search values reset.
TypeScript
bsd-3-clause
UoA-eResearch/research-hub,UoA-eResearch/research-hub,UoA-eResearch/research-hub
--- +++ @@ -1,16 +1,25 @@ -import {AfterViewInit} from "@angular/core"; +import {AfterViewInit, OnInit} from "@angular/core"; import {Component} from "@angular/core"; -import {Router} from "@angular/router"; +import {Router, ActivatedRoute} from "@angular/router"; +import {SearchService} from "../app.search.service"; @Component({ selector: 'comming-soon', templateUrl: './comingSoon.component.html' }) -export class ComingSoonComponent implements AfterViewInit -{ +export class ComingSoonComponent implements OnInit, AfterViewInit { - constructor(private router:Router) { + routeParamsSub: any; + constructor(private router:Router, private searchService:SearchService, private route: ActivatedRoute) { + + } + + ngOnInit() + { + this.routeParamsSub = this.route.params.subscribe(params => { + this.searchService.updateSearchParameters(undefined, {}, true); + }); } getName() @@ -27,4 +36,8 @@ ngAfterViewInit() { window.scrollTo(0, 0); } + + ngOnDestroy() { + this.routeParamsSub.unsubscribe(); + } }
aa3b1b1bab2538576db2e3f99b944fe3776c9edd
app/src/ui/lib/theme-change-monitor.ts
app/src/ui/lib/theme-change-monitor.ts
import { remote } from 'electron' import { ApplicationTheme } from './application-theme' import { IDisposable, Disposable, Emitter } from 'event-kit' import { supportsDarkMode, isDarkModeEnabled } from './dark-theme' class ThemeChangeMonitor implements IDisposable { private readonly emitter = new Emitter() public constructor() { this.subscribe() } public dispose() { remote.nativeTheme.removeAllListeners() } private subscribe = () => { if (!supportsDarkMode()) { return } remote.nativeTheme.addListener('updated', this.onThemeNotificationFromOS) } private onThemeNotificationFromOS = (event: string, userInfo: any) => { const darkModeEnabled = isDarkModeEnabled() const theme = darkModeEnabled ? ApplicationTheme.Dark : ApplicationTheme.Light this.emitThemeChanged(theme) } public onThemeChanged(fn: (theme: ApplicationTheme) => void): Disposable { return this.emitter.on('theme-changed', fn) } private emitThemeChanged(theme: ApplicationTheme) { this.emitter.emit('theme-changed', theme) } } // this becomes our singleton that we can subscribe to from anywhere export const themeChangeMonitor = new ThemeChangeMonitor() // this ensures we cleanup any existing subscription on exit remote.app.on('will-quit', () => { themeChangeMonitor.dispose() })
import { remote } from 'electron' import { ApplicationTheme } from './application-theme' import { IDisposable, Disposable, Emitter } from 'event-kit' import { supportsDarkMode, isDarkModeEnabled } from './dark-theme' class ThemeChangeMonitor implements IDisposable { private readonly emitter = new Emitter() public constructor() { this.subscribe() } public dispose() { if (remote.nativeTheme) { remote.nativeTheme.removeAllListeners() } } private subscribe = () => { if (!supportsDarkMode() || !remote.nativeTheme) { return } remote.nativeTheme.addListener('updated', this.onThemeNotificationFromOS) } private onThemeNotificationFromOS = (event: string, userInfo: any) => { const darkModeEnabled = isDarkModeEnabled() const theme = darkModeEnabled ? ApplicationTheme.Dark : ApplicationTheme.Light this.emitThemeChanged(theme) } public onThemeChanged(fn: (theme: ApplicationTheme) => void): Disposable { return this.emitter.on('theme-changed', fn) } private emitThemeChanged(theme: ApplicationTheme) { this.emitter.emit('theme-changed', theme) } } // this becomes our singleton that we can subscribe to from anywhere export const themeChangeMonitor = new ThemeChangeMonitor() // this ensures we cleanup any existing subscription on exit remote.app.on('will-quit', () => { themeChangeMonitor.dispose() })
Fix nativeTheme errors in tests on Windows 10 1809+ and Server 2019+
Fix nativeTheme errors in tests on Windows 10 1809+ and Server 2019+
TypeScript
mit
say25/desktop,say25/desktop,j-f1/forked-desktop,shiftkey/desktop,artivilla/desktop,say25/desktop,desktop/desktop,artivilla/desktop,shiftkey/desktop,j-f1/forked-desktop,shiftkey/desktop,artivilla/desktop,desktop/desktop,desktop/desktop,j-f1/forked-desktop,j-f1/forked-desktop,say25/desktop,shiftkey/desktop,artivilla/desktop,desktop/desktop
--- +++ @@ -11,11 +11,13 @@ } public dispose() { - remote.nativeTheme.removeAllListeners() + if (remote.nativeTheme) { + remote.nativeTheme.removeAllListeners() + } } private subscribe = () => { - if (!supportsDarkMode()) { + if (!supportsDarkMode() || !remote.nativeTheme) { return }
265a20787f6982e5b0373656efbc01512c179576
app/src/ui/cli-installed/cli-installed.tsx
app/src/ui/cli-installed/cli-installed.tsx
import * as React from 'react' import { Button } from '../lib/button' import { ButtonGroup } from '../lib/button-group' import { Dialog, DialogContent, DialogFooter } from '../dialog' import { InstalledCLIPath } from '../lib/install-cli' interface ICLIInstalledProps { /** Called when the popup should be dismissed. */ readonly onDismissed: () => void } /** Tell the user the CLI tool was successfully installed. */ export class CLIInstalled extends React.Component<ICLIInstalledProps, {}> { public render() { return ( <Dialog title={ __DARWIN__ ? 'Command Line Tool Installed' : 'Command line tool installed' } onDismissed={this.props.onDismissed} onSubmit={this.props.onDismissed} > <DialogContent> <div> The command line tool has been installed at{' '} <strong>{InstalledCLIPath}</strong>. </div> </DialogContent> <DialogFooter> <ButtonGroup> <Button type="submit">OK</Button> </ButtonGroup> </DialogFooter> </Dialog> ) } }
import * as React from 'react' import { Dialog, DialogContent, DefaultDialogFooter } from '../dialog' import { InstalledCLIPath } from '../lib/install-cli' interface ICLIInstalledProps { /** Called when the popup should be dismissed. */ readonly onDismissed: () => void } /** Tell the user the CLI tool was successfully installed. */ export class CLIInstalled extends React.Component<ICLIInstalledProps, {}> { public render() { return ( <Dialog title={ __DARWIN__ ? 'Command Line Tool Installed' : 'Command line tool installed' } onDismissed={this.props.onDismissed} onSubmit={this.props.onDismissed} > <DialogContent> <div> The command line tool has been installed at{' '} <strong>{InstalledCLIPath}</strong>. </div> </DialogContent> <DefaultDialogFooter buttonText="Ok" /> </Dialog> ) } }
Convert cli installed notice dialog to default dialog footer
Convert cli installed notice dialog to default dialog footer
TypeScript
mit
desktop/desktop,say25/desktop,kactus-io/kactus,shiftkey/desktop,say25/desktop,artivilla/desktop,shiftkey/desktop,j-f1/forked-desktop,kactus-io/kactus,say25/desktop,shiftkey/desktop,artivilla/desktop,j-f1/forked-desktop,say25/desktop,desktop/desktop,desktop/desktop,artivilla/desktop,j-f1/forked-desktop,kactus-io/kactus,kactus-io/kactus,shiftkey/desktop,artivilla/desktop,desktop/desktop,j-f1/forked-desktop
--- +++ @@ -1,7 +1,5 @@ import * as React from 'react' -import { Button } from '../lib/button' -import { ButtonGroup } from '../lib/button-group' -import { Dialog, DialogContent, DialogFooter } from '../dialog' +import { Dialog, DialogContent, DefaultDialogFooter } from '../dialog' import { InstalledCLIPath } from '../lib/install-cli' interface ICLIInstalledProps { @@ -28,11 +26,7 @@ <strong>{InstalledCLIPath}</strong>. </div> </DialogContent> - <DialogFooter> - <ButtonGroup> - <Button type="submit">OK</Button> - </ButtonGroup> - </DialogFooter> + <DefaultDialogFooter buttonText="Ok" /> </Dialog> ) }
1ca79ae147725b96f0f6a494f0151c4ab649c55d
app/core/images/row/image-width-calculator.ts
app/core/images/row/image-width-calculator.ts
/** * @author Thomas Kleinke */ export module ImageWidthCalculator { export function computeWidth(imageWidth: number, imageHeight: number, targetHeight: number, maxWidth: number): number { const targetWidth: number = Math.ceil(Math.min((targetHeight / imageHeight), 1) * imageWidth); return Math.min(targetWidth, maxWidth); } }
/** * @author Thomas Kleinke */ export module ImageWidthCalculator { export function computeWidth(imageWidth: number, imageHeight: number, targetHeight: number, maxWidth: number): number { const targetWidth: number = Math.round(Math.min((targetHeight / imageHeight), 1) * imageWidth); return Math.min(targetWidth, maxWidth); } }
Switch rounding function in ImageWidthCalculator
Switch rounding function in ImageWidthCalculator
TypeScript
apache-2.0
codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client
--- +++ @@ -6,7 +6,7 @@ export function computeWidth(imageWidth: number, imageHeight: number, targetHeight: number, maxWidth: number): number { - const targetWidth: number = Math.ceil(Math.min((targetHeight / imageHeight), 1) * imageWidth); + const targetWidth: number = Math.round(Math.min((targetHeight / imageHeight), 1) * imageWidth); return Math.min(targetWidth, maxWidth); }
fa35a1e5563a8a47625e304982868cfcdbf0ee72
coffee-chats/src/main/webapp/src/format.ts
coffee-chats/src/main/webapp/src/format.ts
/** * Joins a list of strings to produce a human readable string: * * > humanReadableJoin(["apple", "banana", "orange"]) * "apple, banana, and orange" */ export function humanReadableJoin(list: string[]) { return list.concat(list.splice(-2, 2).join(" and ")).join(", "); }
/** * Joins a list of strings to produce a human readable string: * * > humanReadableJoin(["apple", "banana", "orange"]) * "apple, banana, and orange" */ export function humanReadableJoin(list: string[]) { list = list.slice(); return list.concat(list.splice(-2, 2).join(" and ")).join(", "); }
Fix humanReadableJoin not being a pure function
Fix humanReadableJoin not being a pure function
TypeScript
apache-2.0
googleinterns/step250-2020,googleinterns/step250-2020,googleinterns/step250-2020,googleinterns/step250-2020
--- +++ @@ -5,5 +5,6 @@ * "apple, banana, and orange" */ export function humanReadableJoin(list: string[]) { + list = list.slice(); return list.concat(list.splice(-2, 2).join(" and ")).join(", "); }
ea27bf8177e49c200c22f5392f40503ecdb09da8
bokehjs/test/core/index.ts
bokehjs/test/core/index.ts
import "./signaling" import "./enums" import "./has_props" import "./layout" import "./logging" import "./properties" import "./property_mixins" import "./util" import "./selection_manager" import "./selector" import "./ui_events"
import "./signaling" import "./enums" import "./has_props" import "./layout" import "./logging" import "./properties" import "./property_mixins" import "./util" import "./selector" import "./ui_events"
Remove SelectionManager import from JS tests
Remove SelectionManager import from JS tests
TypeScript
bsd-3-clause
rs2/bokeh,Karel-van-de-Plassche/bokeh,timsnyder/bokeh,aavanian/bokeh,timsnyder/bokeh,timsnyder/bokeh,rs2/bokeh,rs2/bokeh,rs2/bokeh,dennisobrien/bokeh,stonebig/bokeh,jakirkham/bokeh,stonebig/bokeh,stonebig/bokeh,dennisobrien/bokeh,timsnyder/bokeh,ericmjl/bokeh,philippjfr/bokeh,DuCorey/bokeh,dennisobrien/bokeh,mindriot101/bokeh,philippjfr/bokeh,dennisobrien/bokeh,Karel-van-de-Plassche/bokeh,ericmjl/bokeh,dennisobrien/bokeh,DuCorey/bokeh,aavanian/bokeh,bokeh/bokeh,jakirkham/bokeh,aavanian/bokeh,timsnyder/bokeh,bokeh/bokeh,bokeh/bokeh,Karel-van-de-Plassche/bokeh,mindriot101/bokeh,ericmjl/bokeh,bokeh/bokeh,jakirkham/bokeh,stonebig/bokeh,aavanian/bokeh,ericmjl/bokeh,jakirkham/bokeh,jakirkham/bokeh,rs2/bokeh,Karel-van-de-Plassche/bokeh,mindriot101/bokeh,philippjfr/bokeh,DuCorey/bokeh,Karel-van-de-Plassche/bokeh,DuCorey/bokeh,philippjfr/bokeh,DuCorey/bokeh,aavanian/bokeh,bokeh/bokeh,ericmjl/bokeh,philippjfr/bokeh,mindriot101/bokeh
--- +++ @@ -6,6 +6,5 @@ import "./properties" import "./property_mixins" import "./util" -import "./selection_manager" import "./selector" import "./ui_events"
40916a552f7ccdbc62c934716dbd74727b2d5d84
scripts/cli/utils/useSpinner.ts
scripts/cli/utils/useSpinner.ts
import ora from 'ora'; type FnToSpin<T> = (options: T) => Promise<void>; export const useSpinner = <T>(spinnerLabel: string, fn: FnToSpin<T>, killProcess = true) => { return async (options: T) => { const spinner = new ora(spinnerLabel); spinner.start(); try { await fn(options); spinner.succeed(); } catch (e) { spinner.fail(); console.log(e); if (killProcess) { process.exit(1); } } }; };
import ora from 'ora'; type FnToSpin<T> = (options: T) => Promise<void>; export const useSpinner = <T>(spinnerLabel: string, fn: FnToSpin<T>, killProcess = true) => { return async (options: T) => { const spinner = ora(spinnerLabel); spinner.start(); try { await fn(options); spinner.succeed(); } catch (e) { spinner.fail(); console.log(e); if (killProcess) { process.exit(1); } } }; };
Call ora instead of instantiating it
Call ora instead of instantiating it
TypeScript
agpl-3.0
grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana
--- +++ @@ -4,7 +4,7 @@ export const useSpinner = <T>(spinnerLabel: string, fn: FnToSpin<T>, killProcess = true) => { return async (options: T) => { - const spinner = new ora(spinnerLabel); + const spinner = ora(spinnerLabel); spinner.start(); try { await fn(options);
f3ba44e02964c60dd674645474bcc68cc2b55d11
tests/__tests__/tsx-errors.spec.ts
tests/__tests__/tsx-errors.spec.ts
import runJest from '../__helpers__/runJest'; import * as React from 'react'; describe('TSX Errors', () => { it('should show the correct error locations in the typescript files', () => { const result = runJest('../button', ['--no-cache', '-u']); const stderr = result.stderr.toString(); expect(result.status).toBe(1); expect(stderr).toContain('Button.tsx:22:17'); expect(stderr).toContain('Button.test.tsx:16:12'); }); });
import runJest from '../__helpers__/runJest'; import * as React from 'react'; describe('TSX Errors', () => { it('should show the correct error locations in the typescript files', () => { const result = runJest('../button', ['--no-cache', '-u']); const stderr = result.stderr.toString(); expect(result.status).toBe(1); expect(stderr).toContain('Button.tsx:22:17'); expect(stderr).toContain('Button.test.tsx:19:12'); }); });
Fix line number in a test
Fix line number in a test
TypeScript
mit
kulshekhar/ts-jest,kulshekhar/ts-jest
--- +++ @@ -9,6 +9,6 @@ expect(result.status).toBe(1); expect(stderr).toContain('Button.tsx:22:17'); - expect(stderr).toContain('Button.test.tsx:16:12'); + expect(stderr).toContain('Button.test.tsx:19:12'); }); });
3ea0cdea91f174c9e89cd64d471cd021941197a9
src/renderer/app/components/Menu/styles.ts
src/renderer/app/components/Menu/styles.ts
import styled, { css } from 'styled-components'; import { shadows } from '@mixins'; export const Container = styled.div` width: 300px; padding-top: 4px; padding-bottom: 4px; position: absolute; top: 56px; right: 0; background-color: #fff; z-index: 9999; border-radius: 4px; transform-origin: top right; -webkit-app-region: no-drag; box-sizing: border-box; box-shadow: ${shadows(6)}; ${({ visible }: { visible: boolean }) => css` opacity: ${visible ? 1 : 0}; pointer-events: ${visible ? 'all' : 'none'}; `}; `;
import styled, { css } from 'styled-components'; import { shadows } from '@mixins'; import { EASE_FUNCTION } from '~/constants'; export const Container = styled.div` width: 300px; padding-top: 4px; padding-bottom: 4px; position: absolute; top: 56px; right: 0; background-color: #fff; z-index: 9999; border-radius: 4px; transform-origin: top right; -webkit-app-region: no-drag; will-change: opacity; box-sizing: border-box; box-shadow: ${shadows(6)}; ${({ visible }: { visible: boolean }) => css` opacity: ${visible ? 1 : 0}; pointer-events: ${visible ? 'all' : 'none'}; transform: ${visible ? 'scale(1)' : 'scale(0)'}; transition: ${`0.3s ${EASE_FUNCTION} transform, ${ visible ? 0.1 : 0.2 }s opacity`}; `}; `;
Add toggle animation to menu
Add toggle animation to menu
TypeScript
apache-2.0
Nersent/Wexond,Nersent/Wexond
--- +++ @@ -1,6 +1,7 @@ import styled, { css } from 'styled-components'; import { shadows } from '@mixins'; +import { EASE_FUNCTION } from '~/constants'; export const Container = styled.div` width: 300px; @@ -14,11 +15,16 @@ border-radius: 4px; transform-origin: top right; -webkit-app-region: no-drag; + will-change: opacity; box-sizing: border-box; box-shadow: ${shadows(6)}; ${({ visible }: { visible: boolean }) => css` opacity: ${visible ? 1 : 0}; pointer-events: ${visible ? 'all' : 'none'}; + transform: ${visible ? 'scale(1)' : 'scale(0)'}; + transition: ${`0.3s ${EASE_FUNCTION} transform, ${ + visible ? 0.1 : 0.2 + }s opacity`}; `}; `;
1ad77a76cd70caef63c2847961d15279037c1962
src/shared/components/ErrorMessage.tsx
src/shared/components/ErrorMessage.tsx
import * as React from "react"; import {observer} from "mobx-react"; import ErrorIcon from "./ErrorIcon"; export interface IErrorMessageProps { message?:string; } @observer export default class ErrorMessage extends React.Component<IErrorMessageProps, {}> { static defaultProps = { message: "Error encountered." }; render() { return <span> <i className="fa fa-md fa-exclamation-triangle" style={{ color: "#BB1700", cursor: "pointer", marginRight:7 }} /> {this.props.message!} Please let us know about this error and how you got here at <b style={{whiteSpace:"nowrap"}}>cbioportal at googlegroups dot com.</b> </span> } }
import * as React from "react"; import {observer} from "mobx-react"; import ErrorIcon from "./ErrorIcon"; import AppConfig from "appConfig"; export interface IErrorMessageProps { message?:string; } @observer export default class ErrorMessage extends React.Component<IErrorMessageProps, {}> { static defaultProps = { message: "Error encountered." }; render() { return <span> <i className="fa fa-md fa-exclamation-triangle" style={{ color: "#BB1700", cursor: "pointer", marginRight:7 }} /> {this.props.message!} Please let us know about this error and how you got here at <b style={{ whiteSpace: "nowrap" }}><a href={`mailto:${AppConfig.serverConfig.skin_email_contact}`}>{AppConfig.serverConfig.skin_email_contact}</a></b> </span> } }
Customize contact email in Error message
Customize contact email in Error message Former-commit-id: 3e39c59092b5dc1732445510775bcf5ab228a9c7
TypeScript
agpl-3.0
cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend,alisman/cbioportal-frontend,alisman/cbioportal-frontend,alisman/cbioportal-frontend,cBioPortal/cbioportal-frontend,alisman/cbioportal-frontend,cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend,alisman/cbioportal-frontend,alisman/cbioportal-frontend
--- +++ @@ -1,6 +1,7 @@ import * as React from "react"; import {observer} from "mobx-react"; import ErrorIcon from "./ErrorIcon"; +import AppConfig from "appConfig"; export interface IErrorMessageProps { message?:string; @@ -22,7 +23,7 @@ marginRight:7 }} /> - {this.props.message!} Please let us know about this error and how you got here at <b style={{whiteSpace:"nowrap"}}>cbioportal at googlegroups dot com.</b> + {this.props.message!} Please let us know about this error and how you got here at <b style={{ whiteSpace: "nowrap" }}><a href={`mailto:${AppConfig.serverConfig.skin_email_contact}`}>{AppConfig.serverConfig.skin_email_contact}</a></b> </span> } }
34c112a5db598fdbbe5f929a0120b5712d07589d
src/v2/components/UserSettings/mutations/updateAccountMutation.ts
src/v2/components/UserSettings/mutations/updateAccountMutation.ts
import gql from 'graphql-tag' export default gql` mutation UpdateAccountMutation( $email: String $first_name: String $last_name: String $show_nsfw: Boolean $home_path: String $receive_email: String $receive_newsletter: Boolean $receive_tips_emails: Boolean $receive_group_premium_emails: Boolean $show_tour: Boolean $exclude_from_indexes: Boolean $bio: String $custom_badge_url: String $password: String $password_confirmation: String ) { update_account( input: { email: $email first_name: $first_name last_name: $last_name receive_email: $receive_email bio: $bio show_nsfw: $show_nsfw custom_badge_url: $custom_badge_url home_path: $home_path receive_newsletter: $receive_newsletter receive_tips_emails: $receive_tips_emails receive_group_premium_emails: $receive_group_premium_emails show_tour: $show_tour exclude_from_indexes: $exclude_from_indexes password: $password password_confirmation: $password_confirmation } ) { me { id email name first_name bio settings { receive_email show_nsfw } } } } `
import gql from 'graphql-tag' export default gql` mutation UpdateAccountMutation( $email: String $first_name: String $last_name: String $show_nsfw: Boolean $home_path: String $receive_email: String $receive_newsletter: Boolean $receive_tips_emails: Boolean $receive_group_premium_emails: Boolean $show_tour: Boolean $exclude_from_indexes: Boolean $bio: String $custom_badge_url: String $password: String $password_confirmation: String ) { update_account( input: { email: $email first_name: $first_name last_name: $last_name receive_email: $receive_email bio: $bio show_nsfw: $show_nsfw custom_badge_url: $custom_badge_url home_path: $home_path receive_newsletter: $receive_newsletter receive_tips_emails: $receive_tips_emails receive_group_premium_emails: $receive_group_premium_emails show_tour: $show_tour exclude_from_indexes: $exclude_from_indexes password: $password password_confirmation: $password_confirmation } ) { me { id email name first_name bio settings { receive_email receive_tips_emails home_path receive_group_premium_emails exclude_from_indexes receive_newsletter show_nsfw } } } } `
Add fields to mutation response
Add fields to mutation response
TypeScript
mit
aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell
--- +++ @@ -45,6 +45,11 @@ bio settings { receive_email + receive_tips_emails + home_path + receive_group_premium_emails + exclude_from_indexes + receive_newsletter show_nsfw } }
eb89c92f9c241e675b01c80f6ced09be5dc4f914
src/theme/helpers/getMemberSymbol.ts
src/theme/helpers/getMemberSymbol.ts
/** * Returns the member symbol * @param kindString */ export function getMemberSymbol(kindString: string) { let symbol = ''; switch (kindString) { case 'Constructor signature': symbol = '⊕ '; break; case 'Call signature': symbol = '▸ '; break; case 'Type alias': symbol = 'Τ'; break; case 'Property': case 'Variable': symbol = '● '; break; default: } return symbol; }
/** * Returns the member symbol * @param kindString */ export function getMemberSymbol(kindString: string) { let symbol = ''; switch (kindString) { case 'Constructor signature': symbol = '⊕ '; break; case 'Call signature': symbol = '▸ '; break; case 'Type alias': symbol = 'Ƭ '; break; case 'Property': case 'Variable': symbol = '● '; break; default: } return symbol; }
Change type alias prefix symbol and formatting
Change type alias prefix symbol and formatting
TypeScript
mit
tgreyuk/typedoc-plugin-markdown,tgreyuk/typedoc-plugin-markdown
--- +++ @@ -12,7 +12,7 @@ symbol = '▸ '; break; case 'Type alias': - symbol = 'Τ'; + symbol = 'Ƭ '; break; case 'Property': case 'Variable':
2298690b216938cd9b93b6fae97f83e14d106cc0
jupyter-js-widgets/src/embed-manager.ts
jupyter-js-widgets/src/embed-manager.ts
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. import { ManagerBase } from './manager-base'; export class EmbedManager extends ManagerBase<HTMLElement> { display_widget_state(models, el) { return this.set_state(models, { el: el, displayOnce: true }); } display_view(msg, view, options) { return Promise.resolve(view).then(function(view) { options.el.appendChild(view.el); view.trigger('displayed'); view.on('remove', function() { console.log('View removed', view); }); return view; }); }; _get_comm_info() { return Promise.resolve({}); }; _create_comm() { return Promise.resolve({}); }; require_error(success_callback) { /** * Takes a requirejs success handler and returns a requirejs error handler * that attempts loading the module from npmcdn. */ return function(err) { var failedId = err.requireModules && err.requireModules[0]; if (failedId) { // TODO: Get typing to work for requirejs (window as any).require(['https://npmcdn.com/' + failedId + '/dist/index.js'], success_callback); } else { throw err; } }; } };
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. import { ManagerBase } from './manager-base'; export class EmbedManager extends ManagerBase<HTMLElement> { display_widget_state(models, el) { return this.set_state(models, { el: el, displayOnce: true }); } display_view(msg, view, options) { return Promise.resolve(view).then(function(view) { options.el.appendChild(view.el); view.trigger('displayed'); view.on('remove', function() { console.log('View removed', view); }); return view; }); }; _get_comm_info() { return Promise.resolve({}); }; _create_comm() { return Promise.resolve({ on_close: () => {}, on_msg: () => {}, close: () => {} }); }; /** * Takes a requirejs success handler and returns a requirejs error handler * that attempts loading the module from npmcdn. */ require_error(success_callback) { return function(err) { var failedId = err.requireModules && err.requireModules[0]; if (failedId) { // TODO: Get typing to work for requirejs (window as any).require(['https://npmcdn.com/' + failedId + '/dist/index.js'], success_callback); } else { throw err; } }; } };
Return a fake comm object
Return a fake comm object
TypeScript
bsd-3-clause
ipython/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,cornhundred/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets
--- +++ @@ -27,14 +27,18 @@ }; _create_comm() { - return Promise.resolve({}); + return Promise.resolve({ + on_close: () => {}, + on_msg: () => {}, + close: () => {} + }); }; + /** + * Takes a requirejs success handler and returns a requirejs error handler + * that attempts loading the module from npmcdn. + */ require_error(success_callback) { - /** - * Takes a requirejs success handler and returns a requirejs error handler - * that attempts loading the module from npmcdn. - */ return function(err) { var failedId = err.requireModules && err.requireModules[0]; if (failedId) { @@ -44,7 +48,5 @@ throw err; } }; -} - - + } };
b5ee5af9c2763ed3fa45679cd3e3e35404bbcbd4
src/services/drawers/ellipse-drawer/dynamic-ellipse-drawer.service.ts
src/services/drawers/ellipse-drawer/dynamic-ellipse-drawer.service.ts
import { CesiumService } from '../../cesium/cesium.service'; import { Injectable } from '@angular/core'; import { SimpleDrawerService } from '../simple-drawer/simple-drawer.service'; import { EllipsePrimitive } from 'primitive-primitives'; import { Checker } from '../../../utils/checker'; /** * This drawer is responsible for creating the dynamic version of the ellipse component. * We are using the primitive-primitives implementation of an ellipse. see: https://github.com/gotenxds/Primitive-primitives * This allows us to change the position of the ellipses without creating a new primitive object * as Cesium does not allow updating an ellipse. */ @Injectable() export class DynamicEllipseDrawerService extends SimpleDrawerService { constructor(cesiumService: CesiumService) { super(Cesium.PrimitiveCollection, cesiumService); } add(cesiumProps: any): any { Checker.throwIfAnyNotPresent(cesiumProps, ['center', 'semiMajorAxis', 'semiMinorAxis', 'rotation']); return super.add(new EllipsePrimitive(cesiumProps)); } update(ellipse: any, cesiumProps: any): any { ellipse.updateLocationData(cesiumProps); return ellipse; } }
import { CesiumService } from '../../cesium/cesium.service'; import { Injectable } from '@angular/core'; import { SimpleDrawerService } from '../simple-drawer/simple-drawer.service'; import { EllipsePrimitive } from 'primitive-primitives'; import { Checker } from '../../../utils/checker'; /** * This drawer is responsible for creating the dynamic version of the ellipse component. * We are using the primitive-primitives implementation of an ellipse. see: https://github.com/gotenxds/Primitive-primitives * This allows us to change the position of the ellipses without creating a new primitive object * as Cesium does not allow updating an ellipse. */ @Injectable() export class DynamicEllipseDrawerService extends SimpleDrawerService { constructor(cesiumService: CesiumService) { super(Cesium.PrimitiveCollection, cesiumService); } add(cesiumProps: any): any { Checker.throwIfAnyNotPresent(cesiumProps, ['center', 'semiMajorAxis', 'semiMinorAxis']); return super.add(new EllipsePrimitive(cesiumProps)); } update(ellipse: any, cesiumProps: any): any { ellipse.updateLocationData(cesiumProps); return ellipse; } }
Change that when there is no rotation in props' the checker won't throw an error.
Change that when there is no rotation in props' the checker won't throw an error.
TypeScript
mit
TGFTech/angular-cesium,TGFTech/angular-cesium,TGFTech/angular-cesium
--- +++ @@ -18,7 +18,7 @@ } add(cesiumProps: any): any { - Checker.throwIfAnyNotPresent(cesiumProps, ['center', 'semiMajorAxis', 'semiMinorAxis', 'rotation']); + Checker.throwIfAnyNotPresent(cesiumProps, ['center', 'semiMajorAxis', 'semiMinorAxis']); return super.add(new EllipsePrimitive(cesiumProps)); }
e89ff7648b4c00942fc115cb115441acd5584171
manup-demo/src/app/app.component.ts
manup-demo/src/app/app.component.ts
import { Component } from '@angular/core'; import { Platform } from 'ionic-angular'; import { StatusBar, Splashscreen } from 'ionic-native'; import { TabsPage } from '../pages/tabs/tabs'; import { ManUpService } from 'ionic-manup'; import { TranslateService } from 'ng2-translate' @Component({ templateUrl: 'app.html' }) export class MyApp { rootPage = TabsPage; constructor(platform: Platform, private manup: ManUpService, private translate: TranslateService) { translate.setDefaultLang('en'); platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. StatusBar.styleDefault(); Splashscreen.hide(); manup.validate(); }); } }
import { Component } from '@angular/core'; import { Platform } from 'ionic-angular'; import { StatusBar, Splashscreen } from 'ionic-native'; import { TabsPage } from '../pages/tabs/tabs'; import { ManUpService } from 'ionic-manup'; import { TranslateService } from 'ng2-translate' @Component({ templateUrl: 'app.html' }) export class MyApp { rootPage = TabsPage; constructor(platform: Platform, private manup: ManUpService, private translate: TranslateService) { translate.setDefaultLang('es'); platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. StatusBar.styleDefault(); Splashscreen.hide(); manup.validate(); }); } }
Set demo language to spanish
Set demo language to spanish
TypeScript
mit
NextFaze/ionic-manup,NextFaze/ionic-manup,NextFaze/ionic-manup
--- +++ @@ -14,7 +14,7 @@ rootPage = TabsPage; constructor(platform: Platform, private manup: ManUpService, private translate: TranslateService) { - translate.setDefaultLang('en'); + translate.setDefaultLang('es'); platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need.
4cee646f857d7e2564f762088ed5d9b9630bfd22
Assets/.tiled/platforms.tsx
Assets/.tiled/platforms.tsx
<?xml version="1.0" encoding="UTF-8"?> <tileset name="platforms" tilewidth="128" tileheight="128" spacing="1" tilecount="4" columns="4"> <image source="C:/Users/Monkey/Desktop/platform sprites.png" width="515" height="128"/> <tile id="0"> <objectgroup draworder="index"> <object id="1" x="-0.333333" y="0.666667" width="128" height="74"/> </objectgroup> </tile> <tile id="1"> <objectgroup draworder="index"> <object id="1" x="52.6667" y="0.666667" width="74" height="128"/> </objectgroup> </tile> <tile id="2"> <objectgroup draworder="index"> <object id="1" x="0" y="52.6667" width="128" height="74"/> </objectgroup> </tile> <tile id="3"> <objectgroup draworder="index"> <object id="1" x="0.666667" y="0" width="74" height="128"/> </objectgroup> </tile> </tileset>
<?xml version="1.0" encoding="UTF-8"?> <tileset name="platforms" tilewidth="128" tileheight="128" spacing="1" tilecount="4" columns="4"> <image source="../Tiled2Unity/Textures/platform sprites.png" width="515" height="128"/> <tile id="0"> <objectgroup draworder="index"> <object id="1" x="-0.333333" y="0.666667" width="128" height="74"/> </objectgroup> </tile> <tile id="1"> <objectgroup draworder="index"> <object id="1" x="52.6667" y="0.666667" width="74" height="128"/> </objectgroup> </tile> <tile id="2"> <objectgroup draworder="index"> <object id="1" x="0" y="52.6667" width="128" height="74"/> </objectgroup> </tile> <tile id="3"> <objectgroup draworder="index"> <object id="1" x="0.666667" y="0" width="74" height="128"/> </objectgroup> </tile> </tileset>
Make tile image relative to project
Make tile image relative to project [skip ci]
TypeScript
mit
virtuoushub/game-off-2016,virtuoushub/game-off-2016,whoa-algebraic/game-off-2016,whoa-algebraic/game-off-2016,virtuoushub/game-off-2016,whoa-algebraic/game-off-2016
--- +++ @@ -1,6 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?> <tileset name="platforms" tilewidth="128" tileheight="128" spacing="1" tilecount="4" columns="4"> - <image source="C:/Users/Monkey/Desktop/platform sprites.png" width="515" height="128"/> + <image source="../Tiled2Unity/Textures/platform sprites.png" width="515" height="128"/> <tile id="0"> <objectgroup draworder="index"> <object id="1" x="-0.333333" y="0.666667" width="128" height="74"/>
763aa6e00ef2d5749c2a5d61cae77cd2e4457350
src/__tests__/ModuleBundler.test.ts
src/__tests__/ModuleBundler.test.ts
import * as Archiver from 'archiver'; import * as path from 'path'; import { Logger } from '../lib/Logger'; import { ModuleBundler } from '../ModuleBundler'; describe('ModuleBundler', () => { const servicePath = path.resolve(__dirname, '../../test/1.0'); const artifact = Archiver('zip', { store: true }); const moduleBundler = new ModuleBundler({ servicePath, logger: new Logger(), archive: artifact, }); const { dependencies } = require(`${servicePath}/package.json`); beforeAll(async () => { await moduleBundler.bundle({}); }); Object.keys(dependencies).forEach((dep) => { it(`Has bundled dependency ${dep}`, async () => { expect( moduleBundler.modules.some(({ name }) => name === dep), ).toBeTruthy(); }); }); });
import * as Archiver from 'archiver'; import * as path from 'path'; import { Logger } from '../lib/Logger'; import { ModuleBundler } from '../ModuleBundler'; describe('ModuleBundler', () => { const servicePath = path.resolve(__dirname, '../../test/1.0'); jasmine.DEFAULT_TIMEOUT_INTERVAL = 31000; const artifact = Archiver('zip', { store: true }); const moduleBundler = new ModuleBundler({ servicePath, logger: new Logger(), archive: artifact, }); const { dependencies } = require(`${servicePath}/package.json`); beforeAll(async () => { await moduleBundler.bundle({}); }); Object.keys(dependencies).forEach((dep) => { it(`Has bundled dependency ${dep}`, async () => { expect( moduleBundler.modules.some(({ name }) => name === dep), ).toBeTruthy(); }); }); });
Set jasmine timeout cus travis
Set jasmine timeout cus travis
TypeScript
mit
nfour/serverless-build-plugin,nfour/serverless-build-plugin,nfour/serverless-build-plugin
--- +++ @@ -5,6 +5,8 @@ describe('ModuleBundler', () => { const servicePath = path.resolve(__dirname, '../../test/1.0'); + + jasmine.DEFAULT_TIMEOUT_INTERVAL = 31000; const artifact = Archiver('zip', { store: true }); const moduleBundler = new ModuleBundler({
832533c287b8e6497fd246619338c763dee9464b
src/components/SearchCard/TOpticonButton.tsx
src/components/SearchCard/TOpticonButton.tsx
import * as React from 'react'; import { Button } from '@shopify/polaris'; import { Tooltip } from '@blueprintjs/core'; import { TOpticonData, RequesterScores } from '../../types'; import { turkopticonBaseUrl } from '../../constants'; export interface Props { readonly requesterId: string; readonly turkopticon?: TOpticonData; } class TOpticonButton extends React.PureComponent<Props, never> { static generateTooltipContent = (scores: RequesterScores) => `Pay: ${scores.pay}. Comm: ${scores.comm}. Fair: ${scores.fair}. Fast: ${scores.fast}.`; public render() { const { requesterId, turkopticon } = this.props; return turkopticon ? ( <Tooltip content={TOpticonButton.generateTooltipContent(turkopticon.attrs)} > <Button plain external url={turkopticonBaseUrl + requesterId}> T.O. Page </Button> </Tooltip> ) : ( <Button plain disabled external url={turkopticonBaseUrl + requesterId}> No T.O. data. </Button> ); } } export default TOpticonButton;
import * as React from 'react'; import { Button } from '@shopify/polaris'; import { Tooltip } from '@blueprintjs/core'; import { TOpticonData, RequesterScores } from '../../types'; import { turkopticonBaseUrl } from '../../constants/urls'; export interface Props { readonly requesterId: string; readonly turkopticon?: TOpticonData; } class TOpticonButton extends React.PureComponent<Props, never> { static generateTooltipContent = (scores: RequesterScores) => `Pay: ${scores.pay}. Comm: ${scores.comm}. Fair: ${scores.fair}. Fast: ${scores.fast}.`; public render() { const { requesterId, turkopticon } = this.props; return turkopticon ? ( <Tooltip content={TOpticonButton.generateTooltipContent(turkopticon.attrs)} > <Button plain external url={turkopticonBaseUrl + requesterId}> T.O. Page </Button> </Tooltip> ) : ( <Button plain disabled external url={turkopticonBaseUrl + requesterId}> No T.O. data. </Button> ); } } export default TOpticonButton;
Update file path fo turkopticonBaseUrl.
Update file path fo turkopticonBaseUrl.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -2,7 +2,7 @@ import { Button } from '@shopify/polaris'; import { Tooltip } from '@blueprintjs/core'; import { TOpticonData, RequesterScores } from '../../types'; -import { turkopticonBaseUrl } from '../../constants'; +import { turkopticonBaseUrl } from '../../constants/urls'; export interface Props { readonly requesterId: string;
5c5b1e2eceed6117bf2e310d1679d3c56427b2c6
src/marketplace/orders/ResourceUsageList.tsx
src/marketplace/orders/ResourceUsageList.tsx
import * as React from 'react'; import { withTranslation } from '@waldur/i18n'; import { Table, connectTable, createFetcher } from '@waldur/table-react'; export const TableComponent = props => { const { translate } = props; const columns = [ { title: translate('Date'), render: ({ row }) => row.date, }, { title: translate('Value'), render: ({ row }) => row.usage, }, { title: translate('Type'), render: ({ row }) => row.type, }, { title: translate('Name'), render: ({ row }) => row.name, }, { title: translate('Unit'), render: ({ row }) => row.measured_unit, }, ]; return ( <Table {...props} columns={columns} verboseName={translate('Usages')} showPageSizeSelector={true} /> ); }; const TableOptions = { table: 'ResourceUsages', fetchData: createFetcher('marketplace-component-usages'), mapPropsToFilter: props => ({resource_uuid: props.resource_uuid}), exportRow: row => [ row.date, row.usage, row.type, row.name, row.measured_unit, ], exportFields: [ 'Date', 'Value', 'Type', 'Name', 'Unit', ], }; export const ResourceUsagesList = withTranslation(connectTable(TableOptions)(TableComponent));
import * as React from 'react'; import { withTranslation } from '@waldur/i18n'; import { Table, connectTable, createFetcher } from '@waldur/table-react'; export const TableComponent = props => { const { translate } = props; const columns = [ { title: translate('Date'), render: ({ row }) => row.date, }, { title: translate('Value'), render: ({ row }) => row.usage, }, { title: translate('Unit'), render: ({ row }) => row.measured_unit, }, { title: translate('Type'), render: ({ row }) => row.type, }, { title: translate('Name'), render: ({ row }) => row.name, }, ]; return ( <Table {...props} columns={columns} verboseName={translate('Usages')} showPageSizeSelector={true} /> ); }; const TableOptions = { table: 'ResourceUsages', fetchData: createFetcher('marketplace-component-usages'), mapPropsToFilter: props => ({resource_uuid: props.resource_uuid}), exportRow: row => [ row.date, row.usage, row.measured_unit, row.type, row.name, ], exportFields: [ 'Date', 'Value', 'Unit', 'Type', 'Name', ], }; export const ResourceUsagesList = withTranslation(connectTable(TableOptions)(TableComponent));
Move Unit right after Value column in resource usages list
Move Unit right after Value column in resource usages list [WAL-2050]
TypeScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -15,16 +15,16 @@ render: ({ row }) => row.usage, }, { + title: translate('Unit'), + render: ({ row }) => row.measured_unit, + }, + { title: translate('Type'), render: ({ row }) => row.type, }, { title: translate('Name'), render: ({ row }) => row.name, - }, - { - title: translate('Unit'), - render: ({ row }) => row.measured_unit, }, ]; @@ -45,16 +45,16 @@ exportRow: row => [ row.date, row.usage, + row.measured_unit, row.type, row.name, - row.measured_unit, ], exportFields: [ 'Date', 'Value', + 'Unit', 'Type', 'Name', - 'Unit', ], };
97996fb2ec739ca9ba5593b65b5cbc339f8f7c3b
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;}", "pre {overflow: auto;}" ] }) export class CodeCardComponent { @Input() public code = ''; }
import { Component, Input } from '@angular/core'; @Component({ selector: 'codeCard', template: `<plrsCard sectioned [title]="title"> <pre><code>{{ code }}</code></pre> </plrsCard>`, styles: [ "plrscard {margin-top: 2rem;}", "pre {overflow: auto;}" ] }) export class CodeCardComponent { @Input() public code = ''; @Input() public title = 'Code'; }
Add ability to specify a title for the code.
Add ability to specify a title for the code.
TypeScript
mit
syrp-nz/angular-polaris,syrp-nz/angular-polaris,syrp-nz/angular-polaris
--- +++ @@ -1,7 +1,7 @@ import { Component, Input } from '@angular/core'; @Component({ selector: 'codeCard', - template: `<plrsCard sectioned title="Angular Code"> + template: `<plrsCard sectioned [title]="title"> <pre><code>{{ code }}</code></pre> </plrsCard>`, styles: [ @@ -11,4 +11,5 @@ }) export class CodeCardComponent { @Input() public code = ''; + @Input() public title = 'Code'; }
edc2b7b9a859883edafb050a5623bb31d792920d
src/utils/installation-sucess.ts
src/utils/installation-sucess.ts
import { buildTools } from '../constants'; export function includesSuccess(input: string = '') { let isBuildToolsSuccess; let isPythonSuccess; if (buildTools.version === 2015) { // Success strings for build tools (2015) isBuildToolsSuccess = input.includes('Variable: IsInstalled = 1') || input.includes('Variable: BuildTools_Core_Installed = ') || input.includes('WixBundleInstalled = 1') || input.includes('Setting string variable \'IsInstalled\' to value \'1\''); } else { // Success strings for build tools (2017) isBuildToolsSuccess = input.includes('Closing installer. Return code: 3010.') || input.includes('Closing installer. Return code: 0.'); } // Success strings for Python isPythonSuccess = input.includes('INSTALL. Return value 1') || input.includes('Installation completed successfully') || input.includes('Configuration completed successfully'); return { isBuildToolsSuccess, isPythonSuccess }; } export function includesFailure(input: string = '') { return input.includes('Closing installer. Return code:') || input.includes('Shutting down, exit code:'); }
import { buildTools } from '../constants'; export function includesSuccess(input: string = '') { let isBuildToolsSuccess; let isPythonSuccess; if (buildTools.version === 2015) { // Success strings for build tools (2015) isBuildToolsSuccess = input.includes('Variable: IsInstalled = 1') || input.includes('Variable: BuildTools_Core_Installed = ') || input.includes('WixBundleInstalled = 1') || input.includes('Setting string variable \'IsInstalled\' to value \'1\'') || input.includes('Apply complete, result: 0x0, restart: None, ba requested restart:'); } else { // Success strings for build tools (2017) isBuildToolsSuccess = input.includes('Closing installer. Return code: 3010.') || input.includes('Closing installer. Return code: 0.'); } // Success strings for Python isPythonSuccess = input.includes('INSTALL. Return value 1') || input.includes('Installation completed successfully') || input.includes('Configuration completed successfully'); return { isBuildToolsSuccess, isPythonSuccess }; } export function includesFailure(input: string = '') { return input.includes('Closing installer. Return code:') || input.includes('Shutting down, exit code:'); }
Check for one more line
:wrench: Check for one more line
TypeScript
mit
felixrieseberg/windows-build-tools,felixrieseberg/windows-build-tools
--- +++ @@ -9,7 +9,8 @@ isBuildToolsSuccess = input.includes('Variable: IsInstalled = 1') || input.includes('Variable: BuildTools_Core_Installed = ') || input.includes('WixBundleInstalled = 1') || - input.includes('Setting string variable \'IsInstalled\' to value \'1\''); + input.includes('Setting string variable \'IsInstalled\' to value \'1\'') || + input.includes('Apply complete, result: 0x0, restart: None, ba requested restart:'); } else { // Success strings for build tools (2017) isBuildToolsSuccess = input.includes('Closing installer. Return code: 3010.') ||
25c039a57d86f55eed7c171a3ed88664937a14c2
src/workspace-module-resolver.ts
src/workspace-module-resolver.ts
import { IWorkspaceModuleProvider } from './workspace-module-provider'; import { matchByWords } from './utils'; import * as path from 'path'; export function findWorkspaceModules(moduleProvider: IWorkspaceModuleProvider, currentDocumentPath: string, packageName: string) { if (!packageName) { return []; } return moduleProvider.getWorkspaceModules() .filter((fileInfo) => matchByWords(packageName, fileInfo.fileName)) .map((fileInfo) => path.relative(currentDocumentPath, fileInfo.fsPath).replace('.', '')); }
import * as path from 'path'; import { IWorkspaceModuleProvider } from './workspace-module-provider'; import { matchByWords, stripExtension } from './utils'; import { getConfig } from './config'; export function findWorkspaceModules(moduleProvider: IWorkspaceModuleProvider, currentDocumentPath: string, packageName: string) { if (!packageName) { return []; } return moduleProvider.getWorkspaceModules() .filter((fileInfo) => matchByWords(packageName, fileInfo.fileName)) .map((fileInfo) => composeImportPath(currentDocumentPath, fileInfo.fsPath)); } function composeImportPath(currentDocumentPath: string, fsPath: string) { let relativePath = path.relative(currentDocumentPath, fsPath).replace('.', ''); const config = getConfig(); if (config.skipInitialDotForRelativePath && relativePath.startsWith('./..')) { relativePath = relativePath.substring(2); } if (config.excludeExtension) { relativePath = stripExtension(relativePath); } return relativePath; }
Exclude extension and starting dot based on settings.
Exclude extension and starting dot based on settings.
TypeScript
mit
reflectiondm/vscode-npmsmartimporter
--- +++ @@ -1,6 +1,8 @@ +import * as path from 'path'; + import { IWorkspaceModuleProvider } from './workspace-module-provider'; -import { matchByWords } from './utils'; -import * as path from 'path'; +import { matchByWords, stripExtension } from './utils'; +import { getConfig } from './config'; export function findWorkspaceModules(moduleProvider: IWorkspaceModuleProvider, currentDocumentPath: string, packageName: string) { if (!packageName) { @@ -9,5 +11,20 @@ return moduleProvider.getWorkspaceModules() .filter((fileInfo) => matchByWords(packageName, fileInfo.fileName)) - .map((fileInfo) => path.relative(currentDocumentPath, fileInfo.fsPath).replace('.', '')); + .map((fileInfo) => composeImportPath(currentDocumentPath, fileInfo.fsPath)); } + +function composeImportPath(currentDocumentPath: string, fsPath: string) { + let relativePath = path.relative(currentDocumentPath, fsPath).replace('.', ''); + const config = getConfig(); + + if (config.skipInitialDotForRelativePath && relativePath.startsWith('./..')) { + relativePath = relativePath.substring(2); + } + + if (config.excludeExtension) { + relativePath = stripExtension(relativePath); + } + + return relativePath; +}
d7ceba4ef1e321b1b8026e0dcddba6ed2ecd3fa1
src/theme/helpers/getMarkdownFromHtml.ts
src/theme/helpers/getMarkdownFromHtml.ts
const TurndownService = require('turndown'); const turndownService = new TurndownService(); /** * Coverts html to markdown. We need this in comment blocks that have been processed by the 'Marked' plugin. * @param options */ export function getMarkdownFromHtml(options: any) { return turndownService.turndown(options.fn(this), { codeBlockStyle: 'fenced' }); }
const TurndownService = require('turndown'); const turndownService = new TurndownService(); /** * Coverts html to markdown. We need this in comment blocks that have been processed by the 'Marked' plugin. * @param options */ export function getMarkdownFromHtml(options: any) { return turndownService.turndown(options.fn(this), { codeBlockStyle: 'fenced', }); }
Add trailing comma to adhere to lint rules
Add trailing comma to adhere to lint rules
TypeScript
mit
tgreyuk/typedoc-plugin-markdown,tgreyuk/typedoc-plugin-markdown
--- +++ @@ -7,6 +7,6 @@ */ export function getMarkdownFromHtml(options: any) { return turndownService.turndown(options.fn(this), { - codeBlockStyle: 'fenced' + codeBlockStyle: 'fenced', }); }
b9984c9087abd3301f439282052c130608c83de7
source/ci_source/providers/Nevercode.ts
source/ci_source/providers/Nevercode.ts
import { Env, CISource } from "../ci_source" import { ensureEnvKeysExist, ensureEnvKeysAreInt } from "../ci_source_helpers" /** * Nevercode.io CI Integration * * Environment Variables Documented: https://developer.nevercode.io/v1.0/docs/environment-variables-files */ export class Nevercode implements CISource { constructor(private readonly env: Env) {} get name(): string { return "Nevercode" } get isCI(): boolean { return ensureEnvKeysExist(this.env, ["NEVERCODE"]) } get isPR(): boolean { const mustHave = ["NEVERCODE_PULL_REQUEST", "NEVERCODE_REPO_SLUG"] const mustBeInts = ["NEVERCODE_GIT_PROVIDER_PULL_REQUEST", "NEVERCODE_PULL_REQUEST_NUMBER"] return ( ensureEnvKeysExist(this.env, mustHave) && ensureEnvKeysAreInt(this.env, mustBeInts) && this.env.NEVERCODE_PULL_REQUEST == "true" ) } get pullRequestID(): string { return this.env.NEVERCODE_PULL_REQUEST_NUMBER } get repoSlug(): string { return this.env.NEVERCODE_REPO_SLUG } get supportedPlatforms(): string[] { return ["github"] } get ciRunURL() { return process.env.NEVERCODE_BUILD_URL } private get branchName(): string { if (this.isPR) { return this.env.NEVERCODE_PULL_REQUEST_SOURCE } else { return this.env.NEVERCODE_BRANCH } } }
import { Env, CISource } from "../ci_source" import { ensureEnvKeysExist, ensureEnvKeysAreInt } from "../ci_source_helpers" /** * Nevercode.io CI Integration * * Environment Variables Documented: https://developer.nevercode.io/v1.0/docs/environment-variables-files */ export class Nevercode implements CISource { constructor(private readonly env: Env) {} get name(): string { return "Nevercode" } get isCI(): boolean { return ensureEnvKeysExist(this.env, ["NEVERCODE"]) } get isPR(): boolean { const mustHave = ["NEVERCODE_PULL_REQUEST", "NEVERCODE_REPO_SLUG"] const mustBeInts = ["NEVERCODE_GIT_PROVIDER_PULL_REQUEST", "NEVERCODE_PULL_REQUEST_NUMBER"] return ( ensureEnvKeysExist(this.env, mustHave) && ensureEnvKeysAreInt(this.env, mustBeInts) && this.env.NEVERCODE_PULL_REQUEST == "true" ) } get pullRequestID(): string { return this.env.NEVERCODE_PULL_REQUEST_NUMBER } get repoSlug(): string { return this.env.NEVERCODE_REPO_SLUG } get supportedPlatforms(): string[] { return ["github"] } get ciRunURL() { return process.env.NEVERCODE_BUILD_URL } }
Remove unused function in nevercode
Remove unused function in nevercode
TypeScript
mit
danger/danger-js,danger/danger-js,danger/danger-js,danger/danger-js
--- +++ @@ -42,12 +42,4 @@ get ciRunURL() { return process.env.NEVERCODE_BUILD_URL } - - private get branchName(): string { - if (this.isPR) { - return this.env.NEVERCODE_PULL_REQUEST_SOURCE - } else { - return this.env.NEVERCODE_BRANCH - } - } }
f952ca8afb09d9d6ee7cccd6275c0f4bc996425f
src/Apps/Order/Components/CreditCardInput.tsx
src/Apps/Order/Components/CreditCardInput.tsx
import { color } from "@artsy/palette" import { fontFamily } from "@artsy/palette/dist/platform/fonts" import { border } from "Components/Mixins" import React from "react" import { CardElement } from "react-stripe-elements" import styled from "styled-components" import { BorderBox } from "Styleguide/Elements/Box" const StyledCardElement = styled(CardElement)` width: 100%; font-family: "Comic Sans"; ` interface StyledBorderBox { hasError: boolean } const StyledBorderBox = styled(BorderBox).attrs<StyledBorderBox>({})` ${border}; ` export class CreditCardInput extends React.Component { state = { focused: false, error: false, } render() { return ( <StyledBorderBox className={`${this.state.focused ? "focused" : ""}`} hasError={this.state.error} p={1} > <StyledCardElement onChange={res => { this.setState({ error: res.error }) }} onFocus={() => this.setState({ focused: true })} onBlur={() => this.setState({ focused: false })} style={{ base: { "::placeholder": { color: color("black30"), }, fontFamily: fontFamily.serif.regular as string, fontSmoothing: "antialiased", lineHeight: "20px", }, }} /> </StyledBorderBox> ) } }
import { color } from "@artsy/palette" import { fontFamily } from "@artsy/palette/dist/platform/fonts" import { border } from "Components/Mixins" import React from "react" import { CardElement } from "react-stripe-elements" import styled from "styled-components" import { BorderBox } from "Styleguide/Elements/Box" const StyledCardElement = styled(CardElement)` width: 100%; ` interface StyledBorderBox { hasError: boolean } const StyledBorderBox = styled(BorderBox).attrs<StyledBorderBox>({})` ${border}; ` export class CreditCardInput extends React.Component { state = { focused: false, error: false, } render() { return ( <StyledBorderBox className={`${this.state.focused ? "focused" : ""}`} hasError={this.state.error} p={1} > <StyledCardElement onChange={res => { this.setState({ error: res.error }) }} onFocus={() => this.setState({ focused: true })} onBlur={() => this.setState({ focused: false })} style={{ base: { "::placeholder": { color: color("black30"), }, fontFamily: fontFamily.serif.regular as string, fontSmoothing: "antialiased", lineHeight: "20px", }, }} /> </StyledBorderBox> ) } }
Remove unused font-family from card wrapper
Remove unused font-family from card wrapper
TypeScript
mit
artsy/reaction,xtina-starr/reaction,xtina-starr/reaction,xtina-starr/reaction,xtina-starr/reaction,artsy/reaction-force,artsy/reaction-force,artsy/reaction,artsy/reaction
--- +++ @@ -8,7 +8,6 @@ const StyledCardElement = styled(CardElement)` width: 100%; - font-family: "Comic Sans"; ` interface StyledBorderBox {
8576018af1825a5df897376a9eb75031b54dbbb7
tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts
tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts
declare function all(a?: number, b?: number): void; declare function weird(a?: number | string, b?: number | string): void; declare function prefix(s: string, a?: number, b?: number): void; declare function rest(s: string, a?: number, b?: number, ...rest: number[]): void; declare function normal(s: string): void; declare function thunk(): string; declare var ns: number[]; declare var mixed: (number | string)[]; declare var tuple: [number, string]; // good all(...ns) weird(...ns) weird(...mixed) weird(...tuple) prefix("a", ...ns) rest("d", ...ns) // extra arguments normal("g", ...ns) thunk(...ns) // bad all(...mixed) all(...tuple) prefix("b", ...mixed) prefix("c", ...tuple) rest("e", ...mixed) rest("f", ...tuple) prefix(...ns) // required parameters are required prefix(...mixed) prefix(...tuple)
declare function all(a?: number, b?: number): void; declare function weird(a?: number | string, b?: number | string): void; declare function prefix(s: string, a?: number, b?: number): void; declare function rest(s: string, a?: number, b?: number, ...rest: number[]): void; declare function normal(s: string): void; declare function thunk(): string; declare function prefix2(s: string, n: number, a?: number, b?: number): void; declare var ns: number[]; declare var mixed: (number | string)[]; declare var tuple: [number, string]; // good all(...ns) weird(...ns) weird(...mixed) weird(...tuple) prefix("a", ...ns) rest("d", ...ns) // extra arguments normal("g", ...ns) thunk(...ns) // bad all(...mixed) all(...tuple) prefix("b", ...mixed) prefix("c", ...tuple) rest("e", ...mixed) rest("f", ...tuple) prefix(...ns) // required parameters are required prefix(...mixed) prefix(...tuple) prefix2("g", ...ns);
Add failing test for function calls that have at least one non-spread argument, a spread argument, and overall potentially too few arguments
Add failing test for function calls that have at least one non-spread argument, a spread argument, and overall potentially too few arguments
TypeScript
apache-2.0
SaschaNaz/TypeScript,RyanCavanaugh/TypeScript,nojvek/TypeScript,alexeagle/TypeScript,kitsonk/TypeScript,Microsoft/TypeScript,kpreisser/TypeScript,minestarks/TypeScript,kitsonk/TypeScript,minestarks/TypeScript,microsoft/TypeScript,alexeagle/TypeScript,alexeagle/TypeScript,kpreisser/TypeScript,weswigham/TypeScript,Microsoft/TypeScript,kpreisser/TypeScript,nojvek/TypeScript,nojvek/TypeScript,minestarks/TypeScript,microsoft/TypeScript,SaschaNaz/TypeScript,SaschaNaz/TypeScript,nojvek/TypeScript,RyanCavanaugh/TypeScript,kitsonk/TypeScript,weswigham/TypeScript,RyanCavanaugh/TypeScript,weswigham/TypeScript,Microsoft/TypeScript,microsoft/TypeScript,SaschaNaz/TypeScript
--- +++ @@ -4,6 +4,7 @@ declare function rest(s: string, a?: number, b?: number, ...rest: number[]): void; declare function normal(s: string): void; declare function thunk(): string; +declare function prefix2(s: string, n: number, a?: number, b?: number): void; declare var ns: number[]; declare var mixed: (number | string)[]; @@ -32,3 +33,4 @@ prefix(...ns) // required parameters are required prefix(...mixed) prefix(...tuple) +prefix2("g", ...ns);
f82f95780fed6e54147e99bc995495827990155f
server/test/_root.ts
server/test/_root.ts
import { Database, Mode } from '../src/Database'; // Mocha root suite. Install test hooks for all tests here. // https://mochajs.org/#root-level-hooks before('connect to database', () => { return Database.get().connect(Mode.TEST); }); after('disconnect from database', () => { return Database.get().disconnect(); });
import { Database, Mode } from '../src/Database'; // Catch unhandled Promises process.on('unhandledRejection', (reason) => { process.stderr.write("Unhandled Promise rejection:\n"); console.error(reason); process.exit(1); }); // Mocha root suite. Install test hooks for all tests here. // https://mochajs.org/#root-level-hooks before('connect to database', () => { return Database.get().connect(Mode.TEST); }); after('disconnect from database', () => { return Database.get().disconnect(); });
Enforce handling rejected promises in server tests
Enforce handling rejected promises in server tests
TypeScript
mit
mattbdean/Helium,mattbdean/Helium,mattbdean/Helium,mattbdean/Helium
--- +++ @@ -1,4 +1,11 @@ import { Database, Mode } from '../src/Database'; + +// Catch unhandled Promises +process.on('unhandledRejection', (reason) => { + process.stderr.write("Unhandled Promise rejection:\n"); + console.error(reason); + process.exit(1); +}); // Mocha root suite. Install test hooks for all tests here. // https://mochajs.org/#root-level-hooks
4f05c6975fa95db665c43eb4206d964b88589d99
src/renderer/app/components/NavigationButtons/index.tsx
src/renderer/app/components/NavigationButtons/index.tsx
import { observer } from 'mobx-react'; import * as React from 'react'; import store from '~/renderer/app/store'; import ToolbarButton from '~/renderer/app/components/ToolbarButton'; import { icons } from '~/renderer/app/constants/icons'; import { StyledContainer } from './style'; import { ipcRenderer } from 'electron'; import { callBrowserViewMethod } from '~/shared/utils/browser-view'; const onBackClick = () => { callBrowserViewMethod(store.tabsStore.selectedTabId, 'goBack'); }; const onForwardClick = () => { callBrowserViewMethod(store.tabsStore.selectedTabId, 'goForward'); }; const onRefreshClick = () => { callBrowserViewMethod(store.tabsStore.selectedTabId, 'refresh'); }; export const NavigationButtons = observer(() => { return ( <StyledContainer isFullscreen={store.isFullscreen}> <ToolbarButton disabled={!store.navigationState.canGoBack} size={24} icon={icons.back} style={{ marginLeft: 8 }} onClick={onBackClick} /> <ToolbarButton disabled={!store.navigationState.canGoForward} size={24} icon={icons.forward} onClick={onForwardClick} /> <ToolbarButton size={20} icon={icons.refresh} onClick={onRefreshClick} /> </StyledContainer> ); });
import { observer } from 'mobx-react'; import * as React from 'react'; import store from '~/renderer/app/store'; import ToolbarButton from '~/renderer/app/components/ToolbarButton'; import { icons } from '~/renderer/app/constants/icons'; import { StyledContainer } from './style'; import { ipcRenderer } from 'electron'; import { callBrowserViewMethod } from '~/shared/utils/browser-view'; const onBackClick = () => { callBrowserViewMethod(store.tabsStore.selectedTabId, 'goBack'); }; const onForwardClick = () => { callBrowserViewMethod(store.tabsStore.selectedTabId, 'goForward'); }; const onRefreshClick = () => { callBrowserViewMethod(store.tabsStore.selectedTabId, 'reload'); }; export const NavigationButtons = observer(() => { return ( <StyledContainer isFullscreen={store.isFullscreen}> <ToolbarButton disabled={!store.navigationState.canGoBack} size={24} icon={icons.back} style={{ marginLeft: 8 }} onClick={onBackClick} /> <ToolbarButton disabled={!store.navigationState.canGoForward} size={24} icon={icons.forward} onClick={onForwardClick} /> <ToolbarButton size={20} icon={icons.refresh} onClick={onRefreshClick} /> </StyledContainer> ); });
Fix errors when reloading a page
Fix errors when reloading a page
TypeScript
apache-2.0
Nersent/Wexond,Nersent/Wexond
--- +++ @@ -17,7 +17,7 @@ }; const onRefreshClick = () => { - callBrowserViewMethod(store.tabsStore.selectedTabId, 'refresh'); + callBrowserViewMethod(store.tabsStore.selectedTabId, 'reload'); }; export const NavigationButtons = observer(() => {
94731c52f02a0d46ccdfaa8c16ec79504623d9d3
src/app/app.ts
src/app/app.ts
import {Directive, View, ElementRef} from 'angular2/angular2'; import {RouteConfig, Router} from 'angular2/router'; import {Http, Headers} from 'angular2/http'; import {Component, ViewQuery} from 'angular2/angular2'; import {CORE_DIRECTIVES, FORM_DIRECTIVES} from 'angular2/angular2'; import {ROUTER_DIRECTIVES} from 'angular2/router'; import {SHARED_COMPONENTS } from './components/shared/shared_modules'; import {SHARED_DIRECTIVES} from './directives/directives_modules'; import {Section, Dashboard} from './components/patterns/patterns_modules'; import {Dispatcher} from './common/dispatcher'; let styles = require('./app.scss'); let template = require('./app.html'); @Component({ selector: 'app', // <app></app> bindings: [ CORE_DIRECTIVES, FORM_DIRECTIVES, ROUTER_DIRECTIVES, Dispatcher ], }) @RouteConfig([ { path: '/', component: Dashboard, as: 'Section' } ]) @View({ styles: [styles], template:template, directives: [SHARED_COMPONENTS, ROUTER_DIRECTIVES] }) export class App { title: string; constructor(public http: Http, public dispatcher: Dispatcher) { this.title = 'Angular 2'; } }
import {Directive, View, ElementRef} from 'angular2/angular2'; import {RouteConfig, Router} from 'angular2/router'; import {Http, Headers} from 'angular2/http'; import {Component, ViewQuery} from 'angular2/angular2'; import {CORE_DIRECTIVES, FORM_DIRECTIVES} from 'angular2/angular2'; import {ROUTER_DIRECTIVES} from 'angular2/router'; import {SHARED_COMPONENTS } from './components/shared/shared_modules'; import {SHARED_DIRECTIVES} from './directives/directives_modules'; import {Section, Dashboard} from './components/patterns/patterns_modules'; import {Dispatcher} from './common/dispatcher'; let styles = require('./app.scss'); let template = require('./app.html'); @Component({ selector: 'app', // <app></app> bindings: [ CORE_DIRECTIVES, FORM_DIRECTIVES, ROUTER_DIRECTIVES, Dispatcher ], }) @RouteConfig([ { path: '/', component: Section, as: 'Section' } ]) @View({ styles: [styles], template:template, directives: [SHARED_COMPONENTS, ROUTER_DIRECTIVES] }) export class App { title: string; constructor(public http: Http, public dispatcher: Dispatcher) { this.title = 'Angular 2'; } }
Change Default Page to Section
Change Default Page to Section
TypeScript
mit
Ao21/PatternLibrary,Ao21/PatternLibrary,Ao21/PatternLibrary
--- +++ @@ -20,7 +20,7 @@ bindings: [ CORE_DIRECTIVES, FORM_DIRECTIVES, ROUTER_DIRECTIVES, Dispatcher ], }) @RouteConfig([ - { path: '/', component: Dashboard, as: 'Section' } + { path: '/', component: Section, as: 'Section' } ]) @View({ styles: [styles],
928dfbe439421f61b626f0725f48ca506c763f5a
tools/env/base.ts
tools/env/base.ts
import { EnvConfig } from './env-config.interface'; const BaseConfig: EnvConfig = { // Sample API url API: 'https://demo.com', RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.8.0', RELEASEVERSION: '0.8.0' }; export = BaseConfig;
import { EnvConfig } from './env-config.interface'; const BaseConfig: EnvConfig = { // Sample API url API: 'https://demo.com', RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.9.0', RELEASEVERSION: '0.9.0' }; export = BaseConfig;
Update release version to 0.9.0.
Update release version to 0.9.0.
TypeScript
mit
nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website
--- +++ @@ -3,8 +3,8 @@ const BaseConfig: EnvConfig = { // Sample API url API: 'https://demo.com', - RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.8.0', - RELEASEVERSION: '0.8.0' + RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.9.0', + RELEASEVERSION: '0.9.0' }; export = BaseConfig;
e4e030244b043182ca9b9dabaff47036153a3099
src/app/core/services/socket.service.ts
src/app/core/services/socket.service.ts
import { Injectable } from '@angular/core'; import { environment } from './../../../environments/environment'; import { Observable } from 'rxjs'; import * as io from 'socket.io-client'; @Injectable() export class SocketService { url: string; socket: SocketIOClient.Socket; constructor() { if(environment.production) { this.socket = io.connect({ transports: ['websocket'], upgrade: false }); } else { this.url = `${window.location.protocol}//${window.location.hostname}:3000`; this.socket = io.connect(this.url, { transports: ['websocket'], upgrade: false }); this.sendMessage('message', {message: 'hello'}); } } getSocketId(): string { return (this.socket) ? this.socket.id : ''; } connectToStreaming(socketEventName) { return Observable.fromEvent(this.socket, socketEventName).share(); } sendMessage(type: string, payload: object) { this.socket.emit(type, payload); } }
import { Injectable } from '@angular/core'; import { environment } from './../../../environments/environment'; import { Observable } from 'rxjs'; import * as io from 'socket.io-client'; @Injectable() export class SocketService { url: string; socket: SocketIOClient.Socket; constructor() { if(this.socket) { console.log('SS >>>> ', this.socket.connected); this.socket.removeAllListeners(); this.socket.disconnect(); } if(environment.production) { this.socket = io.connect({ transports: ['websocket'], upgrade: false }); } else { this.url = `${window.location.protocol}//${window.location.hostname}:3000`; this.socket = io.connect(this.url, { transports: ['websocket'], upgrade: false }); } } getSocketId(): string { return (this.socket) ? this.socket.id : ''; } connectToStreaming(socketEventName) { return Observable.fromEvent(this.socket, socketEventName).share(); } sendMessage(type: string, payload: object) { this.socket.emit(type, payload); } }
Add experimental/temporal control to avoid create new connections
Add experimental/temporal control to avoid create new connections
TypeScript
mit
semagarcia/javascript-kata-player,semagarcia/javascript-kata-player,semagarcia/javascript-kata-player
--- +++ @@ -10,12 +10,16 @@ socket: SocketIOClient.Socket; constructor() { + if(this.socket) { + console.log('SS >>>> ', this.socket.connected); + this.socket.removeAllListeners(); + this.socket.disconnect(); + } if(environment.production) { this.socket = io.connect({ transports: ['websocket'], upgrade: false }); } else { this.url = `${window.location.protocol}//${window.location.hostname}:3000`; this.socket = io.connect(this.url, { transports: ['websocket'], upgrade: false }); - this.sendMessage('message', {message: 'hello'}); } }
d8aec0f91e943b98417f7c277065b976450bc017
modules/tinymce/src/plugins/bbcode/test/ts/browser/BbcodeSanityTest.ts
modules/tinymce/src/plugins/bbcode/test/ts/browser/BbcodeSanityTest.ts
import { ApproxStructure, Log, Pipeline } from '@ephox/agar'; import { UnitTest } from '@ephox/bedrock-client'; import { TinyApis, TinyLoader } from '@ephox/mcagar'; import BbcodePlugin from 'tinymce/plugins/bbcode/Plugin'; import Theme from 'tinymce/themes/silver/Theme'; UnitTest.asynctest('browser.tinymce.plugins.bbcode.BbcodeSanityTest', (success, failure) => { BbcodePlugin(); Theme(); TinyLoader.setupLight((editor, onSuccess, onFailure) => { const tinyApis = TinyApis(editor); Pipeline.async({}, Log.steps('TBA', 'BBCode: Set bbcode content and assert the equivalent html structure is present', [ tinyApis.sSetContent('[b]a[/b]'), tinyApis.sAssertContentStructure(ApproxStructure.build((s, str) => { return s.element('body', { children: [ s.element('p', { children: [ s.element('strong', { children: [ s.text(str.is('a')) ] }) ] }) ] }); })) ]), onSuccess, onFailure); }, { plugins: 'bbcode', toolbar: 'bbcode', base_url: '/project/tinymce/js/tinymce', bbcode_dialect: 'punbb' }, success, failure); });
import { ApproxStructure } from '@ephox/agar'; import { describe, it } from '@ephox/bedrock-client'; import { TinyAssertions, TinyHooks } from '@ephox/mcagar'; import Plugin from 'tinymce/plugins/bbcode/Plugin'; import Theme from 'tinymce/themes/silver/Theme'; describe('browser.tinymce.plugins.bbcode.BbcodeSanityTest', () => { const hook = TinyHooks.bddSetupLight({ plugins: 'bbcode', toolbar: 'bbcode', base_url: '/project/tinymce/js/tinymce', bbcode_dialect: 'punbb' }, [ Plugin, Theme ]); it('TBA: Set bbcode content and assert the equivalent html structure is present', () => { const editor = hook.editor(); editor.setContent('[b]a[/b]'); TinyAssertions.assertContentStructure(editor, ApproxStructure.build((s, str) => { return s.element('body', { children: [ s.element('p', { children: [ s.element('strong', { children: [ s.text(str.is('a')) ] }) ] }) ] }); })); }); });
Switch bbcode plugin to use BDD style tests
TINY-6870: Switch bbcode plugin to use BDD style tests
TypeScript
mit
TeamupCom/tinymce,tinymce/tinymce,tinymce/tinymce,TeamupCom/tinymce,tinymce/tinymce
--- +++ @@ -1,39 +1,35 @@ -import { ApproxStructure, Log, Pipeline } from '@ephox/agar'; -import { UnitTest } from '@ephox/bedrock-client'; -import { TinyApis, TinyLoader } from '@ephox/mcagar'; -import BbcodePlugin from 'tinymce/plugins/bbcode/Plugin'; +import { ApproxStructure } from '@ephox/agar'; +import { describe, it } from '@ephox/bedrock-client'; +import { TinyAssertions, TinyHooks } from '@ephox/mcagar'; + +import Plugin from 'tinymce/plugins/bbcode/Plugin'; import Theme from 'tinymce/themes/silver/Theme'; -UnitTest.asynctest('browser.tinymce.plugins.bbcode.BbcodeSanityTest', (success, failure) => { - - BbcodePlugin(); - Theme(); - - TinyLoader.setupLight((editor, onSuccess, onFailure) => { - const tinyApis = TinyApis(editor); - - Pipeline.async({}, Log.steps('TBA', 'BBCode: Set bbcode content and assert the equivalent html structure is present', [ - tinyApis.sSetContent('[b]a[/b]'), - tinyApis.sAssertContentStructure(ApproxStructure.build((s, str) => { - return s.element('body', { - children: [ - s.element('p', { - children: [ - s.element('strong', { - children: [ - s.text(str.is('a')) - ] - }) - ] - }) - ] - }); - })) - ]), onSuccess, onFailure); - }, { +describe('browser.tinymce.plugins.bbcode.BbcodeSanityTest', () => { + const hook = TinyHooks.bddSetupLight({ plugins: 'bbcode', toolbar: 'bbcode', base_url: '/project/tinymce/js/tinymce', bbcode_dialect: 'punbb' - }, success, failure); + }, [ Plugin, Theme ]); + + it('TBA: Set bbcode content and assert the equivalent html structure is present', () => { + const editor = hook.editor(); + editor.setContent('[b]a[/b]'); + TinyAssertions.assertContentStructure(editor, ApproxStructure.build((s, str) => { + return s.element('body', { + children: [ + s.element('p', { + children: [ + s.element('strong', { + children: [ + s.text(str.is('a')) + ] + }) + ] + }) + ] + }); + })); + }); });
2051d9c3facbfa3c0bda0c78c00ec65ab3d826d1
config/webpack.prod.ts
config/webpack.prod.ts
/** * Created by Jean-paul.attard on 06/09/2016. */ var webpack = require('webpack'); var webpackMerge = require('webpack-merge'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var commonConfig = require('./webpack.common'); var helpers = require('./helpers'); const ENV = process.env.NODE_ENV = process.env.ENV = 'production'; module.exports = webpackMerge(commonConfig, { devtool: 'source-map', output: { path: helpers.root('dist'), publicPath: '/', filename: '[name].[hash].js', chunkFilename: '[id].[hash].chunk.js' }, htmlLoader: { minimize: false }, plugins: [ new webpack.NoErrorsPlugin(), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ mangle: { keep_fnames: true }, compress: { warnings: false }, output: { comments: false } }), new ExtractTextPlugin('[name].[hash].css'), new webpack.DefinePlugin({ 'process.env': { 'ENV': JSON.stringify(ENV) } }) ] });
/** * Created by Jean-paul.attard on 06/09/2016. */ var webpack = require('webpack'); var webpackMerge = require('webpack-merge'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var commonConfig = require('./webpack.common'); var helpers = require('./helpers'); const ENV = process.env.NODE_ENV = process.env.ENV = 'production'; module.exports = webpackMerge(commonConfig, { devtool: 'source-map', output: { path: helpers.root('dist'), publicPath: '/', filename: '[name].[hash].js', chunkFilename: '[id].[hash].chunk.js' }, htmlLoader: { minimize: false }, plugins: [ new webpack.NoErrorsPlugin(), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ mangle: { keep_fnames: true }, compress: { // Hide warnings about potentially dangerous optimizations/code. Consider setting it to true for debugging purposes. warnings: false }, comments: false, beautify: false }), new ExtractTextPlugin('[name].[hash].css'), new webpack.DefinePlugin({ 'process.env': { 'ENV': JSON.stringify(ENV) } }) ] });
Set warning compression to false
Set warning compression to false
TypeScript
mit
jeanpaulattard/tourofheroes,jeanpaulattard/tourofheroes,jeanpaulattard/tourofheroes
--- +++ @@ -32,12 +32,11 @@ mangle: { keep_fnames: true }, - compress: { + compress: { // Hide warnings about potentially dangerous optimizations/code. Consider setting it to true for debugging purposes. warnings: false }, - output: { - comments: false - } + comments: false, + beautify: false }), new ExtractTextPlugin('[name].[hash].css'), new webpack.DefinePlugin({
5634ef71147e9b3839cc335b563c8fa0f8245fb8
src/tests/exceptions.ts
src/tests/exceptions.ts
import * as assert from "assert"; import { wrap } from ".."; describe("exceptions", function () { it("should be cached", function () { const error = new Error("expected"); let threw = false; function throwOnce() { if (!threw) { threw = true; throw error; } return "already threw"; } const wrapper = wrap(throwOnce); try { wrapper(); throw new Error("unreached"); } catch (e) { assert.strictEqual(e, error); } try { wrapper(); throw new Error("unreached"); } catch (e) { assert.strictEqual(e, error); } wrapper.dirty(); assert.strictEqual(wrapper(), "already threw"); assert.strictEqual(wrapper(), "already threw"); wrapper.dirty(); assert.strictEqual(wrapper(), "already threw"); }); });
import * as assert from "assert"; import { wrap } from ".."; describe("exceptions", function () { it("should be cached", function () { const error = new Error("expected"); let threw = false; function throwOnce() { if (!threw) { threw = true; throw error; } return "already threw"; } const wrapper = wrap(throwOnce); try { wrapper(); throw new Error("unreached"); } catch (e) { assert.strictEqual(e, error); } try { wrapper(); throw new Error("unreached"); } catch (e) { assert.strictEqual(e, error); } wrapper.dirty(); assert.strictEqual(wrapper(), "already threw"); assert.strictEqual(wrapper(), "already threw"); wrapper.dirty(); assert.strictEqual(wrapper(), "already threw"); }); it("should memoize a throwing fibonacci function", function () { const fib = wrap((n: number) => { if (n < 2) throw n; try { fib(n - 1); } catch (minusOne) { try { fib(n - 2); } catch (minusTwo) { throw minusOne + minusTwo; } } throw new Error("unreached"); }); function check(n: number, expected: number) { try { fib(n); throw new Error("unreached"); } catch (result) { assert.strictEqual(result, expected); } } check(78, 8944394323791464); check(68, 72723460248141); check(58, 591286729879); check(48, 4807526976); fib.dirty(28); check(38, 39088169); check(28, 317811); check(18, 2584); check(8, 21); fib.dirty(20); check(78, 8944394323791464); check(10, 55); }); });
Test memoization of naive Fibonacci function that throws results.
Test memoization of naive Fibonacci function that throws results.
TypeScript
mit
benjamn/optimism,benjamn/optimism
--- +++ @@ -35,4 +35,42 @@ wrapper.dirty(); assert.strictEqual(wrapper(), "already threw"); }); + + it("should memoize a throwing fibonacci function", function () { + const fib = wrap((n: number) => { + if (n < 2) throw n; + try { + fib(n - 1); + } catch (minusOne) { + try { + fib(n - 2); + } catch (minusTwo) { + throw minusOne + minusTwo; + } + } + throw new Error("unreached"); + }); + + function check(n: number, expected: number) { + try { + fib(n); + throw new Error("unreached"); + } catch (result) { + assert.strictEqual(result, expected); + } + } + + check(78, 8944394323791464); + check(68, 72723460248141); + check(58, 591286729879); + check(48, 4807526976); + fib.dirty(28); + check(38, 39088169); + check(28, 317811); + check(18, 2584); + check(8, 21); + fib.dirty(20); + check(78, 8944394323791464); + check(10, 55); + }); });
a49ce682441924e9e095e4a2dcce45523d302732
packages/components/containers/overview/IndexSection.tsx
packages/components/containers/overview/IndexSection.tsx
import React from 'react'; import { Icon } from '../../components'; import { usePermissions } from '../../hooks'; import { classnames } from '../../helpers'; import Sections from './Sections'; import { SectionConfig } from '../../components/layout'; const IndexSection = ({ pages, limit = 4 }: { pages: SectionConfig[]; limit?: number }) => { const permissions = usePermissions(); return ( <div className="overview-grid"> {pages.map(({ icon, text, to, subsections = [], permissions: pagePermissions }) => { return ( <section key={to} className={classnames([ 'overview-grid-item bordered-container bg-white-dm tiny-shadow-container p2', subsections.length > limit && 'overview-grid-item--tall', ])} > <h2 className="h6 mb1"> <Icon name={icon} className="mr0-5" /> <strong>{text}</strong> </h2> <Sections to={to} subsections={subsections} text={text} permissions={permissions} pagePermissions={pagePermissions} /> </section> ); })} </div> ); }; export default IndexSection;
import React from 'react'; import { Icon } from '../../components'; import { usePermissions } from '../../hooks'; import { classnames } from '../../helpers'; import Sections from './Sections'; import { SectionConfig } from '../../components/layout'; const IndexSection = ({ pages, limit = 4 }: { pages: SectionConfig[]; limit?: number }) => { const permissions = usePermissions(); return ( <div className="overview-grid"> {pages.map(({ icon, text, to, subsections = [], permissions: pagePermissions }) => { return ( <section key={to} className={classnames([ 'overview-grid-item bordered-container bg-white-dm tiny-shadow-container p2', subsections.length > limit && 'overview-grid-item--tall', ])} > <h2 className="h6 mb1 flex flex-items-center flex-nowrap"> <Icon name={icon} className="mr0-5 flex-item-noshrink" /> <strong className="ellipsis" title={text}> {text} </strong> </h2> <Sections to={to} subsections={subsections} text={text} permissions={permissions} pagePermissions={pagePermissions} /> </section> ); })} </div> ); }; export default IndexSection;
Fix - icon alignment for overview
Fix - icon alignment for overview
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -20,9 +20,11 @@ subsections.length > limit && 'overview-grid-item--tall', ])} > - <h2 className="h6 mb1"> - <Icon name={icon} className="mr0-5" /> - <strong>{text}</strong> + <h2 className="h6 mb1 flex flex-items-center flex-nowrap"> + <Icon name={icon} className="mr0-5 flex-item-noshrink" /> + <strong className="ellipsis" title={text}> + {text} + </strong> </h2> <Sections to={to}
780cea570b4d4101756053cce45d73b987bd519a
packages/node_modules/glimmer-util/lib/platform-utils.ts
packages/node_modules/glimmer-util/lib/platform-utils.ts
interface InternedStringMarker { "d0850007-25c2-47d8-bb63-c4054016d539": boolean; } export type InternedString = InternedStringMarker & string; export function intern(str: string): InternedString { return <InternedString>str; // let obj = {}; // obj[str] = 1; // for (let key in obj) return <InternedString>key; } interface OpaqueMarker { "a7613ac4-e3a3-4298-b06e-2349fe5a5ed5": boolean; } export type Opaque = OpaqueMarker; export function opaque(value: any): Opaque { return value as Opaque; } export function numberKey(num: number): InternedString { return <InternedString>String(num); } export function LITERAL(str: string): InternedString { return <InternedString>str; } let BASE_KEY = intern(`__glimmer{+ new Date()}`); export function symbol(debugName): InternedString { let number = +(new Date()); return intern(debugName + ' [id=' + BASE_KEY + Math.floor(Math.random() * number) + ']'); }
interface InternedStringMarker { "d0850007-25c2-47d8-bb63-c4054016d539": boolean; } export type InternedString = InternedStringMarker & string; export function intern(str: string): InternedString { return <InternedString>str; // let obj = {}; // obj[str] = 1; // for (let key in obj) return <InternedString>key; } export type Opaque = {} | void; export function opaque(value: Opaque): Opaque { return value; } export function numberKey(num: number): InternedString { return <InternedString>String(num); } export function LITERAL(str: string): InternedString { return <InternedString>str; } let BASE_KEY = intern(`__glimmer{+ new Date()}`); export function symbol(debugName): InternedString { let number = +(new Date()); return intern(debugName + ' [id=' + BASE_KEY + Math.floor(Math.random() * number) + ']'); }
Switch to a nicer `Opaque` implementation
Switch to a nicer `Opaque` implementation Mega props to @mhegazy who invented the trick!
TypeScript
mit
glimmerjs/glimmer-vm,lbdm44/glimmer-vm,lbdm44/glimmer-vm,tildeio/glimmer,chadhietala/glimmer,chadhietala/glimmer,glimmerjs/glimmer-vm,lbdm44/glimmer-vm,glimmerjs/glimmer-vm,tildeio/glimmer,chadhietala/glimmer,chadhietala/glimmer,tildeio/glimmer
--- +++ @@ -11,14 +11,10 @@ // for (let key in obj) return <InternedString>key; } -interface OpaqueMarker { - "a7613ac4-e3a3-4298-b06e-2349fe5a5ed5": boolean; -} +export type Opaque = {} | void; -export type Opaque = OpaqueMarker; - -export function opaque(value: any): Opaque { - return value as Opaque; +export function opaque(value: Opaque): Opaque { + return value; } export function numberKey(num: number): InternedString {
34af3f6b7d72f64571618059c74351a6537f37a0
web-server/tweakr-server/src/app/tweak/tweak.module.ts
web-server/tweakr-server/src/app/tweak/tweak.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import {AngularFireModule} from '@angular/fire'; import {AngularFireAuthModule} from '@angular/fire/auth'; import {AngularFireDatabaseModule} from '@angular/fire/database'; import { TweakRoutingModule } from './tweak-routing.module'; import { TweakComponent } from './tweak.component'; import {EditorsModule} from '../editors/editors.module'; import {TweakrComponent} from '../tweakr.component'; import {getFirebaseConfig} from '../firebase_config'; @NgModule({ declarations: [TweakComponent, TweakrComponent], imports: [ CommonModule, TweakRoutingModule, AngularFireModule.initializeApp(getFirebaseConfig()), AngularFireAuthModule, AngularFireDatabaseModule, EditorsModule ] }) export class TweakModule { }
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import {AngularFireModule} from '@angular/fire'; import {AngularFireAuthModule} from '@angular/fire/auth'; import {AngularFireDatabaseModule} from '@angular/fire/database'; import { TweakRoutingModule } from './tweak-routing.module'; import { TweakComponent } from './tweak.component'; import {MatButtonModule} from '@angular/material/button'; import {MatCardModule} from '@angular/material/card'; import {MatToolbarModule} from '@angular/material/toolbar'; import {MatRadioModule} from '@angular/material/radio'; import {EditorsModule} from '../editors/editors.module'; import {TweakrComponent} from '../tweakr.component'; import {getFirebaseConfig} from '../firebase_config'; @NgModule({ declarations: [TweakComponent, TweakrComponent], imports: [ CommonModule, TweakRoutingModule, AngularFireModule.initializeApp(getFirebaseConfig()), AngularFireAuthModule, AngularFireDatabaseModule, EditorsModule, MatButtonModule, MatCardModule, MatToolbarModule, MatRadioModule ] }) export class TweakModule { }
Fix Card styling not working on Tweakr editors
Fix Card styling not working on Tweakr editors
TypeScript
apache-2.0
google/tweakr,google/tweakr,google/tweakr,google/tweakr,google/tweakr
--- +++ @@ -7,6 +7,11 @@ import { TweakRoutingModule } from './tweak-routing.module'; import { TweakComponent } from './tweak.component'; + +import {MatButtonModule} from '@angular/material/button'; +import {MatCardModule} from '@angular/material/card'; +import {MatToolbarModule} from '@angular/material/toolbar'; +import {MatRadioModule} from '@angular/material/radio'; import {EditorsModule} from '../editors/editors.module'; import {TweakrComponent} from '../tweakr.component'; @@ -21,7 +26,9 @@ TweakRoutingModule, AngularFireModule.initializeApp(getFirebaseConfig()), AngularFireAuthModule, AngularFireDatabaseModule, - EditorsModule + EditorsModule, + MatButtonModule, MatCardModule, MatToolbarModule, + MatRadioModule ] }) export class TweakModule { }
3c1f362737779104882e58a011a082c0cfccba7f
lib/msal-core/src/utils/StringUtils.ts
lib/msal-core/src/utils/StringUtils.ts
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ /** * @hidden */ export class StringUtils { /** * Check if a string is empty * * @param str */ static isEmpty(str: string): boolean { return (typeof str === "undefined" || !str || 0 === str.length); } /** * Check if a string's value is a valid JSON object * * @param str */ static isValidJson(str: string): boolean { try { const parsedValue = JSON.parse(str); return (parsedValue && typeof parsedValue === "object"); } catch (error) { return false; } } }
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ /** * @hidden */ export class StringUtils { /** * Check if a string is empty * * @param str */ static isEmpty(str: string): boolean { return (typeof str === "undefined" || !str || 0 === str.length); } /** * Check if a string's value is a valid JSON object * * @param str */ static isValidJson(str: string): boolean { try { const parsedValue = JSON.parse(str); /** * There are edge cases in which JSON.parse will successfully parse a non-valid JSON object * (e.g. JSON.parse will parse an escaped string into an unescaped string), so adding a type check * of the parsed value is necessary in order to be certain that the string represents a valid JSON object. * */ return (parsedValue && typeof parsedValue === "object"); } catch (error) { return false; } } }
Add explanatory comment to isValidJson method
Add explanatory comment to isValidJson method
TypeScript
mit
AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js
--- +++ @@ -24,6 +24,11 @@ static isValidJson(str: string): boolean { try { const parsedValue = JSON.parse(str); + /** + * There are edge cases in which JSON.parse will successfully parse a non-valid JSON object + * (e.g. JSON.parse will parse an escaped string into an unescaped string), so adding a type check + * of the parsed value is necessary in order to be certain that the string represents a valid JSON object. + * */ return (parsedValue && typeof parsedValue === "object"); } catch (error) { return false;
eeabe48cef90c70b817962bdb73a1e68950348e5
frontend/sequences/step_tiles/__tests__/tile_set_servo_angle_test.tsx
frontend/sequences/step_tiles/__tests__/tile_set_servo_angle_test.tsx
import * as React from "react"; import { TileSetServoAngle } from "../tile_set_servo_angle"; import { mount } from "enzyme"; import { fakeSequence } from "../../../__test_support__/fake_state/resources"; import { SetServoAngle } from "farmbot"; import { emptyState } from "../../../resources/reducer"; import { StepParams } from "../../interfaces"; describe("<TileSetServoAngle/>", () => { const currentStep: SetServoAngle = { kind: "set_servo_angle", args: { pin_number: 4, pin_value: 90, } }; const fakeProps = (): StepParams => ({ currentSequence: fakeSequence(), currentStep: currentStep, dispatch: jest.fn(), index: 0, resources: emptyState().index, confirmStepDeletion: false, }); it("renders inputs", () => { const block = mount(<TileSetServoAngle {...fakeProps()} />); const inputs = block.find("input"); const labels = block.find("label"); expect(inputs.length).toEqual(3); expect(labels.length).toEqual(2); expect(inputs.first().props().placeholder).toEqual("Set Servo Angle"); expect(labels.at(0).text()).toContain("Servo pin"); expect(inputs.at(1).props().value).toEqual(4); }); });
import * as React from "react"; import { TileSetServoAngle } from "../tile_set_servo_angle"; import { mount } from "enzyme"; import { fakeSequence } from "../../../__test_support__/fake_state/resources"; import { SetServoAngle } from "farmbot"; import { emptyState } from "../../../resources/reducer"; import { StepParams } from "../../interfaces"; describe("<TileSetServoAngle/>", () => { const currentStep: SetServoAngle = { kind: "set_servo_angle", args: { pin_number: 4, pin_value: 90, } }; const fakeProps = (): StepParams => ({ currentSequence: fakeSequence(), currentStep: currentStep, dispatch: jest.fn(), index: 0, resources: emptyState().index, confirmStepDeletion: false, }); it("renders inputs", () => { const block = mount(<TileSetServoAngle {...fakeProps()} />); const inputs = block.find("input"); const labels = block.find("label"); expect(inputs.length).toEqual(4); expect(labels.length).toEqual(4); expect(inputs.first().props().placeholder).toEqual("Set Servo Angle"); expect(labels.at(0).text()).toContain("Servo pin"); expect(inputs.at(1).props().value).toEqual("4"); }); });
Fix test breakage in set_servo_angle.
Fix test breakage in set_servo_angle.
TypeScript
mit
FarmBot/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,FarmBot/Farmbot-Web-API,gabrielburnworth/Farmbot-Web-App,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app
--- +++ @@ -28,10 +28,10 @@ const block = mount(<TileSetServoAngle {...fakeProps()} />); const inputs = block.find("input"); const labels = block.find("label"); - expect(inputs.length).toEqual(3); - expect(labels.length).toEqual(2); + expect(inputs.length).toEqual(4); + expect(labels.length).toEqual(4); expect(inputs.first().props().placeholder).toEqual("Set Servo Angle"); expect(labels.at(0).text()).toContain("Servo pin"); - expect(inputs.at(1).props().value).toEqual(4); + expect(inputs.at(1).props().value).toEqual("4"); }); });
9b1dbe8ec632c03807f7d9df584035948c87f011
app/static/helloWorld.ts
app/static/helloWorld.ts
import 'zone.js'; import 'reflect-metadata'; import { Component } from '@angular/core'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; @Component({ selector: 'i-am', template: '<h2> I am {{ status }} </h2>' }) export class IAmAliveComponent { status: string; constructor() { this.status = 'Alive'; } } @NgModule({ imports: [BrowserModule], declarations: [IAmAliveComponent], bootstrap: [IAmAliveComponent] }) export class PhilTestModule { } platformBrowserDynamic().bootstrapModule(PhilTestModule);
import 'zone.js'; import 'reflect-metadata'; import { Component } from '@angular/core'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; @Component({ selector: 'i-am', template: '<h2> I am {{ status }} </h2><br/><h3>Your lucky number is {{ randNum }}</h3>' }) export class IAmAliveComponent { status: string; randNum: number; constructor() { this.status = 'Alive'; this.randNum = 42; } } @NgModule({ imports: [BrowserModule], declarations: [IAmAliveComponent], bootstrap: [IAmAliveComponent] }) export class PhilTestModule { } platformBrowserDynamic().bootstrapModule(PhilTestModule);
Add template support for random number
Add template support for random number
TypeScript
mit
pbraunstein/trackercise,pbraunstein/trackercise,pbraunstein/trackercise,pbraunstein/trackercise,pbraunstein/trackercise
--- +++ @@ -8,13 +8,15 @@ @Component({ selector: 'i-am', - template: '<h2> I am {{ status }} </h2>' + template: '<h2> I am {{ status }} </h2><br/><h3>Your lucky number is {{ randNum }}</h3>' }) export class IAmAliveComponent { status: string; + randNum: number; constructor() { this.status = 'Alive'; + this.randNum = 42; } }
cf49610b3c93fc46412961f02c4e35bc8a9717ad
step-release-vis/src/app/components/environments/environments_test.ts
step-release-vis/src/app/components/environments/environments_test.ts
import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {EnvironmentsComponent} from './environments'; import {HttpClientTestingModule} from '@angular/common/http/testing'; describe('EnvironmentsComponent', () => { let component: EnvironmentsComponent; let fixture: ComponentFixture<EnvironmentsComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [EnvironmentsComponent], imports: [HttpClientTestingModule], }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(EnvironmentsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {EnvironmentsComponent} from './environments'; import {HttpClientTestingModule} from '@angular/common/http/testing'; import {FileServiceStub} from '../../../testing/FileServiceStub'; import {FileService} from '../../services/file'; import {ActivatedRouteStub} from '../../../testing/ActivatedRouteStub'; import {ActivatedRoute} from '@angular/router'; import {EnvironmentComponent} from '../environment/environment'; describe('EnvironmentsComponent', () => { let component: EnvironmentsComponent; let fixture: ComponentFixture<EnvironmentsComponent>; let activatedRouteStub: ActivatedRouteStub; let fileServiceStub: FileServiceStub; beforeEach(async(() => { fileServiceStub = new FileServiceStub(); activatedRouteStub = new ActivatedRouteStub({ jsonUri: fileServiceStub.jsonUri, }); TestBed.configureTestingModule({ declarations: [EnvironmentsComponent, EnvironmentComponent], imports: [HttpClientTestingModule], providers: [ {provide: FileService, useValue: fileServiceStub}, {provide: ActivatedRoute, useValue: activatedRouteStub}, ], }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(EnvironmentsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should assign environments field', () => { fixture.detectChanges(); expect(component.environments).toEqual( fileServiceStub.files[fileServiceStub.jsonUri] ); }); });
Add test for Environments component.
Add test for Environments component.
TypeScript
apache-2.0
googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020
--- +++ @@ -2,15 +2,30 @@ import {EnvironmentsComponent} from './environments'; import {HttpClientTestingModule} from '@angular/common/http/testing'; +import {FileServiceStub} from '../../../testing/FileServiceStub'; +import {FileService} from '../../services/file'; +import {ActivatedRouteStub} from '../../../testing/ActivatedRouteStub'; +import {ActivatedRoute} from '@angular/router'; +import {EnvironmentComponent} from '../environment/environment'; describe('EnvironmentsComponent', () => { let component: EnvironmentsComponent; let fixture: ComponentFixture<EnvironmentsComponent>; + let activatedRouteStub: ActivatedRouteStub; + let fileServiceStub: FileServiceStub; beforeEach(async(() => { + fileServiceStub = new FileServiceStub(); + activatedRouteStub = new ActivatedRouteStub({ + jsonUri: fileServiceStub.jsonUri, + }); TestBed.configureTestingModule({ - declarations: [EnvironmentsComponent], + declarations: [EnvironmentsComponent, EnvironmentComponent], imports: [HttpClientTestingModule], + providers: [ + {provide: FileService, useValue: fileServiceStub}, + {provide: ActivatedRoute, useValue: activatedRouteStub}, + ], }).compileComponents(); })); @@ -23,4 +38,11 @@ it('should create', () => { expect(component).toBeTruthy(); }); + + it('should assign environments field', () => { + fixture.detectChanges(); + expect(component.environments).toEqual( + fileServiceStub.files[fileServiceStub.jsonUri] + ); + }); });
d287fb6173a817a476922a44981426ee64af5bde
src/common-ui/components/progress-step.tsx
src/common-ui/components/progress-step.tsx
import React, { PureComponent } from 'react' import cx from 'classnames' const styles = require('./progress-step.css') interface Props { onClick: () => void isSeen?: boolean isCurrentStep: boolean } const noop = () => undefined export default class ProgressStep extends PureComponent<Props> { render() { return ( <span onClick={this.props.isSeen ? this.props.onClick : noop} className={cx(styles.progressStep, { [styles.progressStepSeen]: this.props.isSeen, [styles.progressStepCurrent]: this.props.isCurrentStep, })} /> ) } }
import React, { PureComponent } from 'react' import cx from 'classnames' const styles = require('./progress-step.css') interface Props { onClick: () => void isSeen?: boolean isCurrentStep: boolean } export default class ProgressStep extends PureComponent<Props> { render() { return ( <span onClick={this.props.onClick} className={cx(styles.progressStep, { [styles.progressStepSeen]: this.props.isSeen, [styles.progressStepCurrent]: this.props.isCurrentStep, })} /> ) } }
Allow pressing of all onboarding step bubbles
Allow pressing of all onboarding step bubbles
TypeScript
mit
WorldBrain/WebMemex,WorldBrain/WebMemex
--- +++ @@ -9,13 +9,11 @@ isCurrentStep: boolean } -const noop = () => undefined - export default class ProgressStep extends PureComponent<Props> { render() { return ( <span - onClick={this.props.isSeen ? this.props.onClick : noop} + onClick={this.props.onClick} className={cx(styles.progressStep, { [styles.progressStepSeen]: this.props.isSeen, [styles.progressStepCurrent]: this.props.isCurrentStep,