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
baca5a865674c224a10174497d5366dfb631ed99
src/main/javascript/engine/models.ts
src/main/javascript/engine/models.ts
import { EventType } from './enums/event-type'; export interface Player extends Entity { //TODO: Remove these from the game engine & replace here getDialogs: () => any getCombatSchedule: () => any getEquipment: () => any switchSheathing: () => any getChat: () => any getSavedChannelOwner: () => any } export interface Npc extends Entity { } export interface Entity extends Node { } export interface Location extends Node { } export interface Node { } export interface CoordGrid { } export interface DynamicMapSquare { } export interface NodeHash { } export interface EventContext { event: EventType; trigger: number | string; player: Player; npc?: Npc; console?: boolean; cmdArgs?: string[]; component?: number; interface?: number; slot?: number; button?: number; fromslot?: number; toslot?: number; }
import { EventType } from './enums/event-type'; export interface Player extends Entity { //TODO: Remove these from the game engine & replace here getDialogs: () => any getCombatSchedule: () => any getEquipment: () => any switchSheathing: () => any getChat: () => any getSavedChannelOwner: () => any } export interface Npc extends Entity { } export interface Entity extends Node { } export interface Location extends Node { } export interface Node { } export interface CoordGrid { } export interface DynamicMapSquare { } export interface NodeHash { } export interface EventContext { event: EventType; trigger: number | string; player: Player; npc?: Npc; location?: Location; console?: boolean; cmdArgs?: string[]; component?: number; interface?: number; slot?: number; button?: number; fromslot?: number; toslot?: number; }
Add 'location' to the event context
Add 'location' to the event context
TypeScript
mit
Sundays211/VirtueRS3,Sundays211/VirtueRS3,Sundays211/VirtueRS3
--- +++ @@ -43,6 +43,7 @@ trigger: number | string; player: Player; npc?: Npc; + location?: Location; console?: boolean; cmdArgs?: string[]; component?: number;
27ef040730026577a6f3a39d0ddb0bddabe20119
src/app/leaflet/leaflet-sidebar/leaflet-sidebar.component.spec.ts
src/app/leaflet/leaflet-sidebar/leaflet-sidebar.component.spec.ts
/* tslint:disable:no-unused-variable */ /*! * Leaflet Sidebar Component Test * * Copyright(c) Exequiel Ceasar Navarrete <[email protected]> * Licensed under MIT */ import { TestBed, async, inject } from '@angular/core/testing'; import { LeafletSidebarComponent } from './leaflet-sidebar.component'; import { LeafletMapService } from '../leaflet-map.service'; describe('Component: LeafletSidebar', () => { beforeEach(() => TestBed.configureTestingModule({ providers: [ LeafletMapService, LeafletSidebarComponent ] })); it('should create an instance', inject([LeafletSidebarComponent], (component: LeafletSidebarComponent) => { expect(component).toBeTruthy(); })); });
/* tslint:disable:no-unused-variable */ /*! * Leaflet Sidebar Component Test * * Copyright(c) Exequiel Ceasar Navarrete <[email protected]> * Licensed under MIT */ import { TestBed, async, inject } from '@angular/core/testing'; import { LeafletSidebarComponent } from './leaflet-sidebar.component'; import { LeafletMapService } from '../leaflet-map.service'; describe('Component: LeafletSidebar', () => { beforeEach(() => TestBed.configureTestingModule({ declarations: [ LeafletSidebarComponent ], providers: [ LeafletMapService, LeafletSidebarComponent ] })); it('should create an instance', inject([LeafletSidebarComponent], (component: LeafletSidebarComponent) => { expect(component).toBeTruthy(); })); it('should emit onBeforeShow', async(inject([LeafletSidebarComponent], (component: LeafletSidebarComponent) => { component.onShow.subscribe((event: Event) => { expect(event).toBeTruthy(); }); component.onBeforeShow(new Event('beforeShow')); })); it('should emit onAfterShow', async(inject([LeafletSidebarComponent], (component: LeafletSidebarComponent) => { component.onShown.subscribe((event: Event) => { expect(event).toBeTruthy(); }); component.onAfterShow(new Event('afterShow')); })); it('should emit onBeforeHide', async(inject([LeafletSidebarComponent], (component: LeafletSidebarComponent) => { component.onHide.subscribe((event: Event) => { expect(event).toBeTruthy(); }); component.onBeforeHide(new Event('beforeHide')); })); it('should emit onAfterHide', async(inject([LeafletSidebarComponent], (component: LeafletSidebarComponent) => { component.onHidden.subscribe((event: Event) => { expect(event).toBeTruthy(); }); component.onBeforeHide(new Event('afterHide')); })); });
Add more tests for LeafletSidebarComponent
Add more tests for LeafletSidebarComponent
TypeScript
mit
ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2
--- +++ @@ -13,6 +13,9 @@ describe('Component: LeafletSidebar', () => { beforeEach(() => TestBed.configureTestingModule({ + declarations: [ + LeafletSidebarComponent + ], providers: [ LeafletMapService, LeafletSidebarComponent @@ -23,6 +26,38 @@ expect(component).toBeTruthy(); })); + it('should emit onBeforeShow', async(inject([LeafletSidebarComponent], (component: LeafletSidebarComponent) => { + component.onShow.subscribe((event: Event) => { + expect(event).toBeTruthy(); + }); + + component.onBeforeShow(new Event('beforeShow')); + })); + + it('should emit onAfterShow', async(inject([LeafletSidebarComponent], (component: LeafletSidebarComponent) => { + component.onShown.subscribe((event: Event) => { + expect(event).toBeTruthy(); + }); + + component.onAfterShow(new Event('afterShow')); + })); + + it('should emit onBeforeHide', async(inject([LeafletSidebarComponent], (component: LeafletSidebarComponent) => { + component.onHide.subscribe((event: Event) => { + expect(event).toBeTruthy(); + }); + + component.onBeforeHide(new Event('beforeHide')); + })); + + it('should emit onAfterHide', async(inject([LeafletSidebarComponent], (component: LeafletSidebarComponent) => { + component.onHidden.subscribe((event: Event) => { + expect(event).toBeTruthy(); + }); + + component.onBeforeHide(new Event('afterHide')); + })); + });
77f9a15ca37c6db333969182e788ae6ef6076590
src/index.ts
src/index.ts
import * as chalk from "chalk"; import * as tty from "tty"; /** * Prints a message indicating Ctrl+C was pressed then exits the process. */ export function defaultCtrlCHandler(): void { console.log(`'${chalk.cyan("^C")}', exiting`); process.exit(); } /** * Monitors Ctrl+C and executes a callback instead of SIGINT. * * @param {Function} cb * Callback function to execute on Ctrl+C. * @default "defaultCtrlCHandler" */ export function monitorCtrlC(cb?: Function): void { const stdin = process.stdin as tty.ReadStream; if (stdin && stdin.isTTY) { const handler = (typeof cb === "function" ? cb : defaultCtrlCHandler); stdin.setRawMode(true); stdin.on("data", function monitorCtrlCOnData(data: Buffer): void { if (data.length === 1 && data[0] === 0x03) { // Ctrl+C return handler(); } }); } }
import * as chalk from "chalk"; import * as tty from "tty"; /** * Prints a message indicating Ctrl+C was pressed then kills the process with SIGINT status. */ export function defaultCtrlCHandler(): void { console.log(`'${chalk.cyan("^C")}', exiting`); process.kill(process.pid, "SIGINT"); } /** * Monitors Ctrl+C and executes a callback instead of SIGINT. * * @param {Function} cb * Callback function to execute on Ctrl+C. * @default "defaultCtrlCHandler" */ export function monitorCtrlC(cb?: Function): void { const stdin = process.stdin as tty.ReadStream; if (stdin && stdin.isTTY) { const handler = (typeof cb === "function" ? cb : defaultCtrlCHandler); stdin.setRawMode(true); stdin.on("data", function monitorCtrlCOnData(data: Buffer): void { if (data.length === 1 && data[0] === 0x03) { // Ctrl+C return handler(); } }); } }
Use process.kill with SIGINT status by default
Use process.kill with SIGINT status by default
TypeScript
mit
pandell/node-monitorctrlc,pandell/node-monitorctrlc
--- +++ @@ -3,11 +3,11 @@ /** - * Prints a message indicating Ctrl+C was pressed then exits the process. + * Prints a message indicating Ctrl+C was pressed then kills the process with SIGINT status. */ export function defaultCtrlCHandler(): void { console.log(`'${chalk.cyan("^C")}', exiting`); - process.exit(); + process.kill(process.pid, "SIGINT"); } /**
b6f86e341edb5cae5d9996ababd1fcc3988f2bd2
packages/mathjax2-extension/src/index.ts
packages/mathjax2-extension/src/index.ts
/* ----------------------------------------------------------------------------- | Copyright (c) Jupyter Development Team. | Distributed under the terms of the Modified BSD License. |----------------------------------------------------------------------------*/ /** * @packageDocumentation * @module mathjax2-extension */ import { JupyterFrontEndPlugin } from '@jupyterlab/application'; import { PageConfig } from '@jupyterlab/coreutils'; import { ILatexTypesetter } from '@jupyterlab/rendermime'; import { MathJaxTypesetter } from '@jupyterlab/mathjax2'; /** * The MathJax latexTypesetter plugin. */ const plugin: JupyterFrontEndPlugin<ILatexTypesetter> = { id: '@jupyterlab/mathjax2-extension:plugin', autoStart: true, provides: ILatexTypesetter, activate: () => { const url = PageConfig.getOption('fullMathjaxUrl'); const config = PageConfig.getOption('mathjaxConfig'); if (!url) { const message = `${plugin.id} uses 'mathJaxUrl' and 'mathjaxConfig' in PageConfig ` + `to operate but 'mathJaxUrl' was not found.`; throw new Error(message); } return new MathJaxTypesetter({ url, config }); } }; /** * Export the plugin as default. */ export default plugin;
/* ----------------------------------------------------------------------------- | Copyright (c) Jupyter Development Team. | Distributed under the terms of the Modified BSD License. |----------------------------------------------------------------------------*/ /** * @packageDocumentation * @module mathjax2-extension */ import { JupyterFrontEndPlugin } from '@jupyterlab/application'; import { PageConfig } from '@jupyterlab/coreutils'; import { ILatexTypesetter } from '@jupyterlab/rendermime'; import { MathJaxTypesetter } from '@jupyterlab/mathjax2'; /** * The MathJax latexTypesetter plugin. */ const plugin: JupyterFrontEndPlugin<ILatexTypesetter> = { id: '@jupyterlab/mathjax2-extension:plugin', autoStart: true, provides: ILatexTypesetter, activate: () => { const [urlParam, configParam] = ['fullMathjaxUrl', 'mathjaxConfig']; const url = PageConfig.getOption(urlParam); const config = PageConfig.getOption(configParam); if (!url) { const message = `${plugin.id} uses '${urlParam}' and '${configParam}' in PageConfig ` + `to operate but '${urlParam}' was not found.`; throw new Error(message); } return new MathJaxTypesetter({ url, config }); } }; /** * Export the plugin as default. */ export default plugin;
Update console message if fullMathjaxUrl is missing
Update console message if fullMathjaxUrl is missing
TypeScript
bsd-3-clause
jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab
--- +++ @@ -23,13 +23,14 @@ autoStart: true, provides: ILatexTypesetter, activate: () => { - const url = PageConfig.getOption('fullMathjaxUrl'); - const config = PageConfig.getOption('mathjaxConfig'); + const [urlParam, configParam] = ['fullMathjaxUrl', 'mathjaxConfig']; + const url = PageConfig.getOption(urlParam); + const config = PageConfig.getOption(configParam); if (!url) { const message = - `${plugin.id} uses 'mathJaxUrl' and 'mathjaxConfig' in PageConfig ` + - `to operate but 'mathJaxUrl' was not found.`; + `${plugin.id} uses '${urlParam}' and '${configParam}' in PageConfig ` + + `to operate but '${urlParam}' was not found.`; throw new Error(message); }
b5618bbbc731073b53d33585cc4125760cdf3cfd
app/src/lib/git/fetch.ts
app/src/lib/git/fetch.ts
import { git, envForAuthentication } from './core' import { Repository } from '../../models/repository' import { User } from '../../models/user' /** Fetch from the given remote. */ export async function fetch(repository: Repository, user: User | null, remote: string): Promise<void> { const options = { successExitCodes: new Set([ 0 ]), env: envForAuthentication(user), } await git([ 'fetch', '--prune', remote ], repository.path, 'fetch', options) } /** Fetch a given refspec from the given remote. */ export async function fetchRefspec(repository: Repository, user: User | null, remote: string, refspec: string): Promise<void> { const options = { successExitCodes: new Set([ 0, 128 ]), env: envForAuthentication(user), } await git([ 'fetch', remote, refspec ], repository.path, 'fetchRefspec', options) }
import { git, envForAuthentication, expectedAuthenticationErrors } from './core' import { Repository } from '../../models/repository' import { User } from '../../models/user' /** Fetch from the given remote. */ export async function fetch(repository: Repository, user: User | null, remote: string): Promise<void> { const options = { successExitCodes: new Set([ 0 ]), env: envForAuthentication(user), expectedErrors: expectedAuthenticationErrors(), } await git([ 'fetch', '--prune', remote ], repository.path, 'fetch', options) } /** Fetch a given refspec from the given remote. */ export async function fetchRefspec(repository: Repository, user: User | null, remote: string, refspec: string): Promise<void> { const options = { successExitCodes: new Set([ 0, 128 ]), env: envForAuthentication(user), expectedErrors: expectedAuthenticationErrors(), } await git([ 'fetch', remote, refspec ], repository.path, 'fetchRefspec', options) }
Revert "drop expected errors to raise the exception directly"
Revert "drop expected errors to raise the exception directly" This reverts commit 785dfebc947fd5b1173db0db9fde940efcd7404b.
TypeScript
mit
say25/desktop,gengjiawen/desktop,j-f1/forked-desktop,j-f1/forked-desktop,shiftkey/desktop,BugTesterTest/desktops,hjobrien/desktop,BugTesterTest/desktops,desktop/desktop,gengjiawen/desktop,desktop/desktop,hjobrien/desktop,say25/desktop,say25/desktop,j-f1/forked-desktop,BugTesterTest/desktops,kactus-io/kactus,j-f1/forked-desktop,gengjiawen/desktop,kactus-io/kactus,gengjiawen/desktop,hjobrien/desktop,say25/desktop,kactus-io/kactus,artivilla/desktop,BugTesterTest/desktops,shiftkey/desktop,desktop/desktop,artivilla/desktop,artivilla/desktop,hjobrien/desktop,kactus-io/kactus,artivilla/desktop,shiftkey/desktop,desktop/desktop,shiftkey/desktop
--- +++ @@ -1,4 +1,4 @@ -import { git, envForAuthentication } from './core' +import { git, envForAuthentication, expectedAuthenticationErrors } from './core' import { Repository } from '../../models/repository' import { User } from '../../models/user' @@ -7,6 +7,7 @@ const options = { successExitCodes: new Set([ 0 ]), env: envForAuthentication(user), + expectedErrors: expectedAuthenticationErrors(), } await git([ 'fetch', '--prune', remote ], repository.path, 'fetch', options) @@ -17,6 +18,7 @@ const options = { successExitCodes: new Set([ 0, 128 ]), env: envForAuthentication(user), + expectedErrors: expectedAuthenticationErrors(), } await git([ 'fetch', remote, refspec ], repository.path, 'fetchRefspec', options)
dbbbd22b945b53e8b7d888ea971482bfac25d319
src/adhocracy/adhocracy/frontend/static/js/Adhocracy/EmbedSpec.ts
src/adhocracy/adhocracy/frontend/static/js/Adhocracy/EmbedSpec.ts
/// <reference path="../../lib/DefinitelyTyped/jasmine/jasmine.d.ts"/> import Embed = require("./Embed"); export var register = () => { describe("Embed", () => { var $routeMock; var $compileMock; beforeEach(() => { $routeMock = { current: { params: { widget: "document-workbench", path: "/this/is/a/path", test: "\"&" } } }; // FIXME DefinitelyTyped does not yet know of `and`. $compileMock = (<any>jasmine.createSpy("$compileMock")) .and.returnValue(() => undefined); }); describe("route2template", () => { it("compiles a template from the parameters given in $route", () => { var expected = "<adh-document-workbench data-path=\"&#x27;/this/is/a/path&#x27;\" " + "data-test=\"&#x27;&quot;&amp;&#x27;\"></adh-document-workbench>"; expect(Embed.route2template($routeMock)).toBe(expected); }); }); describe("factory", () => { it("calls $compile", () => { var directive = Embed.factory($compileMock, $routeMock); directive.link(undefined, { contents: () => undefined, html: () => undefined }); expect($compileMock).toHaveBeenCalled(); }); }); }); };
/// <reference path="../../lib/DefinitelyTyped/jasmine/jasmine.d.ts"/> import Embed = require("./Embed"); export var register = () => { describe("Embed", () => { var $routeMock; var $compileMock; beforeEach(() => { $routeMock = { current: { params: { widget: "document-workbench", path: "/this/is/a/path", test: "\"'&" } } }; // FIXME DefinitelyTyped does not yet know of `and`. $compileMock = (<any>jasmine.createSpy("$compileMock")) .and.returnValue(() => undefined); }); describe("route2template", () => { it("compiles a template from the parameters given in $route", () => { var expected = "<adh-document-workbench data-path=\"&#x27;/this/is/a/path&#x27;\" " + "data-test=\"&#x27;&quot;\\&#x27;&amp;&#x27;\"></adh-document-workbench>"; expect(Embed.route2template($routeMock)).toBe(expected); }); }); describe("factory", () => { it("calls $compile", () => { var directive = Embed.factory($compileMock, $routeMock); directive.link(undefined, { contents: () => undefined, html: () => undefined }); expect($compileMock).toHaveBeenCalled(); }); }); }); };
Add quotation challenge to test case
Add quotation challenge to test case
TypeScript
agpl-3.0
xs2maverick/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator
--- +++ @@ -13,7 +13,7 @@ params: { widget: "document-workbench", path: "/this/is/a/path", - test: "\"&" + test: "\"'&" } } }; @@ -25,7 +25,7 @@ describe("route2template", () => { it("compiles a template from the parameters given in $route", () => { var expected = "<adh-document-workbench data-path=\"&#x27;/this/is/a/path&#x27;\" " + - "data-test=\"&#x27;&quot;&amp;&#x27;\"></adh-document-workbench>"; + "data-test=\"&#x27;&quot;\\&#x27;&amp;&#x27;\"></adh-document-workbench>"; expect(Embed.route2template($routeMock)).toBe(expected); }); });
547a1fe10ffdab1035cc9c42e8825222f40e04f9
src/router.tsx
src/router.tsx
import * as React from 'react'; import { AppStore } from './store'; import { Activities } from './containers/activities'; import { Video } from './containers/video'; import { observer } from 'mobx-react'; interface RouterProps { appStore: AppStore; } @observer export class Router extends React.Component<RouterProps> { render(): JSX.Element | null { const { appStore } = this.props; switch (appStore.route) { case 'activities': return <Activities appStore={appStore} />; case 'video/:id': return <Video appStore={appStore} id={appStore.params.id} />; default: return null; } } }
import * as React from 'react'; import { AppStore, Route } from './store'; import { observer } from 'mobx-react'; interface RouterProps { appStore: AppStore; } @observer export class Router extends React.Component<RouterProps> { render(): JSX.Element | null { const { appStore } = this.props; return <LazyComponent bundle={appStore.route} store={appStore} />; } } interface LazyComponentProps { bundle: Route; store: AppStore; } interface LazyComponentState { Component: React.ComponentClass<{ appStore: AppStore }> | null; } class LazyComponent extends React.Component<LazyComponentProps, LazyComponentState> { constructor(props) { super(props); this.state = { Component: null }; } componentWillReceiveProps(nextProps: LazyComponentProps) { let name = nextProps.bundle; if (name) { this.route(name); } } componentDidMount() { this.componentWillReceiveProps(this.props); } async route(name) { let target; if (name === 'activities') { target = await import('./containers/activities'); } if (name === 'video/:id') { target = await import('./containers/video'); } this.setState({ Component: target.default }); } render(): JSX.Element | null { const { Component } = this.state; if (Component) { return <Component appStore={this.props.store} {...this.props.store.params} />; } return null; } }
Make code-splitting work by adding LazyComponent
refactor: Make code-splitting work by adding LazyComponent
TypeScript
mit
misantronic/rbtv.ts.youtube,misantronic/rbtv.ts.youtube,misantronic/rbtv.ts.youtube
--- +++ @@ -1,7 +1,5 @@ import * as React from 'react'; -import { AppStore } from './store'; -import { Activities } from './containers/activities'; -import { Video } from './containers/video'; +import { AppStore, Route } from './store'; import { observer } from 'mobx-react'; interface RouterProps { @@ -13,13 +11,59 @@ render(): JSX.Element | null { const { appStore } = this.props; - switch (appStore.route) { - case 'activities': - return <Activities appStore={appStore} />; - case 'video/:id': - return <Video appStore={appStore} id={appStore.params.id} />; - default: - return null; + return <LazyComponent bundle={appStore.route} store={appStore} />; + } +} + +interface LazyComponentProps { + bundle: Route; + store: AppStore; +} + +interface LazyComponentState { + Component: React.ComponentClass<{ appStore: AppStore }> | null; +} + +class LazyComponent extends React.Component<LazyComponentProps, LazyComponentState> { + constructor(props) { + super(props); + this.state = { + Component: null + }; + } + + componentWillReceiveProps(nextProps: LazyComponentProps) { + let name = nextProps.bundle; + + if (name) { + this.route(name); } } + + componentDidMount() { + this.componentWillReceiveProps(this.props); + } + + async route(name) { + let target; + + if (name === 'activities') { + target = await import('./containers/activities'); + } + if (name === 'video/:id') { + target = await import('./containers/video'); + } + + this.setState({ Component: target.default }); + } + + render(): JSX.Element | null { + const { Component } = this.state; + + if (Component) { + return <Component appStore={this.props.store} {...this.props.store.params} />; + } + + return null; + } }
66467a4647010cf28bf98b2668acc4b1c789008d
index.ts
index.ts
export {ModelServiceRef, DatabaseConnectionRef, ModelsConfig} from "./src/tokens"; export {BaseModel} from "./src/base_model"; export {ModelCollectionObservable} from "./src/model_collection.interface"; export {ModelService} from "./src/model.service"; import {ModelServiceRef, DatabaseConnectionRef, ModelsConfig} from "./src/tokens"; import {provide, ApplicationRef} from "@angular/core"; import {AngularFire, FirebaseRef} from 'angularfire2/angularfire2'; import {ModelService} from './src/model.service'; import {BaseModel} from "./src/base_model"; import {FirebaseConnection} from './src/firebase/firebase.connection'; // provide(ModelsConfig, { // useValue: models // }), export const MODEL_PROVIDERS:any[] = [ {provide: ModelsConfig, useValue: {}}, { provide: ModelServiceRef, useClass: ModelService }, { provide: DatabaseConnectionRef, useFactory: (ref:firebase.app.App, app:ApplicationRef, af:AngularFire, ms: ModelService) => { let cache = {}; return (type: string) => { return cache[type] = cache[type] || (new FirebaseConnection(app, ref, af, ms)).setType(type); }; }, deps: [FirebaseRef, ApplicationRef, AngularFire, ModelServiceRef] }, ];
export {ModelServiceRef, DatabaseConnectionRef, ModelsConfig} from "./src/tokens"; export {BaseModel} from "./src/base_model"; export {ModelCollectionObservable} from "./src/model_collection.interface"; export {ModelService} from "./src/model.service"; import {ModelServiceRef, DatabaseConnectionRef, ModelsConfig} from "./src/tokens"; import {provide, ApplicationRef} from "@angular/core"; import {AngularFire, FirebaseRef} from 'angularfire2/angularfire2'; import {ModelService} from './src/model.service'; import {BaseModel} from "./src/base_model"; import {FirebaseConnection} from './src/firebase/firebase.connection'; // provide(ModelsConfig, { // useValue: models // }), export const MODEL_PROVIDERS:any[] = [ { provide: ModelServiceRef, useClass: ModelService }, { provide: DatabaseConnectionRef, useFactory: (ref:firebase.app.App, app:ApplicationRef, af:AngularFire, ms: ModelService) => { let cache = {}; return (type: string) => { return cache[type] = cache[type] || (new FirebaseConnection(app, ref, af, ms)).setType(type); }; }, deps: [FirebaseRef, ApplicationRef, AngularFire, ModelServiceRef] }, ];
Remove useless ModelsConfig provide in obsrm that was potentially overwriting the APP provided config.
Remove useless ModelsConfig provide in obsrm that was potentially overwriting the APP provided config.
TypeScript
mit
tomdegoede/obsrm
--- +++ @@ -15,8 +15,6 @@ // }), export const MODEL_PROVIDERS:any[] = [ - {provide: ModelsConfig, useValue: {}}, - { provide: ModelServiceRef, useClass: ModelService }, { provide: DatabaseConnectionRef,
dd70134584c4ef9673826ce40905cda6e20b03aa
app/src/ui/updates/update-available.tsx
app/src/ui/updates/update-available.tsx
import * as React from 'react' import { Button } from '../lib/button' import { Dispatcher } from '../../lib/dispatcher' import { updateStore } from '../lib/update-store' import { ButtonGroup } from '../lib/button-group' import { Dialog, DialogContent, DialogFooter } from '../dialog' interface IUpdateAvailableProps { readonly dispatcher: Dispatcher } /** * 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 ( <Dialog id='update-available' title={__DARWIN__ ? 'Update Available' : 'Update available'} onSubmit={this.updateNow} onDismissed={this.dismiss} > <DialogContent> GitHub Desktop will be updated after it restarts! </DialogContent> <DialogFooter> <ButtonGroup> <Button type='submit'>{__DARWIN__ ? 'Update Now' : 'Update now'}</Button> <Button onClick={this.dismiss}>Cancel</Button> </ButtonGroup> </DialogFooter> </Dialog> ) } private updateNow = () => { updateStore.quitAndInstallUpdate() } private dismiss = () => { this.props.dispatcher.closePopup() } }
import * as React from 'react' import { LinkButton } from '../lib/link-button' import { Dispatcher } from '../../lib/dispatcher' import { updateStore } from '../lib/update-store' import { Octicon, OcticonSymbol } from '../octicons' // import { Dialog, DialogContent, DialogFooter } from '../dialog' interface IUpdateAvailableProps { readonly dispatcher: Dispatcher } /** * 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' title={__DARWIN__ ? 'Update Available' : 'Update available'} onSubmit={this.updateNow} > <span> <Octicon symbol={OcticonSymbol.desktopDownload} /> 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>. <a onClick={this.dismiss}> <Octicon symbol={OcticonSymbol.x} /> </a> </span> </div> ) } private updateNow = () => { updateStore.quitAndInstallUpdate() } private dismiss = () => { this.props.dispatcher.closePopup() } }
Rewrite component so that it's not based on a dialog
Rewrite component so that it's not based on a dialog
TypeScript
mit
j-f1/forked-desktop,kactus-io/kactus,BugTesterTest/desktops,shiftkey/desktop,j-f1/forked-desktop,artivilla/desktop,shiftkey/desktop,gengjiawen/desktop,BugTesterTest/desktops,desktop/desktop,gengjiawen/desktop,desktop/desktop,kactus-io/kactus,say25/desktop,shiftkey/desktop,hjobrien/desktop,say25/desktop,artivilla/desktop,gengjiawen/desktop,hjobrien/desktop,hjobrien/desktop,desktop/desktop,shiftkey/desktop,artivilla/desktop,BugTesterTest/desktops,j-f1/forked-desktop,hjobrien/desktop,gengjiawen/desktop,j-f1/forked-desktop,artivilla/desktop,say25/desktop,desktop/desktop,kactus-io/kactus,BugTesterTest/desktops,say25/desktop,kactus-io/kactus
--- +++ @@ -1,9 +1,9 @@ import * as React from 'react' -import { Button } from '../lib/button' +import { LinkButton } from '../lib/link-button' import { Dispatcher } from '../../lib/dispatcher' import { updateStore } from '../lib/update-store' -import { ButtonGroup } from '../lib/button-group' -import { Dialog, DialogContent, DialogFooter } from '../dialog' +import { Octicon, OcticonSymbol } from '../octicons' +// import { Dialog, DialogContent, DialogFooter } from '../dialog' interface IUpdateAvailableProps { readonly dispatcher: Dispatcher @@ -16,23 +16,20 @@ export class UpdateAvailable extends React.Component<IUpdateAvailableProps, void> { public render() { return ( - <Dialog + <div id='update-available' title={__DARWIN__ ? 'Update Available' : 'Update available'} onSubmit={this.updateNow} - onDismissed={this.dismiss} > - <DialogContent> - GitHub Desktop will be updated after it restarts! - </DialogContent> + <span> + <Octicon symbol={OcticonSymbol.desktopDownload} /> + 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>. - <DialogFooter> - <ButtonGroup> - <Button type='submit'>{__DARWIN__ ? 'Update Now' : 'Update now'}</Button> - <Button onClick={this.dismiss}>Cancel</Button> - </ButtonGroup> - </DialogFooter> - </Dialog> + <a onClick={this.dismiss}> + <Octicon symbol={OcticonSymbol.x} /> + </a> + </span> + </div> ) }
81ba488c3a2d3f9336b8e278c7b1159c1bc2c2ff
public/ts/ConnectState.ts
public/ts/ConnectState.ts
module Scuffle { export class ConnectState extends Phaser.State { game : Game create() { var group = this.add.group() group.alpha = 0 var text = this.add.text(this.world.centerX, this.world.centerY, this.game.socket === undefined ? 'Connecting' : 'Reconnecting', undefined, group) text.anchor.setTo(0.5, 0.5) text.font = 'Iceland' text.fontSize = 60 text.fill = '#acf' var tween = this.add.tween(group).to({ alpha: 1 }, 500, Phaser.Easing.Linear.None, true) tween.onComplete.add(() => { if(this.game.socket === undefined) this.game.socket = io.connect('http://yellow.shockk.co.uk:1337') this.game.socket.once('connect', () => { var tween = this.add.tween(group).to({ alpha: 0 }, 500, Phaser.Easing.Linear.None, true) tween.onComplete.add(() => this.game.state.start('Preload')) }) this.game.socket.on('disconnect', () => this.game.state.start('Connect')) }) } } }
module Scuffle { export class ConnectState extends Phaser.State { game : Game create() { var group = this.add.group() group.alpha = 0 var text = this.add.text(this.world.centerX, this.world.centerY, this.game.socket === undefined ? 'Connecting' : 'Reconnecting', undefined, group) text.anchor.setTo(0.5, 0.5) text.font = 'Iceland' text.fontSize = 60 text.fill = '#acf' var tween = this.add.tween(group).to({ alpha: 1 }, 500, Phaser.Easing.Linear.None, true) tween.onComplete.add(() => { if(this.game.socket === undefined) this.game.socket = io.connect('http://yellow.shockk.co.uk:1337') else this.game.socket.removeAllListeners() this.game.socket.once('connect', () => { var tween = this.add.tween(group).to({ alpha: 0 }, 500, Phaser.Easing.Linear.None, true) tween.onComplete.add(() => this.game.state.start('Preload')) }) this.game.socket.once('disconnect', () => this.game.state.start('Connect')) }) } } }
Remove listeners on reconnection, only fire disconnect event once
Remove listeners on reconnection, only fire disconnect event once
TypeScript
apache-2.0
shockkolate/scuffle,shockkolate/scuffle,shockkolate/scuffle
--- +++ @@ -18,12 +18,14 @@ tween.onComplete.add(() => { if(this.game.socket === undefined) this.game.socket = io.connect('http://yellow.shockk.co.uk:1337') + else + this.game.socket.removeAllListeners() this.game.socket.once('connect', () => { var tween = this.add.tween(group).to({ alpha: 0 }, 500, Phaser.Easing.Linear.None, true) tween.onComplete.add(() => this.game.state.start('Preload')) }) - this.game.socket.on('disconnect', () => this.game.state.start('Connect')) + this.game.socket.once('disconnect', () => this.game.state.start('Connect')) }) } }
c065e7dfcc2374ec125180bbc558e3539e7a8ff1
src/lib/Scenes/Show/Components/Artists/Components/ArtistListItem.tsx
src/lib/Scenes/Show/Components/Artists/Components/ArtistListItem.tsx
import { Box, Flex, Sans } from "@artsy/palette" import InvertedButton from "lib/Components/Buttons/InvertedButton" import React from "react" interface Props { name: string isFollowed: boolean onPress: () => void isFollowedChanging: boolean } export const ArtistListItem: React.SFC<Props> = ({ name, isFollowed, onPress, isFollowedChanging }) => { return ( <Flex justifyContent="space-between" alignItems="center" flexDirection="row"> <Sans size="3">{name}</Sans> <Box width={112} height={32}> <InvertedButton text={isFollowed ? "Following" : "Follow"} onPress={onPress} selected={isFollowed} inProgress={isFollowedChanging} /> </Box> </Flex> ) }
import { Box, Flex, Sans } from "@artsy/palette" import InvertedButton from "lib/Components/Buttons/InvertedButton" import React from "react" interface Props { name: string isFollowed: boolean onPress: () => void isFollowedChanging: boolean } export const ArtistListItem: React.SFC<Props> = ({ name, isFollowed, onPress, isFollowedChanging }) => { return ( <Flex justifyContent="space-between" alignItems="center" flexDirection="row"> <Sans size="3">{name}</Sans> {/* TODO: Remove hardcoded sizes once designs firm up */} <Box width={112} height={32}> <InvertedButton text={isFollowed ? "Following" : "Follow"} onPress={onPress} selected={isFollowed} inProgress={isFollowedChanging} /> </Box> </Flex> ) }
Add TODO comment to denote temporary size hardcoding
Add TODO comment to denote temporary size hardcoding
TypeScript
mit
artsy/emission,artsy/eigen,artsy/eigen,artsy/eigen,artsy/emission,artsy/eigen,artsy/eigen,artsy/emission,artsy/emission,artsy/emission,artsy/eigen,artsy/emission,artsy/emission,artsy/eigen
--- +++ @@ -13,6 +13,7 @@ return ( <Flex justifyContent="space-between" alignItems="center" flexDirection="row"> <Sans size="3">{name}</Sans> + {/* TODO: Remove hardcoded sizes once designs firm up */} <Box width={112} height={32}> <InvertedButton text={isFollowed ? "Following" : "Follow"}
ddd3214b8fcf3e75bd30a654d09b5c53dfdf164c
cucumber-react/javascript/src/components/gherkin/GherkinDocument.tsx
cucumber-react/javascript/src/components/gherkin/GherkinDocument.tsx
import { messages } from 'cucumber-messages' import React from 'react' import Feature from './Feature' interface IProps { gherkinDocument: messages.IGherkinDocument } const GherkinDocument: React.FunctionComponent<IProps> = ({ gherkinDocument, }) => { return ( gherkinDocument.feature && <Feature feature={gherkinDocument.feature}/> ) } export default GherkinDocument
import { messages } from 'cucumber-messages' import React from 'react' import Feature from './Feature' interface IProps { gherkinDocument: messages.IGherkinDocument } const GherkinDocument: React.FunctionComponent<IProps> = ({ gherkinDocument, }) => { return ( gherkinDocument.feature ? <Feature feature={gherkinDocument.feature}/> : null ) } export default GherkinDocument
Return null when there is no feature
Return null when there is no feature
TypeScript
mit
cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber
--- +++ @@ -10,7 +10,7 @@ gherkinDocument, }) => { return ( - gherkinDocument.feature && <Feature feature={gherkinDocument.feature}/> + gherkinDocument.feature ? <Feature feature={gherkinDocument.feature}/> : null ) }
d6f692535c4f28de5ed5aeab58481d9f808e4148
src/next/mutators.ts
src/next/mutators.ts
import { Mutator } from './mutators/Mutator'; import { IdentifierMutator } from './mutators/IdentifierMutator'; import { ImportSpecifierMutator } from './mutators/ImportSpecifierMutator'; import { InterfaceDeclarationMutator } from './mutators/InterfaceDeclararionMutator'; export const mutators: Mutator[] = [ new IdentifierMutator(), new ImportSpecifierMutator(), new InterfaceDeclarationMutator() ];
import { Mutator } from './mutators/Mutator'; import { InterfaceDeclarationMutator } from './mutators/InterfaceDeclararionMutator'; import { VariableDeclarationListMutator } from './mutators/VariableDeclarationListMutator'; export const mutators: Mutator[] = [ new InterfaceDeclarationMutator(), new VariableDeclarationListMutator(), ];
Change to latest mutator instances.
Change to latest mutator instances.
TypeScript
mit
fabiandev/ts-runtime,fabiandev/ts-runtime,fabiandev/ts-runtime
--- +++ @@ -1,11 +1,9 @@ import { Mutator } from './mutators/Mutator'; -import { IdentifierMutator } from './mutators/IdentifierMutator'; -import { ImportSpecifierMutator } from './mutators/ImportSpecifierMutator'; import { InterfaceDeclarationMutator } from './mutators/InterfaceDeclararionMutator'; +import { VariableDeclarationListMutator } from './mutators/VariableDeclarationListMutator'; export const mutators: Mutator[] = [ - new IdentifierMutator(), - new ImportSpecifierMutator(), - new InterfaceDeclarationMutator() + new InterfaceDeclarationMutator(), + new VariableDeclarationListMutator(), ];
c3eac4bf993119318f28c4c90d0b66b3d5704574
json.ts
json.ts
/** * Wraps parsing of JSON, so that an error is logged, but no exception is thrown */ export function safeParseJson (value?: string|false|null) : {[k: string]: any}|null { try { if (value) { const content = value.trim(); return (content !== "") ? JSON.parse(content) : null; } } catch (e) { console.error(`Could not parse JSON content: ${e.message}`, e); } return null; } /** * Parses JSON from the given element's content. */ export function parseElementAsJson (element: HTMLElement) : {[k: string]: any}|null { return safeParseJson( (element.textContent || "") .replace(/&lt;/g, "<") .replace(/&gt;/g, ">") .replace(/&amp;/g, "&") ); }
/** * Wraps parsing of JSON, so that an error is logged, but no exception is thrown */ export function safeParseJson<T extends {[k: string]: any}> (value?: string|false|null) : T|null { try { if (value) { const content = value.trim(); return (content !== "") ? JSON.parse(content) : null; } } catch (e) { console.error(`Could not parse JSON content: ${e.message}`, e); } return null; } /** * Parses JSON from the given element's content. */ export function parseElementAsJson<T extends {[k: string]: any}> (element: HTMLElement) : T|null { return safeParseJson( (element.textContent || "") .replace(/&lt;/g, "<") .replace(/&gt;/g, ">") .replace(/&amp;/g, "&") ); }
Make JSON method return types generic
Make JSON method return types generic
TypeScript
bsd-3-clause
Becklyn/mojave,Becklyn/mojave,Becklyn/mojave
--- +++ @@ -1,7 +1,7 @@ /** * Wraps parsing of JSON, so that an error is logged, but no exception is thrown */ -export function safeParseJson (value?: string|false|null) : {[k: string]: any}|null +export function safeParseJson<T extends {[k: string]: any}> (value?: string|false|null) : T|null { try { @@ -24,7 +24,7 @@ /** * Parses JSON from the given element's content. */ -export function parseElementAsJson (element: HTMLElement) : {[k: string]: any}|null +export function parseElementAsJson<T extends {[k: string]: any}> (element: HTMLElement) : T|null { return safeParseJson( (element.textContent || "")
aad99397b58b4c5a91c1dab2c5f67f58bb18346f
src/responseFormatUtility.ts
src/responseFormatUtility.ts
'use strict'; import { window } from 'vscode'; import { MimeUtility } from './mimeUtility'; import { format as JSONFormat } from "jsonc-parser"; import { EOL } from "os"; const pd = require('pretty-data').pd; export class ResponseFormatUtility { public static FormatBody(body: string, contentType: string, suppressValidation: boolean): string { if (contentType) { let mime = MimeUtility.parse(contentType); let type = mime.type; let suffix = mime.suffix; if (type === 'application/json' || suffix === '+json') { if (ResponseFormatUtility.IsJsonString(body)) { const edits = JSONFormat(body, undefined, { tabSize: 2, insertSpaces: true, eol: EOL }); body = edits.reduceRight( (prev, cur) => prev.substring(0, cur.offset) + cur.content + prev.substring(cur.offset + cur.length), body); } else if (!suppressValidation) { window.showWarningMessage('The content type of response is application/json, while response body is not a valid json string'); } } else if (type === 'application/xml' || type === 'text/xml' || (type === 'application/atom' && suffix === '+xml')) { body = pd.xml(body); } else if (type === 'text/css') { body = pd.css(body); } } return body; } public static IsJsonString(data: string) { try { JSON.parse(data); return true; } catch { return false; } } }
'use strict'; import { window } from 'vscode'; import { MimeUtility } from './mimeUtility'; import { format as JSONFormat, applyEdits } from "jsonc-parser"; import { EOL } from "os"; const pd = require('pretty-data').pd; export class ResponseFormatUtility { public static FormatBody(body: string, contentType: string, suppressValidation: boolean): string { if (contentType) { let mime = MimeUtility.parse(contentType); let type = mime.type; let suffix = mime.suffix; if (type === 'application/json' || suffix === '+json') { if (ResponseFormatUtility.IsJsonString(body)) { const edits = JSONFormat(body, undefined, { tabSize: 2, insertSpaces: true, eol: EOL }); body = applyEdits(body, edits); } else if (!suppressValidation) { window.showWarningMessage('The content type of response is application/json, while response body is not a valid json string'); } } else if (type === 'application/xml' || type === 'text/xml' || (type === 'application/atom' && suffix === '+xml')) { body = pd.xml(body); } else if (type === 'text/css') { body = pd.css(body); } } return body; } public static IsJsonString(data: string) { try { JSON.parse(data); return true; } catch { return false; } } }
Use native applyEdits function from node-jsonc-parser module
Use native applyEdits function from node-jsonc-parser module
TypeScript
mit
Huachao/vscode-restclient,Huachao/vscode-restclient
--- +++ @@ -2,7 +2,7 @@ import { window } from 'vscode'; import { MimeUtility } from './mimeUtility'; -import { format as JSONFormat } from "jsonc-parser"; +import { format as JSONFormat, applyEdits } from "jsonc-parser"; import { EOL } from "os"; const pd = require('pretty-data').pd; @@ -16,9 +16,7 @@ suffix === '+json') { if (ResponseFormatUtility.IsJsonString(body)) { const edits = JSONFormat(body, undefined, { tabSize: 2, insertSpaces: true, eol: EOL }); - body = edits.reduceRight( - (prev, cur) => prev.substring(0, cur.offset) + cur.content + prev.substring(cur.offset + cur.length), - body); + body = applyEdits(body, edits); } else if (!suppressValidation) { window.showWarningMessage('The content type of response is application/json, while response body is not a valid json string'); }
02dfee06151467d6e0b4787d1a8eb1b86d979c7c
src/services/item-service.ts
src/services/item-service.ts
import { Item } from '../models/item'; import { Trie } from '../models/trie'; import { ItemRepository } from '../repository/item-repository'; export class ItemService { private readonly repository: ItemRepository; constructor(repository: ItemRepository) { this.repository = repository; } page(items: number[], page: number, pageSize: number): Promise<Item[]> { let start = (page - 1) * pageSize; let end = page * pageSize; let ids = items.slice(start, end); return this.fetchItems(ids); } ids(name: string): Promise<number[]> { return this.repository.findIdsByName(name); } async populate(id: number): Promise<Trie<Item> | undefined> { let value = await this.repository.findById(id); if (value === undefined) { return undefined; } let children: (Trie<Item> | undefined)[] = []; if (value.kids !== undefined && value.kids.length > 0) { children = await Promise.all(value.kids.map(kid => this.populate(kid))); } return { value, children }; } private async fetchItems(ids: number[]): Promise<Item[]> { let result: Item[] = []; for (let id of ids) { let item = await this.repository.findById(id); if (item !== undefined) { result.push(item); } } return result; } }
import { autoinject } from 'aurelia-framework'; import { Item } from '../models/item'; import { Trie } from '../models/trie'; import { ItemRepository } from '../repository/item-repository'; @autoinject() export class ItemService { private readonly repository: ItemRepository; constructor(repository: ItemRepository) { this.repository = repository; } page(items: number[], page: number, pageSize: number): Promise<Item[]> { let start = (page - 1) * pageSize; let end = page * pageSize; let ids = items.slice(start, end); return this.fetchItems(ids); } ids(name: string): Promise<number[]> { return this.repository.findIdsByName(name); } async populate(id: number): Promise<Trie<Item> | undefined> { let value = await this.repository.findById(id); if (value === undefined) { return undefined; } let children: (Trie<Item> | undefined)[] = []; if (value.kids !== undefined && value.kids.length > 0) { children = await Promise.all(value.kids.map(kid => this.populate(kid))); } return { value, children }; } private async fetchItems(ids: number[]): Promise<Item[]> { let result: Item[] = []; for (let id of ids) { let item = await this.repository.findById(id); if (item !== undefined) { result.push(item); } } return result; } }
Add missing autoinject annotation to ItemService
Add missing autoinject annotation to ItemService
TypeScript
isc
michaelbull/aurelia-hacker-news,michaelbull/aurelia-hacker-news,MikeBull94/aurelia-hacker-news,michaelbull/aurelia-hacker-news,MikeBull94/aurelia-hacker-news
--- +++ @@ -1,7 +1,9 @@ +import { autoinject } from 'aurelia-framework'; import { Item } from '../models/item'; import { Trie } from '../models/trie'; import { ItemRepository } from '../repository/item-repository'; +@autoinject() export class ItemService { private readonly repository: ItemRepository;
d501bea6bbd85415f05093a520761fe50288cd1e
src/constants/settings.ts
src/constants/settings.ts
import { PersistedStateKey, ImmutablePersistedStateKey } from '../types'; export const PERSISTED_STATE_WHITELIST: PersistedStateKey[] = [ 'tab', 'account', 'hitBlocklist', 'hitDatabase', 'requesterBlocklist', 'sortingOption', 'searchOptions', 'topticonSettings', 'watchers', 'audioSettingsV1', 'dailyEarningsGoal', 'notificationSettings' ]; export const IMMUTABLE_PERSISTED_STATE_WHITELIST: ImmutablePersistedStateKey[] = [ 'hitBlocklist', 'requesterBlocklist', 'watchers', 'hitDatabase' ];
import { PersistedStateKey, ImmutablePersistedStateKey } from '../types'; export const PERSISTED_STATE_WHITELIST: PersistedStateKey[] = [ 'tab', 'account', 'hitBlocklist', 'hitDatabase', 'requesterBlocklist', 'sortingOption', 'searchOptions', 'topticonSettings', 'watchers', 'watcherFolders', 'watcherTreeSettings', 'audioSettingsV1', 'dailyEarningsGoal', 'notificationSettings' ]; export const IMMUTABLE_PERSISTED_STATE_WHITELIST: ImmutablePersistedStateKey[] = [ 'hitBlocklist', 'requesterBlocklist', 'watchers', 'hitDatabase' ];
Add watcherFolders and watcherTreeSettings to PERSISTED_STATE_WHITELIST.
Add watcherFolders and watcherTreeSettings to PERSISTED_STATE_WHITELIST.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -10,6 +10,8 @@ 'searchOptions', 'topticonSettings', 'watchers', + 'watcherFolders', + 'watcherTreeSettings', 'audioSettingsV1', 'dailyEarningsGoal', 'notificationSettings'
905da1ff6125b9bf887f7d219e0c81cdf6c45936
src/dev/stories/index.tsx
src/dev/stories/index.tsx
import 'babel-polyfill' import React from 'react' import { storiesOf } from '@storybook/react' import ProgressStepContainer from 'src/common-ui/components/progress-step-container' import OnboardingTooltip from 'src/overview/onboarding/components/onboarding-tooltip' storiesOf('ProgressContainer', module) .add('No steps seen/completed', () => ( <ProgressStepContainer totalSteps={4} onStepClick={() => undefined} /> )) .add('All steps seen', () => ( <ProgressStepContainer totalSteps={4} currentStep={4} onStepClick={() => undefined} /> )) storiesOf('Onboarding Tooltip', module).add('Import example', () => ( <OnboardingTooltip descriptionText="Import your existing bookmarks &amp; web history from Pocket, Diigo, Raindrop.io and many more." CTAText="Import" onCTAClick={() => undefined} onDismiss={() => undefined} /> ))
import 'babel-polyfill' import React from 'react' import { storiesOf } from '@storybook/react' import QRCanvas from 'src/common-ui/components/qr-canvas' import ProgressStepContainer from 'src/common-ui/components/progress-step-container' import OnboardingTooltip from 'src/overview/onboarding/components/onboarding-tooltip' storiesOf('ProgressContainer', module) .add('No steps seen/completed', () => ( <ProgressStepContainer totalSteps={4} onStepClick={() => undefined} /> )) .add('All steps seen', () => ( <ProgressStepContainer totalSteps={4} currentStep={4} onStepClick={() => undefined} /> )) storiesOf('Onboarding Tooltip', module).add('Import example', () => ( <OnboardingTooltip descriptionText="Import your existing bookmarks &amp; web history from Pocket, Diigo, Raindrop.io and many more." CTAText="Import" onCTAClick={() => undefined} onDismiss={() => undefined} /> )) const longText = ` Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Dolor sed viverra ipsum nunc aliquet bibendum enim. In massa tempor nec feugiat. Nunc aliquet bibendum enim facilisis gravida. Nisl nunc mi ipsum faucibus vitae aliquet nec ullamcorper. Amet luctus venenatis lectus magna fringilla. Volutpat maecenas volutpat blandit aliquam etiam erat velit scelerisque in. Egestas egestas fringilla phasellus faucibus scelerisque eleifend. Sagittis orci a scelerisque purus semper eget duis. Nulla pharetra diam sit amet nisl suscipit. Sed adipiscing diam donec adipiscing tristique risus nec feugiat in. ' Fusce ut placerat orci nulla. Pharetra vel turpis nunc eget lorem dolor. Tristique senectus et netus et malesuada. ` storiesOf('QR Code creation', module) .add('HTML canvas short example', () => <QRCanvas toEncode="test" />) .add('HTML canvas long example', () => <QRCanvas toEncode={longText} />)
Add some storybook stories to demonstrate QRCanvas usage
Add some storybook stories to demonstrate QRCanvas usage
TypeScript
mit
WorldBrain/WebMemex,WorldBrain/WebMemex
--- +++ @@ -2,6 +2,7 @@ import React from 'react' import { storiesOf } from '@storybook/react' +import QRCanvas from 'src/common-ui/components/qr-canvas' import ProgressStepContainer from 'src/common-ui/components/progress-step-container' import OnboardingTooltip from 'src/overview/onboarding/components/onboarding-tooltip' @@ -25,3 +26,17 @@ onDismiss={() => undefined} /> )) + +const longText = ` +Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +Dolor sed viverra ipsum nunc aliquet bibendum enim. In massa tempor nec feugiat. +Nunc aliquet bibendum enim facilisis gravida. Nisl nunc mi ipsum faucibus vitae aliquet nec ullamcorper. +Amet luctus venenatis lectus magna fringilla. Volutpat maecenas volutpat blandit aliquam etiam erat velit scelerisque in. +Egestas egestas fringilla phasellus faucibus scelerisque eleifend. Sagittis orci a scelerisque purus semper eget duis. +Nulla pharetra diam sit amet nisl suscipit. Sed adipiscing diam donec adipiscing tristique risus nec feugiat in. ' +Fusce ut placerat orci nulla. Pharetra vel turpis nunc eget lorem dolor. Tristique senectus et netus et malesuada. +` + +storiesOf('QR Code creation', module) + .add('HTML canvas short example', () => <QRCanvas toEncode="test" />) + .add('HTML canvas long example', () => <QRCanvas toEncode={longText} />)
73b85378c45357c1521a4c2116b3d81f45beb103
src/utils/wrapConstructor.ts
src/utils/wrapConstructor.ts
import { assignAll } from './assignAll'; const PROPERTY_EXCLUDES = [ 'length', 'name', 'arguments', 'called', 'prototype' ]; /** * Wraps a constructor in a wrapper function and copies all static properties * and methods to the new constructor. * @export * @param {Function} Ctor * @param {(Ctor: Function, ...args: any[]) => any} wrapper * @returns {Function} */ export function wrapConstructor(Ctor: Function, wrapper: (Ctor: Function, ...args: any[]) => any): Function { function ConstructorWrapper(...args: any[]) { return wrapper.call(this, Ctor, ...args); } ConstructorWrapper.prototype = Ctor.prototype; return assignAll(ConstructorWrapper, Ctor, PROPERTY_EXCLUDES); }
import { assignAll } from './assignAll'; const PROPERTY_EXCLUDES = [ 'length', 'name', 'arguments', 'called', 'prototype' ]; /** * Wraps a constructor in a wrapper function and copies all static properties * and methods to the new constructor. * @export * @param {Function} Ctor * @param {(Ctor: Function, ...args: any[]) => any} wrapper * @returns {Function} */ export function wrapConstructor(Ctor: Function, wrapper: (Ctor: Function, ...args: any[]) => any): Function { function ConstructorWrapper(...args: any[]) { return wrapper.call(this, Ctor, ...args); } ConstructorWrapper.prototype = Ctor.prototype; Object.defineProperty(ConstructorWrapper, 'name', { writable: true }); (ConstructorWrapper as any).name = Ctor.name; return assignAll(ConstructorWrapper, Ctor, PROPERTY_EXCLUDES); }
Copy original function name to wrapper
fix(BindAll): Copy original function name to wrapper
TypeScript
mit
steelsojka/lodash-decorators
--- +++ @@ -22,6 +22,8 @@ } ConstructorWrapper.prototype = Ctor.prototype; + Object.defineProperty(ConstructorWrapper, 'name', { writable: true }); + (ConstructorWrapper as any).name = Ctor.name; return assignAll(ConstructorWrapper, Ctor, PROPERTY_EXCLUDES); }
23c5f39e8e408317362ebe33e9be6c180242b8b8
app/src/lib/fatal-error.ts
app/src/lib/fatal-error.ts
/** Throw an error. */ export default function fatalError(msg: string): never { throw new Error(msg) }
/** Throw an error. */ export default function fatalError(msg: string): never { throw new Error(msg) } /** * Utility function used to achieve exhaustive type checks at compile time. * * If the type system is bypassed or this method will throw an exception * using the second parameter as the message. * * @param {x} Placeholder parameter in order to leverage the type * system. Pass the variable which has been type narrowed * in an exhaustive check. * * @param {message} The message to be used in the runtime exception. * */ export function assertNever(x: never, message: string): never { throw new Error(message) }
Add type helper for exhaustive checks
Add type helper for exhaustive checks
TypeScript
mit
shiftkey/desktop,kactus-io/kactus,BugTesterTest/desktops,say25/desktop,kactus-io/kactus,hjobrien/desktop,shiftkey/desktop,BugTesterTest/desktops,hjobrien/desktop,gengjiawen/desktop,artivilla/desktop,BugTesterTest/desktops,kactus-io/kactus,BugTesterTest/desktops,artivilla/desktop,desktop/desktop,artivilla/desktop,gengjiawen/desktop,desktop/desktop,j-f1/forked-desktop,gengjiawen/desktop,shiftkey/desktop,shiftkey/desktop,hjobrien/desktop,hjobrien/desktop,desktop/desktop,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,say25/desktop,j-f1/forked-desktop,say25/desktop,gengjiawen/desktop,artivilla/desktop,j-f1/forked-desktop,desktop/desktop
--- +++ @@ -2,3 +2,20 @@ export default function fatalError(msg: string): never { throw new Error(msg) } + +/** + * Utility function used to achieve exhaustive type checks at compile time. + * + * If the type system is bypassed or this method will throw an exception + * using the second parameter as the message. + * + * @param {x} Placeholder parameter in order to leverage the type + * system. Pass the variable which has been type narrowed + * in an exhaustive check. + * + * @param {message} The message to be used in the runtime exception. + * + */ +export function assertNever(x: never, message: string): never { + throw new Error(message) +}
2e7e06ddf346601573351c83dd45722209ea3694
packages/lesswrong/platform/webpack/lib/random.ts
packages/lesswrong/platform/webpack/lib/random.ts
import * as _ from 'underscore'; // Excludes 0O1lIUV const unmistakableChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTWXYZ23456789"; export const randomId = () => { if (webpackIsServer) { const crypto = require('crypto'); const bytes = crypto.randomBytes(17); const result = []; for (let byte of bytes) { // Discards part of each byte and has modulo bias. Doesn't matter in // this context. result.push(unmistakableChars[byte % unmistakableChars.length]); } return result.join(''); } else { const result = []; function randInt(max) { return Math.floor(Math.random() * max); } for (let i=0; i<17; i++) result.push(unmistakableChars[randInt(unmistakableChars.length)]); return result.join(''); } } export const randomSecret = () => { if (webpackIsServer) { const crypto = require('crypto'); return crypto.randomBytes(15).toString('base64'); } else { throw new Error("No CSPRNG available on the client"); } } console.log(`Sample randomId: ${randomId()}`); console.log(`Sample randomSecret: ${randomSecret()}`);
import * as _ from 'underscore'; // Excludes 0O1lIUV const unmistakableChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTWXYZ23456789"; export const randomId = () => { if (webpackIsServer) { const crypto = require('crypto'); const bytes = crypto.randomBytes(17); const result = []; for (let byte of bytes) { // Discards part of each byte and has modulo bias. Doesn't matter in // this context. result.push(unmistakableChars[byte % unmistakableChars.length]); } return result.join(''); } else { const result = []; function randInt(max) { return Math.floor(Math.random() * max); } for (let i=0; i<17; i++) result.push(unmistakableChars[randInt(unmistakableChars.length)]); return result.join(''); } } export const randomSecret = () => { if (webpackIsServer) { const crypto = require('crypto'); return crypto.randomBytes(15).toString('base64'); } else { throw new Error("No CSPRNG available on the client"); } }
Remove some crashing debug console.logs
Remove some crashing debug console.logs
TypeScript
mit
Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2
--- +++ @@ -33,6 +33,3 @@ throw new Error("No CSPRNG available on the client"); } } - -console.log(`Sample randomId: ${randomId()}`); -console.log(`Sample randomSecret: ${randomSecret()}`);
0c4652394d1a42148a4e61552ec0633cfba13bd9
mehuge/mehuge-events.ts
mehuge/mehuge-events.ts
/// <reference path="../cu/cu.ts" /> module MehugeEvents { var subscribers: any = {}; var listener; export function sub(topic: string, handler: (...data: any[]) => void) { var subs = subscribers[topic] = subscribers[topic] || { listeners: [] }; subs.listeners.push({ listener: handler }); // first handler for any topic? Register event handler if (!listener) { cuAPI.OnEvent(listener = function (topic: string, ...data: any[]) { var listeners = subscribers[topic].listeners, parsedData; for (var i = 0; i < listeners.length; i++) { if (listeners[i].listener) { listeners[i].listener(event, data); } } }); } // first handler for this topic, ask client to send these events if (subs.handlers.length === 1) { cuAPI.Listen(topic); } } export function unsub(topic: string) { cuAPI.Ignore(topic); } export function pub(topic: string, ...data: any[]) { cuAPI.Fire(topic, data); } }
/// <reference path="../cu/cu.ts" /> module MehugeEvents { var subscribers: any = {}; var listener; export function sub(topic: string, handler: (...data: any[]) => void) { var subs = subscribers[topic] = subscribers[topic] || { listeners: [] }; subs.listeners.push({ listener: handler }); // first handler for any topic? Register event handler if (!listener) { cuAPI.OnEvent(listener = function (topic: string, ...data: any[]) { var listeners = subscribers[topic].listeners, parsedData; for (var i = 0; i < listeners.length; i++) { if (listeners[i].listener) { listeners[i].listener(topic, data); } } }); } // first handler for this topic, ask client to send these events if (subs.listeners.length === 1) { cuAPI.Listen(topic); } } export function unsub(topic: string) { cuAPI.Ignore(topic); } export function pub(topic: string, ...data: any[]) { cuAPI.Fire(topic, data); } }
Fix some typos that made things broken
Fix some typos that made things broken
TypeScript
mpl-2.0
Mehuge/cu-ui-legacy,Mehuge/cu-ui-legacy,Mehuge/cu-ui-legacy,Mehuge/cu-ui-legacy,Mehuge/cu-ui-legacy
--- +++ @@ -13,14 +13,14 @@ var listeners = subscribers[topic].listeners, parsedData; for (var i = 0; i < listeners.length; i++) { if (listeners[i].listener) { - listeners[i].listener(event, data); + listeners[i].listener(topic, data); } } }); } // first handler for this topic, ask client to send these events - if (subs.handlers.length === 1) { + if (subs.listeners.length === 1) { cuAPI.Listen(topic); } }
54e64cf64c03b35849035c2ba6952ae893960fd9
lib/resources/connections.ts
lib/resources/connections.ts
import * as debug from 'debug'; import { Client } from '../client'; import { BasiqPromise, ConnectionCreateOptions, ConnectionUpdateOptions } from '../interfaces'; import { Resource } from './resource'; const log = debug('basiq-api:resource:connection'); class Connection extends Resource { constructor(client: Client) { super(client); } create(options: ConnectionCreateOptions): BasiqPromise { return this.client .post('connections', options) .then(res => this.client.formatResponse(res)) ; } refresh(id: string): BasiqPromise { return this.client .post(`connections/${id}/refresh`) .then(res => this.client.formatResponse(res)) ; } retrieve(id: string): BasiqPromise { return this.client .get(`connections/${id}`) .then(res => this.client.formatResponse(res)) ; } update(id: string, options: ConnectionUpdateOptions): BasiqPromise { return this.client .put(`connections/${id}`, options) .then(res => this.client.formatResponse(res)) ; } delete(id: string): BasiqPromise { return this.client .delete(`connections/${id}`) .then(res => this.client.formatResponse(res)) ; } } export { Connection };
import * as debug from 'debug'; import { Client } from '../client'; import { BasiqPromise, ConnectionCreateOptions, ConnectionUpdateOptions } from '../interfaces'; import { Resource } from './resource'; const log = debug('basiq-api:resource:connection'); class Connection extends Resource { constructor(client: Client) { super(client); } create(options: ConnectionCreateOptions): BasiqPromise { return this.client .post('connections', options) .then(res => this.client.formatResponse(res)) ; } refresh(connectionId: string): BasiqPromise { return this.client .post(`connections/${connectionId}/refresh`) .then(res => this.client.formatResponse(res)) ; } retrieve(connectionId: string): BasiqPromise { return this.client .get(`connections/${connectionId}`) .then(res => this.client.formatResponse(res)) ; } update(connectionId: string, options: ConnectionUpdateOptions): BasiqPromise { return this.client .put(`connections/${connectionId}`, options) .then(res => this.client.formatResponse(res)) ; } delete(connectionId: string): BasiqPromise { return this.client .delete(`connections/${connectionId}`) .then(res => this.client.formatResponse(res)) ; } } export { Connection };
Rename id parameter to connectionId
Rename id parameter to connectionId
TypeScript
bsd-2-clause
FluentDevelopment/basiq-api
--- +++ @@ -19,30 +19,30 @@ ; } - refresh(id: string): BasiqPromise { + refresh(connectionId: string): BasiqPromise { return this.client - .post(`connections/${id}/refresh`) + .post(`connections/${connectionId}/refresh`) .then(res => this.client.formatResponse(res)) ; } - retrieve(id: string): BasiqPromise { + retrieve(connectionId: string): BasiqPromise { return this.client - .get(`connections/${id}`) + .get(`connections/${connectionId}`) .then(res => this.client.formatResponse(res)) ; } - update(id: string, options: ConnectionUpdateOptions): BasiqPromise { + update(connectionId: string, options: ConnectionUpdateOptions): BasiqPromise { return this.client - .put(`connections/${id}`, options) + .put(`connections/${connectionId}`, options) .then(res => this.client.formatResponse(res)) ; } - delete(id: string): BasiqPromise { + delete(connectionId: string): BasiqPromise { return this.client - .delete(`connections/${id}`) + .delete(`connections/${connectionId}`) .then(res => this.client.formatResponse(res)) ; }
5b1c9c51d81856fb508789cbad95086f2151a613
app/src/ui/create-branch/index.tsx
app/src/ui/create-branch/index.tsx
import * as React from 'react' import Repository from '../../models/repository' import { Dispatcher } from '../../lib/dispatcher' interface ICreateBranchProps { readonly repository: Repository readonly dispatcher: Dispatcher } interface ICreateBranchState { } export default class CreateBranch extends React.Component<ICreateBranchProps, ICreateBranchState> { public render() { return ( <div id='create-branch' className='panel'> <div className='header'>Create New Branch</div> <hr/> <label>Name <input type='text'/></label> <label>From <select> <option value='master'>master</option> </select> </label> <hr/> <button onClick={() => this.createBranch()}>Create Branch</button> </div> ) } private createBranch() { } }
import * as React from 'react' import Repository from '../../models/repository' import { Dispatcher } from '../../lib/dispatcher' // import { LocalGitOperations } from '../../lib/local-git-operations' interface ICreateBranchProps { readonly repository: Repository readonly dispatcher: Dispatcher } interface ICreateBranchState { readonly currentError: Error | null readonly proposedName: string | null } export default class CreateBranch extends React.Component<ICreateBranchProps, ICreateBranchState> { public constructor(props: ICreateBranchProps) { super(props) this.state = { currentError: null, proposedName: null, } } public render() { const proposedName = this.state.proposedName const disabled = !proposedName return ( <div id='create-branch' className='panel'> <div className='header'>Create New Branch</div> <hr/> <label>Name <input type='text' onChange={event => this.onChange(event)}/></label> <label>From <select> <option value='master'>master</option> </select> </label> <hr/> <button onClick={() => this.createBranch()} disabled={disabled}>Create Branch</button> </div> ) } private onChange(event: React.FormEvent<HTMLInputElement>) { const str = event.target.value this.setState({ currentError: this.state.currentError, proposedName: str, }) } private createBranch() { } }
Disable if there's no name yet.
Disable if there's no name yet.
TypeScript
mit
artivilla/desktop,BugTesterTest/desktops,hjobrien/desktop,gengjiawen/desktop,desktop/desktop,shiftkey/desktop,gengjiawen/desktop,gengjiawen/desktop,artivilla/desktop,BugTesterTest/desktops,hjobrien/desktop,shiftkey/desktop,say25/desktop,shiftkey/desktop,desktop/desktop,j-f1/forked-desktop,kactus-io/kactus,kactus-io/kactus,artivilla/desktop,j-f1/forked-desktop,j-f1/forked-desktop,hjobrien/desktop,shiftkey/desktop,BugTesterTest/desktops,gengjiawen/desktop,artivilla/desktop,desktop/desktop,hjobrien/desktop,j-f1/forked-desktop,say25/desktop,kactus-io/kactus,BugTesterTest/desktops,say25/desktop,desktop/desktop,kactus-io/kactus,say25/desktop
--- +++ @@ -2,6 +2,7 @@ import Repository from '../../models/repository' import { Dispatcher } from '../../lib/dispatcher' +// import { LocalGitOperations } from '../../lib/local-git-operations' interface ICreateBranchProps { readonly repository: Repository @@ -9,17 +10,29 @@ } interface ICreateBranchState { - + readonly currentError: Error | null + readonly proposedName: string | null } export default class CreateBranch extends React.Component<ICreateBranchProps, ICreateBranchState> { + public constructor(props: ICreateBranchProps) { + super(props) + + this.state = { + currentError: null, + proposedName: null, + } + } + public render() { + const proposedName = this.state.proposedName + const disabled = !proposedName return ( <div id='create-branch' className='panel'> <div className='header'>Create New Branch</div> <hr/> - <label>Name <input type='text'/></label> + <label>Name <input type='text' onChange={event => this.onChange(event)}/></label> <label>From <select> @@ -28,9 +41,17 @@ </label> <hr/> - <button onClick={() => this.createBranch()}>Create Branch</button> + <button onClick={() => this.createBranch()} disabled={disabled}>Create Branch</button> </div> ) + } + + private onChange(event: React.FormEvent<HTMLInputElement>) { + const str = event.target.value + this.setState({ + currentError: this.state.currentError, + proposedName: str, + }) } private createBranch() {
909e7e7d2ec3b21f0a0b4f2cb8f6a875550b6dc9
polygerrit-ui/app/styles/gr-modal-styles.ts
polygerrit-ui/app/styles/gr-modal-styles.ts
/** * @license * Copyright 2022 Google LLC * SPDX-License-Identifier: Apache-2.0 */ import {css} from 'lit'; export const modalStyles = css` dialog { padding: 0; border: 1px solid var(--border-color); border-radius: var(--border-radius); } dialog::backdrop { background-color: black; opacity: var(--modal-opacity, 0.6); } `;
/** * @license * Copyright 2022 Google LLC * SPDX-License-Identifier: Apache-2.0 */ import {css} from 'lit'; export const modalStyles = css` dialog { padding: 0; border: 1px solid var(--border-color); border-radius: var(--border-radius); background: var(--dialog-background-color); box-shadow: var(--elevation-level-5); } dialog::backdrop { background-color: black; opacity: var(--modal-opacity, 0.6); } `;
Add missing GrOverlay styles to GrModalStyles
Add missing GrOverlay styles to GrModalStyles Release-Notes: skip Google-bug-id: b/255524908 Change-Id: If284faacd218fc5a8caf7bfdb404c52730dd92bd
TypeScript
apache-2.0
GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit
--- +++ @@ -10,6 +10,8 @@ padding: 0; border: 1px solid var(--border-color); border-radius: var(--border-radius); + background: var(--dialog-background-color); + box-shadow: var(--elevation-level-5); } dialog::backdrop { background-color: black;
d398bbdcb0cac623a4a0a84603d719aade418470
packages/core/src/compileInBrowser.ts
packages/core/src/compileInBrowser.ts
import babelPlugin from "./babelPlugin"; import handleEvalScript from "./handleEvalScript"; import getBabelOptions, { getAndResetLocs } from "./getBabelOptions"; window["__fromJSEval"] = function(code) { function compile(code, url, done) { const babelResult = window["Babel"].transform( code, getBabelOptions(babelPlugin, {}, url) ); babelResult.locs = getAndResetLocs(); done(babelResult); } let returnValue; // handle eval script is sync because compile is sync! handleEvalScript(code, compile, evalScript => { returnValue = { evalScript, returnValue: eval(evalScript.instrumentedCode) }; }); return returnValue; };
import babelPlugin from "./babelPlugin"; import handleEvalScript from "./handleEvalScript"; import getBabelOptions, { getAndResetLocs } from "./getBabelOptions"; var Babel = window["Babel"]; delete window["__core-js_shared__"]; // Added by babel standalone, but breaks some lodash tests window["__fromJSEval"] = function(code) { function compile(code, url, done) { const babelResult = Babel.transform( code, getBabelOptions(babelPlugin, {}, url) ); babelResult.locs = getAndResetLocs(); done(babelResult); } let returnValue; // handle eval script is sync because compile is sync! handleEvalScript(code, compile, evalScript => { returnValue = { evalScript, returnValue: eval(evalScript.instrumentedCode) }; }); return returnValue; };
Reduce babel standalone side effects
Reduce babel standalone side effects
TypeScript
mit
mattzeunert/FromJS,mattzeunert/FromJS,mattzeunert/FromJS,mattzeunert/FromJS
--- +++ @@ -2,9 +2,12 @@ import handleEvalScript from "./handleEvalScript"; import getBabelOptions, { getAndResetLocs } from "./getBabelOptions"; +var Babel = window["Babel"]; +delete window["__core-js_shared__"]; // Added by babel standalone, but breaks some lodash tests + window["__fromJSEval"] = function(code) { function compile(code, url, done) { - const babelResult = window["Babel"].transform( + const babelResult = Babel.transform( code, getBabelOptions(babelPlugin, {}, url) );
49e60c2b64081638cf67d009ae6979ac04d1aacd
index.d.ts
index.d.ts
import FakeXMLHttpRequest from "fake-xml-http-request"; import { Params, QueryParams } from "route-recognizer"; type SetupCallback = (this: Server) => void; interface SetupConfig { forcePassthrough: boolean; } export type Config = SetupCallback | SetupConfig; export class Server { // HTTP request verbs public get: RequestHandler; public put: RequestHandler; public post: RequestHandler; public patch: RequestHandler; public delete: RequestHandler; public options: RequestHandler; public head: RequestHandler; constructor(setup?: SetupCallback); public shutdown(): void; } export type RequestHandler = ( urlExpression: string, response: ResponseHandler, async?: boolean | number ) => void; export type ResponseData = [number, { [k: string]: string }, string]; interface ExtraRequestData { params: Params; queryParams: QueryParams; } export type ResponseHandler = ( request: FakeXMLHttpRequest | ExtraRequestData ) => ResponseData | PromiseLike<ResponseData>; export default Server;
import FakeXMLHttpRequest from 'fake-xml-http-request'; import { Params, QueryParams } from 'route-recognizer'; type SetupCallback = (this: Server) => void; interface SetupConfig { forcePassthrough: boolean; } export type Config = SetupCallback | SetupConfig; export class Server { public passthrough: RequestHandler; constructor(config?: Config); // HTTP request verbs public get: RequestHandler; public put: RequestHandler; public post: RequestHandler; public patch: RequestHandler; public delete: RequestHandler; public options: RequestHandler; public head: RequestHandler; public shutdown(): void; } export type RequestHandler = ( urlExpression: string, response: ResponseHandler, asyncOrDelay?: boolean | number ) => void; export type ResponseData = [number, { [k: string]: string }, string]; interface ExtraRequestData { params: Params; queryParams: QueryParams; } export type ResponseHandler = ( request: FakeXMLHttpRequest | ExtraRequestData ) => ResponseData | PromiseLike<ResponseData>; export default Server;
Allow this.passthrough for repsonse param
[Type] Allow this.passthrough for repsonse param
TypeScript
mit
pretenderjs/pretender,trek/pretender,pretenderjs/pretender
--- +++ @@ -1,11 +1,15 @@ -import FakeXMLHttpRequest from "fake-xml-http-request"; -import { Params, QueryParams } from "route-recognizer"; +import FakeXMLHttpRequest from 'fake-xml-http-request'; +import { Params, QueryParams } from 'route-recognizer'; + type SetupCallback = (this: Server) => void; interface SetupConfig { forcePassthrough: boolean; } export type Config = SetupCallback | SetupConfig; export class Server { + public passthrough: RequestHandler; + + constructor(config?: Config); // HTTP request verbs public get: RequestHandler; public put: RequestHandler; @@ -14,7 +18,6 @@ public delete: RequestHandler; public options: RequestHandler; public head: RequestHandler; - constructor(setup?: SetupCallback); public shutdown(): void; } @@ -22,7 +25,7 @@ export type RequestHandler = ( urlExpression: string, response: ResponseHandler, - async?: boolean | number + asyncOrDelay?: boolean | number ) => void; export type ResponseData = [number, { [k: string]: string }, string];
4929cd85a148421ee6c506074c5bb07d3b8a4c3f
src/pages/story-list.ts
src/pages/story-list.ts
import { observable } from 'aurelia-framework'; import { activationStrategy } from 'aurelia-router'; import { HackerNewsApi, STORIES_PER_PAGE } from '../services/api'; export abstract class StoryList { stories: any[]; offset: number; @observable() currentPage: number; totalPages: number; readonly api: HackerNewsApi; private allStories: number[] = []; constructor(api: HackerNewsApi) { this.api = api; } abstract fetchIds(): Promise<number[]>; determineActivationStrategy(): string { // don't forcefully refresh the page, just invoke our activate method return activationStrategy.invokeLifecycle; } async activate(params: any): Promise<void> { window.scrollTo(0, 0); if (params.page === undefined || isNaN(params.page) || params.page < 1) { this.currentPage = 1; } else { this.currentPage = Number(params.page); } this.allStories = await this.fetchIds(); this.stories = await this.api.fetchItemsOnPage(this.allStories, this.currentPage); this.totalPages = Math.ceil(this.allStories.length / STORIES_PER_PAGE); } currentPageChanged(newValue: number, oldValue: number): void { if (newValue === oldValue) { return; } this.offset = STORIES_PER_PAGE * (newValue - 1); } }
import { observable } from 'aurelia-framework'; import { HackerNewsApi, STORIES_PER_PAGE } from '../services/api'; export abstract class StoryList { stories: any[]; offset: number; @observable() currentPage: number; totalPages: number; readonly api: HackerNewsApi; private allStories: number[] = []; constructor(api: HackerNewsApi) { this.api = api; } abstract fetchIds(): Promise<number[]>; determineActivationStrategy(): string { return 'replace'; } async activate(params: any): Promise<void> { window.scrollTo(0, 0); if (params.page === undefined || isNaN(params.page) || params.page < 1) { this.currentPage = 1; } else { this.currentPage = Number(params.page); } this.allStories = await this.fetchIds(); this.stories = await this.api.fetchItemsOnPage(this.allStories, this.currentPage); this.totalPages = Math.ceil(this.allStories.length / STORIES_PER_PAGE); } currentPageChanged(newValue: number, oldValue: number): void { if (newValue === oldValue) { return; } this.offset = STORIES_PER_PAGE * (newValue - 1); } }
Use replace activation strategy for StoryList view models
Use replace activation strategy for StoryList view models
TypeScript
isc
michaelbull/aurelia-hacker-news,michaelbull/aurelia-hacker-news,MikeBull94/aurelia-hacker-news,michaelbull/aurelia-hacker-news,MikeBull94/aurelia-hacker-news
--- +++ @@ -1,5 +1,4 @@ import { observable } from 'aurelia-framework'; -import { activationStrategy } from 'aurelia-router'; import { HackerNewsApi, STORIES_PER_PAGE @@ -22,8 +21,7 @@ abstract fetchIds(): Promise<number[]>; determineActivationStrategy(): string { - // don't forcefully refresh the page, just invoke our activate method - return activationStrategy.invokeLifecycle; + return 'replace'; } async activate(params: any): Promise<void> {
68f8bf68b63cb5a6a6ac3e6ae477e597e70bcf79
src/app/components/post-components/post-photo/post-photo.component.ts
src/app/components/post-components/post-photo/post-photo.component.ts
import { Component, Input } from '@angular/core'; import { Photo } from '../../../data.types'; import { FullscreenService } from '../../../shared/fullscreen.service'; @Component({ selector: 'post-photo', template: ` <img *ngFor="let photo of postPhotos" (click)="fullScreen($event)" src="{{photo.alt_sizes[0].url}}" sizes="(min-width: 64em) 34vw, (min-width: 48em) 73vw, 95vw" [srcset]="createSrcSet(photo)" [tumblrImage]="photo"> `, styleUrls: ['./post-photo.component.scss'] }) export class PostPhotoComponent { @Input('postPhotos') postPhotos: Photo[]; constructor(private fullscreenService: FullscreenService) { } private createSrcSet(photo: Photo): string { let srcset: string = ''; photo.alt_sizes.forEach(picture => { srcset += picture.url + ' ' + picture.width + 'w, '; }); return srcset.substring(0, srcset.lastIndexOf(', ')); } private fullScreen(event: any) { let elem = event.currentTarget; this.fullscreenService.requestFullscreen(elem); } }
import { Component, Input } from '@angular/core'; import { Photo } from '../../../data.types'; import { FullscreenService } from '../../../shared/fullscreen.service'; @Component({ selector: 'post-photo', template: ` <img *ngFor="let photo of postPhotos" (click)="fullScreen($event)" src="{{photo.original_size.url}}" sizes="(min-width: 64em) 34vw, (min-width: 48em) 73vw, 95vw" [srcset]="createSrcSet(photo)" [tumblrImage]="photo"> `, styleUrls: ['./post-photo.component.scss'] }) export class PostPhotoComponent { @Input('postPhotos') postPhotos: Photo[]; constructor(private fullscreenService: FullscreenService) { } private createSrcSet(photo: Photo): string { if (photo.alt_sizes.length === 0) { return photo.original_size.url; } let srcset: string = ''; photo.alt_sizes.forEach(picture => { srcset += picture.url + ' ' + picture.width + 'w, '; }); return srcset.substring(0, srcset.lastIndexOf(', ')); } private fullScreen(event: any) { let elem = event.currentTarget; this.fullscreenService.requestFullscreen(elem); } }
Fix for rare case where photo doesn't have alt sizes
Fix for rare case where photo doesn't have alt sizes
TypeScript
mit
zoehneto/tumblr-reader,zoehneto/tumblr-reader,zoehneto/tumblr-reader
--- +++ @@ -6,7 +6,7 @@ selector: 'post-photo', template: ` <img *ngFor="let photo of postPhotos" (click)="fullScreen($event)" - src="{{photo.alt_sizes[0].url}}" sizes="(min-width: 64em) 34vw, + src="{{photo.original_size.url}}" sizes="(min-width: 64em) 34vw, (min-width: 48em) 73vw, 95vw" [srcset]="createSrcSet(photo)" [tumblrImage]="photo"> `, @@ -18,6 +18,10 @@ } private createSrcSet(photo: Photo): string { + if (photo.alt_sizes.length === 0) { + return photo.original_size.url; + } + let srcset: string = ''; photo.alt_sizes.forEach(picture => { srcset += picture.url + ' ' + picture.width + 'w, ';
c94612aa3fc4016aa33e196f926e2b53ee148b1c
server/libs/api/user-functions.ts
server/libs/api/user-functions.ts
///<reference path="../../../typings/globals/mysql/index.d.ts"/> import * as mysql from 'mysql'; export class UserFunctions { /** * Callback for responding with user details query from the Database as a JSON object * * @callback sendResponse * @param {object} rows - Rows return from the query */ /** * Method get all user details from the database. * * @param {mysql.IConnection} connection - Connection object that has connection metadata * @param {sendResponse} callback - Response rows as JSON to the request * */ getAllUsers(connection: mysql.IConnection, callback) { let query = 'SELECT * FROM users'; connection.query(query, (err, rows) => { callback(rows); }); } }
///<reference path="../../../typings/globals/mysql/index.d.ts"/> import * as mysql from 'mysql'; export class UserFunctions { /** * Callback for responding with user details query from the Database as a JSON object * * @callback sendResponse * @param {object} rows - Rows return from the query */ /** * Method get all user details from the database. * * @param {mysql.IConnection} connection - Connection object that has connection metadata * @param {sendResponse} callback - Response rows as JSON to the request * */ getAllUsers(connection: mysql.IConnection, callback) { let query = 'SELECT * FROM users'; connection.query(query, (err, rows) => { callback(rows); }); } /** * Callback for responding with specified user details that query from the Database as a JSON object * * @callback sendResponse * @param {object} row - Row return from the query */ /** * Get speficied user details from the database. * * @param {number} userID - ID of the use to retrieve data * @param {mysql.IConnection} connection - Connection object that has connection metadata * @param {sendResponse} callback - Response rows as JSON to the request * */ getUser(userID: number, connection: mysql.IConnection, callback) { let query = 'SELECT * FROM users WHERE id=' + userID.toString(); connection.query(query, (err, row) => { callback(row); }) } /** * Callback for responding with specified user details that query from the Database as a JSON object * * @callback sendResponse * @param {object} row - Row return from the query */ /** * Get speficied user details from the database. * * @param {number} userID - ID of the use to retrieve data * @param {string} userName - New User name to be updated with * @param {mysql.IConnection} connection - Connection object that has connection metadata * @param {sendResponse} callback - Response rows as JSON to the request * */ updateUser(userID: number, userName:string, connection: mysql.IConnection, callback) { let query = 'UPDATE users SET userName= WHERE id=' + userID.toString(); connection.query(query, (err, row) => { callback(row); }) } }
Update user functions with following helpers - Get user by ID - Update user details
Update user functions with following helpers - Get user by ID - Update user details
TypeScript
mit
shavindraSN/examen,shavindraSN/examen,shavindraSN/examen
--- +++ @@ -16,11 +16,57 @@ * @param {mysql.IConnection} connection - Connection object that has connection metadata * @param {sendResponse} callback - Response rows as JSON to the request * - */ + */ getAllUsers(connection: mysql.IConnection, callback) { let query = 'SELECT * FROM users'; connection.query(query, (err, rows) => { callback(rows); }); } + + /** + * Callback for responding with specified user details that query from the Database as a JSON object + * + * @callback sendResponse + * @param {object} row - Row return from the query + */ + + /** + * Get speficied user details from the database. + * + * @param {number} userID - ID of the use to retrieve data + * @param {mysql.IConnection} connection - Connection object that has connection metadata + * @param {sendResponse} callback - Response rows as JSON to the request + * + */ + getUser(userID: number, connection: mysql.IConnection, callback) { + let query = 'SELECT * FROM users WHERE id=' + userID.toString(); + connection.query(query, (err, row) => { + callback(row); + }) + } + + /** + * Callback for responding with specified user details that query from the Database as a JSON object + * + * @callback sendResponse + * @param {object} row - Row return from the query + */ + + /** + * Get speficied user details from the database. + * + * @param {number} userID - ID of the use to retrieve data + * @param {string} userName - New User name to be updated with + * @param {mysql.IConnection} connection - Connection object that has connection metadata + * @param {sendResponse} callback - Response rows as JSON to the request + * + */ + + updateUser(userID: number, userName:string, connection: mysql.IConnection, callback) { + let query = 'UPDATE users SET userName= WHERE id=' + userID.toString(); + connection.query(query, (err, row) => { + callback(row); + }) + } }
c0576bda677c8838fd922453f568b7ddf6b6f84c
index.ts
index.ts
import * as express from 'express'; import * as graphqlHTTP from 'express-graphql'; import * as url from 'url'; import { SchemaBuilder } from './SchemaBuilder'; let ELASTIC_BASEURL = 'http://localhost:9200'; let argv = process.argv.slice(2) || []; let arg0 = argv[0] || ''; let _url = url.parse(arg0); if (_url.host) { ELASTIC_BASEURL = `${_url.protocol}//${_url.host}`; } const app = express(); (async function () { let builder = new SchemaBuilder(ELASTIC_BASEURL); app.use('/graphql', graphqlHTTP({ schema: await builder.build(), graphiql: true, })); console.log('Now browse to localhost:4000/graphql'); })().catch(e => console.log(e)); app.listen(4000, () => console.log('Server started'));
import * as express from 'express'; import * as graphqlHTTP from 'express-graphql'; import * as url from 'url'; import { SchemaBuilder } from './SchemaBuilder'; let ELASTIC_BASEURL = 'http://localhost:9200'; let PORT = 4000; let argv = process.argv.slice(2) || []; let arg0 = argv[0] || ''; let _url = url.parse(arg0); if (_url.host) { ELASTIC_BASEURL = `${_url.protocol}//${_url.host}`; } let arg1 = parseInt(argv[1] || '', 10); if (arg1 > 0) { PORT = arg1; } const app = express(); (async function() { let builder = new SchemaBuilder(ELASTIC_BASEURL); app.use('/graphql', graphqlHTTP({ schema: await builder.build(), graphiql: true, })); console.log('Now browse to http://localhost:${PORT}/graphql'); })().catch(e => console.log(e)); app.listen(PORT, () => console.log('Server started at ${PORT}'));
Make port configurable through commandline argument
Make port configurable through commandline argument
TypeScript
mit
nripendra/node-elasticsearch-graphql
--- +++ @@ -4,6 +4,7 @@ import { SchemaBuilder } from './SchemaBuilder'; let ELASTIC_BASEURL = 'http://localhost:9200'; +let PORT = 4000; let argv = process.argv.slice(2) || []; let arg0 = argv[0] || ''; @@ -12,9 +13,14 @@ ELASTIC_BASEURL = `${_url.protocol}//${_url.host}`; } +let arg1 = parseInt(argv[1] || '', 10); +if (arg1 > 0) { + PORT = arg1; +} + const app = express(); -(async function () { +(async function() { let builder = new SchemaBuilder(ELASTIC_BASEURL); @@ -22,7 +28,7 @@ schema: await builder.build(), graphiql: true, })); - console.log('Now browse to localhost:4000/graphql'); + console.log('Now browse to http://localhost:${PORT}/graphql'); })().catch(e => console.log(e)); -app.listen(4000, () => console.log('Server started')); +app.listen(PORT, () => console.log('Server started at ${PORT}'));
f1610692a8bbd86d90973307d3f55231acf92e61
src/types/runtime/gravity/FeaturedLink.ts
src/types/runtime/gravity/FeaturedLink.ts
import { Record, String, Static, Null, Boolean, Number, Array, Undefined, } from "runtypes" export const FeaturedLink = Record({ id: String, _id: String, href: String, title: String, subtitle: String, description: String, original_width: Number.Or(Null), original_height: Number.Or(Null), image_url: String.Or(Null), image_versions: Array(String), image_urls: Record({ small_rectangle: String.Or(Undefined), large_square: String.Or(Undefined), large_rectangle: String.Or(Undefined), medium_square: String.Or(Undefined), medium_rectangle: String.Or(Undefined), small_square: String.Or(Undefined), wide: String.Or(Undefined), }), display_on_desktop: Boolean, display_on_mobile: Boolean, display_on_martsy: Boolean, created_at: String, updated_at: String, }) export type FeaturedLink = Static<typeof FeaturedLink>
import { Record, String, Static, Null, Boolean, Number, Array, Undefined, } from "runtypes" export const FeaturedLink = Record({ id: String, _id: String, href: String.Or(Null), title: String.Or(Null), subtitle: String.Or(Null), description: String.Or(Null), original_width: Number.Or(Null), original_height: Number.Or(Null), image_url: String.Or(Null), image_versions: Array(String), image_urls: Record({ small_rectangle: String.Or(Undefined), large_square: String.Or(Undefined), large_rectangle: String.Or(Undefined), medium_square: String.Or(Undefined), medium_rectangle: String.Or(Undefined), small_square: String.Or(Undefined), wide: String.Or(Undefined), }), display_on_desktop: Boolean, display_on_mobile: Boolean, display_on_martsy: Boolean, created_at: String, updated_at: String, }) export type FeaturedLink = Static<typeof FeaturedLink>
Allow more fields to be nullable
Allow more fields to be nullable
TypeScript
mit
artsy/metaphysics,artsy/metaphysics,artsy/metaphysics
--- +++ @@ -12,10 +12,10 @@ export const FeaturedLink = Record({ id: String, _id: String, - href: String, - title: String, - subtitle: String, - description: String, + href: String.Or(Null), + title: String.Or(Null), + subtitle: String.Or(Null), + description: String.Or(Null), original_width: Number.Or(Null), original_height: Number.Or(Null), image_url: String.Or(Null),
ee2d63799cbd0890927353d000e923e7fef39d99
code-generation/config/isAllowedMixin.ts
code-generation/config/isAllowedMixin.ts
import {MixinViewModel} from "./../view-models"; export function isAllowedMixin(mixin: MixinViewModel) { switch (mixin.name) { case "ModifierableNode": case "NamedNode": case "PropertyNamedNode": case "DeclarationNamedNode": case "BindingNamedNode": case "HeritageClauseableNode": case "NamespaceChildableNode": case "OverloadableNode": case "TextInsertableNode": case "UnwrappableNode": return false; default: return true; } }
import {MixinViewModel} from "./../view-models"; export function isAllowedMixin(mixin: MixinViewModel) { switch (mixin.name) { case "ModifierableNode": case "NamedNode": case "PropertyNamedNode": case "DeclarationNamedNode": case "BindingNamedNode": case "HeritageClauseableNode": case "NamespaceChildableNode": case "OverloadableNode": case "TextInsertableNode": case "UnwrappableNode": case "ChildOrderableNode": return false; default: return true; } }
Update code verification to ignore ChildOrderableNode.
Update code verification to ignore ChildOrderableNode.
TypeScript
mit
dsherret/ts-simple-ast
--- +++ @@ -12,6 +12,7 @@ case "OverloadableNode": case "TextInsertableNode": case "UnwrappableNode": + case "ChildOrderableNode": return false; default: return true;
55aefeadb0cef8609b499eb998558f03fad83225
app/core/map.service.ts
app/core/map.service.ts
import { Injectable } from '@angular/core'; @Injectable() export class MapService { constructor() { } }
import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { Map, MapType } from './map'; @Injectable() export class MapService { constructor(private http: Http) { } addMap( title: string = "", height: number, width: number, mapType: MapType, creatorId: number, graphics: string = "" ) { // TODO: compute hash, id, date and return an Observable<Map> } map(id: number) { } maps() { } }
Prepare a MapService with functions signatures
Prepare a MapService with functions signatures
TypeScript
mit
ABAPlan/abaplan-core,ABAPlan/abaplan-core,ABAPlan/abaplan-core
--- +++ @@ -1,9 +1,33 @@ import { Injectable } from '@angular/core'; +import { Http, Response } from '@angular/http'; +import { Observable } from 'rxjs/Observable'; + +import { Map, MapType } from './map'; @Injectable() export class MapService { - constructor() { + constructor(private http: Http) { } + addMap( + title: string = "", + height: number, + width: number, + mapType: MapType, + creatorId: number, + graphics: string = "" + ) { + // TODO: compute hash, id, date and return an Observable<Map> + } + + map(id: number) { + + } + + maps() { + + } + + }
55225bd5cd2f1de36f2c9b6488cd66f5e3243a96
app/src/common/utils.ts
app/src/common/utils.ts
// Copyright (c) 2016 Vadim Macagon // MIT License, see LICENSE file for full terms. // Various Utility Functions /** * Creates a new object that contains all the properties of the [[source]] object except the ones * given in [[propsToOmit]]. Note that this function only takes into account own properties of the * source object. * * @param source The object from which properties should be copied. * @param propsToOmit The names of properties that should not be copied from the source object. * @return A new object that contains the properties that were copied from the source object. */ export function omitOwnProps(source: any, propsToOmit: string[]): any { const result: any = {}; Object.getOwnPropertyNames(source).forEach(propertyName => { if (!(propertyName in propsToOmit)) { result[propertyName] = source[propertyName]; } }); return result; }
// Copyright (c) 2016 Vadim Macagon // MIT License, see LICENSE file for full terms. // Various Utility Functions /** * Creates a new object that contains all the properties of the [[source]] object except the ones * given in [[propsToOmit]]. Note that this function only takes into account own properties of the * source object. * * @param source The object from which properties should be copied. * @param propsToOmit The names of properties that should not be copied from the source object. * @return A new object that contains the properties that were copied from the source object. */ export function omitOwnProps(source: any, propsToOmit: string[]): any { const result: any = {}; Object.getOwnPropertyNames(source).forEach(propertyName => { if (propsToOmit.indexOf(propertyName) < 0) { result[propertyName] = source[propertyName]; } }); return result; }
Fix omitOwnProps() to actually work as documented
Fix omitOwnProps() to actually work as documented This is a perfect example of why one should write tests!
TypeScript
mit
debugworkbench/hydragon,debugworkbench/hydragon,debugworkbench/hydragon
--- +++ @@ -15,7 +15,7 @@ export function omitOwnProps(source: any, propsToOmit: string[]): any { const result: any = {}; Object.getOwnPropertyNames(source).forEach(propertyName => { - if (!(propertyName in propsToOmit)) { + if (propsToOmit.indexOf(propertyName) < 0) { result[propertyName] = source[propertyName]; } });
23ea12ac44f2c2f72e44d4fc8705c65980634e8b
src/homebridge.ts
src/homebridge.ts
import "hap-nodejs" export interface Homebridge { hap: HAPNodeJS.HAPNodeJS log: Logger registerAccessory( pluginName: string, accessoryName: string, constructor: AccessoryConstructor ): void } export interface Logger { debug: (...message: string[]) => void info: (...message: string[]) => void warn: (...message: string[]) => void error: (...message: string[]) => void } export interface Accessory { getServices(): HAPNodeJS.Service[] } export interface AccessoryConstructor { new (log: Logger, config: any): Accessory } export default Homebridge
import "hap-nodejs" export interface Homebridge { hap: HAPNodeJS.HAPNodeJS log: Logger registerAccessory( pluginName: string, accessoryName: string, constructor: AccessoryConstructor ): void } export interface Logger { debug: (...message: string[]) => void info: (...message: string[]) => void warn: (...message: string[]) => void error: (...message: string[]) => void } export interface Accessory { getServices(): HAPNodeJS.Service[] } export type AccessoryConstructor = new (log: Logger, config: any) => Accessory export default Homebridge
Update style to conform with new TSLint rule
Update style to conform with new TSLint rule
TypeScript
mit
JosephDuffy/homebridge-pc-volume,JosephDuffy/homebridge-pc-volume,JosephDuffy/homebridge-pc-volume
--- +++ @@ -21,8 +21,6 @@ getServices(): HAPNodeJS.Service[] } -export interface AccessoryConstructor { - new (log: Logger, config: any): Accessory -} +export type AccessoryConstructor = new (log: Logger, config: any) => Accessory export default Homebridge
038d267980b94e110767bdc820454a0a346ba4f7
ui/src/shared/components/SourceIndicator.tsx
ui/src/shared/components/SourceIndicator.tsx
import React, {SFC} from 'react' import PropTypes from 'prop-types' import _ from 'lodash' import uuid from 'uuid' import ReactTooltip from 'react-tooltip' import {Source} from 'src/types' interface Props { sourceOverride?: Source } const SourceIndicator: SFC<Props> = ( {sourceOverride}, {source: {name, url}} ) => { const sourceName: string = _.get(sourceOverride, 'name', name) const sourceUrl: string = _.get(sourceOverride, 'url', url) const sourceNameTooltip: string = `<h1>Connected to Source:</h1><p><code>${sourceName} @ ${sourceUrl}</code></p>` const uuidTooltip: string = uuid.v4() return sourceName ? ( <div className="source-indicator" data-for={uuidTooltip} data-tip={sourceNameTooltip} > <span className="icon server2" /> <ReactTooltip id={uuidTooltip} effect="solid" html={true} place="left" class="influx-tooltip" /> </div> ) : null } const {shape} = PropTypes SourceIndicator.contextTypes = { source: shape({}), } export default SourceIndicator
import React, {SFC} from 'react' import PropTypes from 'prop-types' import _ from 'lodash' import uuid from 'uuid' import ReactTooltip from 'react-tooltip' import {Source} from 'src/types' interface Props { sourceOverride?: Source } const SourceIndicator: SFC<Props> = ( {sourceOverride}, {source: {name, url}} ) => { const sourceName: string = _.get(sourceOverride, 'name', name) const sourceUrl: string = _.get(sourceOverride, 'url', url) const sourceNameTooltip: string = `<h1>Connected to Source:</h1><p><code>${sourceName} @ ${sourceUrl}</code></p>` const uuidTooltip: string = uuid.v4() return sourceName ? ( <div className="source-indicator" data-for={uuidTooltip} data-tip={sourceNameTooltip} > <span className="icon disks" /> <ReactTooltip id={uuidTooltip} effect="solid" html={true} place="left" class="influx-tooltip" /> </div> ) : null } const {shape} = PropTypes SourceIndicator.contextTypes = { source: shape({}), } export default SourceIndicator
Change source indicator to look more "databasey"
Change source indicator to look more "databasey"
TypeScript
mit
influxdata/influxdb,nooproblem/influxdb,influxdb/influxdb,nooproblem/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdb/influxdb,influxdata/influxdb,nooproblem/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,li-ang/influxdb
--- +++ @@ -26,7 +26,7 @@ data-for={uuidTooltip} data-tip={sourceNameTooltip} > - <span className="icon server2" /> + <span className="icon disks" /> <ReactTooltip id={uuidTooltip} effect="solid"
3b92c1c949819b4b31ef1e4fc851555da27e6c82
server/src/services/documentSymbolService.ts
server/src/services/documentSymbolService.ts
import { Analysis } from '../analysis'; import { SymbolInformation, CompletionItemKind, Location } from 'vscode-languageserver'; export function buildDocumentSymbols(uri: string, analysis: Analysis): SymbolInformation[] { const symbols: SymbolInformation[] = []; for (const symbol of analysis.symbols.filter(f => f.isGlobalScope)) { // Populate the document's functions: if (symbol.kind === 'Function') { if (symbol.name === null) { continue; } symbols.push({ name: symbol.name, containerName: symbol.container || undefined, kind: CompletionItemKind.Function, location: Location.create(uri, symbol.range) }); } // Populate the document's variables: else if (symbol.kind === 'Variable') { if (symbol.name === null) { continue; } symbols.push({ name: symbol.name, kind: CompletionItemKind.Variable, location: Location.create(uri, symbol.range) }); } } return symbols; }
import { Analysis } from '../analysis'; import { SymbolInformation, Location, SymbolKind } from 'vscode-languageserver'; export function buildDocumentSymbols(uri: string, analysis: Analysis): SymbolInformation[] { const symbols: SymbolInformation[] = []; for (const symbol of analysis.symbols.filter(sym => sym.isGlobalScope)) { // Populate the document's functions: if (symbol.kind === 'Function') { if (symbol.name === null) { continue; } symbols.push({ name: symbol.name, containerName: symbol.container || undefined, kind: SymbolKind.Function, location: Location.create(uri, symbol.range) }); } // Populate the document's variables: else if (symbol.kind === 'Variable') { if (symbol.name === null) { continue; } symbols.push({ name: symbol.name, kind: SymbolKind.Variable, location: Location.create(uri, symbol.range) }); } } return symbols; }
Fix improper symbol kinds being returned by DocumentSymbolService
Fix improper symbol kinds being returned by DocumentSymbolService
TypeScript
mit
trixnz/vscode-lua,trixnz/vscode-lua
--- +++ @@ -1,10 +1,10 @@ import { Analysis } from '../analysis'; -import { SymbolInformation, CompletionItemKind, Location } from 'vscode-languageserver'; +import { SymbolInformation, Location, SymbolKind } from 'vscode-languageserver'; export function buildDocumentSymbols(uri: string, analysis: Analysis): SymbolInformation[] { const symbols: SymbolInformation[] = []; - for (const symbol of analysis.symbols.filter(f => f.isGlobalScope)) { + for (const symbol of analysis.symbols.filter(sym => sym.isGlobalScope)) { // Populate the document's functions: if (symbol.kind === 'Function') { if (symbol.name === null) { continue; } @@ -12,7 +12,7 @@ symbols.push({ name: symbol.name, containerName: symbol.container || undefined, - kind: CompletionItemKind.Function, + kind: SymbolKind.Function, location: Location.create(uri, symbol.range) }); } @@ -22,7 +22,7 @@ symbols.push({ name: symbol.name, - kind: CompletionItemKind.Variable, + kind: SymbolKind.Variable, location: Location.create(uri, symbol.range) }); }
b396ede44be06f5d8361b4e8266e64d9a9b4b226
src/task-group.ts
src/task-group.ts
import Wipable from './wipable'; export default class TaskGroup extends Wipable { taskGroup: Element; constructor(taskGroup: Element) { super(); this.taskGroup = taskGroup; } // header.classList.contains("bar-row") title(): string { const nameButtons = this.taskGroup.getElementsByClassName('PotColumnName-nameButton'); const headerButton = nameButtons[0]; const content = headerButton.textContent; if (content == null) { throw new Error(`Could not find text under ${headerButton}`); } return content; } children(): Element[] { const projectClassName = 'ProjectSpreadsheetGridRow-dropTargetRow'; console.debug({ taskGroup: this.taskGroup }); let tasks = Array.from(this.taskGroup.getElementsByClassName(projectClassName)); if (tasks.length === 0) { const myTasksClassName = 'MyTasksSpreadsheetGridRow-dropTargetRow'; tasks = Array.from(this.taskGroup.getElementsByClassName(myTasksClassName)); } return tasks; } elementsToMark() { const children = this.children(); console.debug('children:', children); return children.flatMap((child: Element) => Array.from(child.getElementsByClassName('SpreadsheetGridTaskNameAndDetailsCell-rowNumber'))); } }
import Wipable from './wipable'; export default class TaskGroup extends Wipable { taskGroup: Element; constructor(taskGroup: Element) { super(); this.taskGroup = taskGroup; } // header.classList.contains("bar-row") title(): string { const nameButtons = this.taskGroup.getElementsByClassName('PotColumnName-nameButton'); const headerButton = nameButtons[0]; const content = headerButton.textContent; if (content == null) { throw new Error(`Could not find text under ${headerButton}`); } return content; } children(): Element[] { const projectClassName = 'ProjectSpreadsheetGridRow-dropTargetRow'; console.debug({ taskGroup: this.taskGroup }); let tasks = Array.from(this.taskGroup.getElementsByClassName(projectClassName)); if (tasks.length === 0) { const myTasksClassName = 'MyTasksSpreadsheetGridRow-dropTargetRow'; tasks = Array.from(this.taskGroup.getElementsByClassName(myTasksClassName)); } return tasks; } elementsToMark() { const children = this.children(); console.debug('children:', children); return children.flatMap((child: Element) => Array.from(child.getElementsByClassName('SpreadsheetGridTaskNameAndDetailsCellGroup-rowNumber'))); } }
Adjust to CSS change on asana.com
Adjust to CSS change on asana.com
TypeScript
mit
apiology/wip-limiter,apiology/wip-limiter,apiology/wip-limiter
--- +++ @@ -33,6 +33,6 @@ elementsToMark() { const children = this.children(); console.debug('children:', children); - return children.flatMap((child: Element) => Array.from(child.getElementsByClassName('SpreadsheetGridTaskNameAndDetailsCell-rowNumber'))); + return children.flatMap((child: Element) => Array.from(child.getElementsByClassName('SpreadsheetGridTaskNameAndDetailsCellGroup-rowNumber'))); } }
0c9b5540a1eae38322a26b396a7f06a6f076f9cf
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/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;
import * as React from 'react'; import { Button, Stack, TextContainer } from '@shopify/polaris'; import { Tooltip } from '@blueprintjs/core'; import { TOpticonData } 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 = (data: TOpticonData) => { const { attrs: { pay, comm, fair, fast }, reviews, tos_flags } = data; return ( <Stack vertical> <TextContainer> Pay: {pay}. Comm: {comm}. Fair: {fair}. Fast: {fast}. </TextContainer> <TextContainer>Calculated from {reviews} reviews.</TextContainer> <TextContainer>{tos_flags} reported TOS violations.</TextContainer> </Stack> ); }; public render() { const { requesterId, turkopticon } = this.props; return turkopticon ? ( <Tooltip content={TOpticonButton.generateTooltipContent(turkopticon)}> <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;
Add number of reviews and TOS violations to TO tooltip.
Add number of reviews and TOS violations to TO tooltip.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -1,7 +1,7 @@ import * as React from 'react'; -import { Button } from '@shopify/polaris'; +import { Button, Stack, TextContainer } from '@shopify/polaris'; import { Tooltip } from '@blueprintjs/core'; -import { TOpticonData, RequesterScores } from '../../types'; +import { TOpticonData } from '../../types'; import { turkopticonBaseUrl } from '../../constants/urls'; export interface Props { @@ -10,19 +10,25 @@ } class TOpticonButton extends React.PureComponent<Props, never> { - static generateTooltipContent = (scores: RequesterScores) => - `Pay: ${scores.pay}. - Comm: ${scores.comm}. - Fair: ${scores.fair}. - Fast: ${scores.fast}.`; + static generateTooltipContent = (data: TOpticonData) => { + const { attrs: { pay, comm, fair, fast }, reviews, tos_flags } = data; + + return ( + <Stack vertical> + <TextContainer> + Pay: {pay}. Comm: {comm}. Fair: {fair}. Fast: {fast}. + </TextContainer> + <TextContainer>Calculated from {reviews} reviews.</TextContainer> + <TextContainer>{tos_flags} reported TOS violations.</TextContainer> + </Stack> + ); + }; public render() { const { requesterId, turkopticon } = this.props; return turkopticon ? ( - <Tooltip - content={TOpticonButton.generateTooltipContent(turkopticon.attrs)} - > + <Tooltip content={TOpticonButton.generateTooltipContent(turkopticon)}> <Button plain external url={turkopticonBaseUrl + requesterId}> T.O. Page </Button>
ccc844c33220a9b009f067706f3bf0b3b5de045a
src/formatters/index.ts
src/formatters/index.ts
/** * @license * Copyright 2013 Palantir Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export * from "./jsonFormatter"; export * from "./pmdFormatter"; export * from "./proseFormatter"; export * from "./verboseFormatter";
/** * @license * Copyright 2013 Palantir Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export { Formatter as JsonFormatter } from "./jsonFormatter"; export { Formatter as PmdFormatter } from "./pmdFormatter"; export { Formatter as ProseFormatter } from "./proseFormatter"; export { Formatter as VerboseFormatter } from "./verboseFormatter";
Use explicit exports for formatters.
Use explicit exports for formatters.
TypeScript
apache-2.0
weswigham/tslint,andy-hanson/tslint,RyanCavanaugh/tslint,mprobst/tslint,palantir/tslint,weswigham/tslint,berickson1/tslint,nchen63/tslint,RyanCavanaugh/tslint,IllusionMH/tslint,andy-ms/tslint,bolatovumar/tslint,Pajn/tslint,nchen63/tslint,andy-ms/tslint,RyanCavanaugh/tslint,JoshuaKGoldberg/tslint,ScottSWu/tslint,YuichiNukiyama/tslint,bolatovumar/tslint,weswigham/tslint,JoshuaKGoldberg/tslint,palantir/tslint,Pajn/tslint,berickson1/tslint,berickson1/tslint,YuichiNukiyama/tslint,andy-hanson/tslint,ScottSWu/tslint,nchen63/tslint,andy-hanson/tslint,IllusionMH/tslint,bolatovumar/tslint,IllusionMH/tslint,ScottSWu/tslint,mprobst/tslint,JoshuaKGoldberg/tslint,andy-ms/tslint,YuichiNukiyama/tslint,mprobst/tslint,Pajn/tslint,palantir/tslint
--- +++ @@ -15,7 +15,7 @@ * limitations under the License. */ -export * from "./jsonFormatter"; -export * from "./pmdFormatter"; -export * from "./proseFormatter"; -export * from "./verboseFormatter"; +export { Formatter as JsonFormatter } from "./jsonFormatter"; +export { Formatter as PmdFormatter } from "./pmdFormatter"; +export { Formatter as ProseFormatter } from "./proseFormatter"; +export { Formatter as VerboseFormatter } from "./verboseFormatter";
312a582bab061f1af84c281c8585d5b550110d40
ui/src/components/Footer.tsx
ui/src/components/Footer.tsx
import React, {FunctionComponent} from 'react' export const Footer: FunctionComponent = () => { return ( <div id="footer"> <hr /> Lovingly crafted by{' '} <a href="http://github.com/coddingtonbear">Adam Coddington</a> and others. See our <a href="/privacy-policy">Privacy Policy</a> and{' '} <a href="/terms-of-service">Terms of Service</a>. <br /> Questions? Ask on{' '} <a href="https://gitter.im/coddingtonbear/inthe.am">Gitter</a>. <a href="http://github.com/coddingtonbear/inthe.am"> Contribute to this project on Github </a> . </div> ) } export default Footer
import React, {FunctionComponent} from 'react' import {Link} from 'react-router-dom' export const Footer: FunctionComponent = () => { return ( <div id="footer"> <hr /> Lovingly crafted by{' '} <a href="http://github.com/coddingtonbear">Adam Coddington</a> and others. See our <Link to="/privacy-policy">Privacy Policy</Link> and{' '} <Link to="/terms-of-service">Terms of Service</Link>. <br /> Questions? Ask on{' '} <a href="https://gitter.im/coddingtonbear/inthe.am">Gitter</a>. <a href="http://github.com/coddingtonbear/inthe.am"> Contribute to this project on Github </a> . </div> ) } export default Footer
Use in-page linking to get to TOS and PP.
Use in-page linking to get to TOS and PP.
TypeScript
agpl-3.0
coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am
--- +++ @@ -1,4 +1,5 @@ import React, {FunctionComponent} from 'react' +import {Link} from 'react-router-dom' export const Footer: FunctionComponent = () => { return ( @@ -6,8 +7,8 @@ <hr /> Lovingly crafted by{' '} <a href="http://github.com/coddingtonbear">Adam Coddington</a> and others. - See our <a href="/privacy-policy">Privacy Policy</a> and{' '} - <a href="/terms-of-service">Terms of Service</a>. + See our <Link to="/privacy-policy">Privacy Policy</Link> and{' '} + <Link to="/terms-of-service">Terms of Service</Link>. <br /> Questions? Ask on{' '} <a href="https://gitter.im/coddingtonbear/inthe.am">Gitter</a>.
7e2611109c0e32f10e750a8bed7988fedd5084ac
src/slurm/EditDialog.tsx
src/slurm/EditDialog.tsx
import { translate } from '@waldur/i18n'; import { createNameField, createDescriptionField, } from '@waldur/resource/actions/base'; import { UpdateResourceDialog } from '@waldur/resource/actions/UpdateResourceDialog'; import { updateAllocation } from './api'; export const EditDialog = ({ resolve: { resource } }) => { return ( <UpdateResourceDialog fields={[createNameField(), createDescriptionField()]} resource={resource} initialValues={{ name: resource.name, description: resource.description, }} updateResource={updateAllocation} verboseName={translate('SLURM allocation')} /> ); };
import { translate } from '@waldur/i18n'; import { createNameField, createDescriptionField, } from '@waldur/resource/actions/base'; import { UpdateResourceDialog } from '@waldur/resource/actions/UpdateResourceDialog'; import { updateAllocation } from './api'; const getFields = () => [ createNameField(), createDescriptionField(), { name: 'cpu_limit', type: 'integer', required: true, label: translate('CPU limit'), }, { name: 'gpu_limit', type: 'integer', required: true, label: translate('GPU limit'), }, { name: 'ram_limit', type: 'integer', required: true, label: translate('RAM limit'), }, ]; export const EditDialog = ({ resolve: { resource } }) => { return ( <UpdateResourceDialog fields={getFields()} resource={resource} initialValues={{ name: resource.name, description: resource.description, cpu_limit: resource.cpu_limit, gpu_limit: resource.gpu_limit, ram_limit: resource.ram_limit, }} updateResource={updateAllocation} verboseName={translate('SLURM allocation')} /> ); };
Allow to update limits of SLURM allocation.
Allow to update limits of SLURM allocation.
TypeScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -7,14 +7,40 @@ import { updateAllocation } from './api'; +const getFields = () => [ + createNameField(), + createDescriptionField(), + { + name: 'cpu_limit', + type: 'integer', + required: true, + label: translate('CPU limit'), + }, + { + name: 'gpu_limit', + type: 'integer', + required: true, + label: translate('GPU limit'), + }, + { + name: 'ram_limit', + type: 'integer', + required: true, + label: translate('RAM limit'), + }, +]; + export const EditDialog = ({ resolve: { resource } }) => { return ( <UpdateResourceDialog - fields={[createNameField(), createDescriptionField()]} + fields={getFields()} resource={resource} initialValues={{ name: resource.name, description: resource.description, + cpu_limit: resource.cpu_limit, + gpu_limit: resource.gpu_limit, + ram_limit: resource.ram_limit, }} updateResource={updateAllocation} verboseName={translate('SLURM allocation')}
13e88a83d57a8bb742cf2e89e5916b588027a3e4
src/config/client-config.ts
src/config/client-config.ts
export const AUTH0_APPKEY = 'CoDxjf3YK5wB9y14G0Ee9oXlk03zFuUF' export const AUTH0_DOMAIN = 'odbrian.eu.auth0.com' export const AUTH0_LOCKOPTIONS = { allowedConnections: ['google-oauth2'], allowForgotPassword: false, allowSignUp: false, closable: false, auth: { connectionScopes: { 'google-oauth2': ['https://picasaweb.google.com/data/'] }, params: { scope: 'openid profile photos' // audience: 'https://API_ID HERE' } // responseType: 'token' }, languageDictionary: { title: 'Sign into Google' } }
export const AUTH0_APPKEY = 'CoDxjf3YK5wB9y14G0Ee9oXlk03zFuUF' export const AUTH0_DOMAIN = 'odbrian.eu.auth0.com' export const AUTH0_LOCKOPTIONS = { allowedConnections: ['google-oauth2'], allowForgotPassword: false, allowSignUp: false, closable: false, auth: { connectionScopes: { 'google-oauth2': ['https://picasaweb.google.com/data/'] }, params: { scope: 'openid profile photos', audience: 'https://brianAPI' }, responseType: 'id_token token' }, languageDictionary: { title: 'Sign into Google' } } export const API_ID = `https://brianAPI`
Set client config for API calls
Set client config for API calls
TypeScript
mit
OpenDirective/brian,OpenDirective/brian,OpenDirective/brian
--- +++ @@ -10,12 +10,13 @@ 'google-oauth2': ['https://picasaweb.google.com/data/'] }, params: { - scope: 'openid profile photos' - // audience: 'https://API_ID HERE' - } - // responseType: 'token' + scope: 'openid profile photos', + audience: 'https://brianAPI' + }, + responseType: 'id_token token' }, languageDictionary: { title: 'Sign into Google' } } +export const API_ID = `https://brianAPI`
907f3a04d5af56ca9df8460b8aa7beb5a2b4b2f8
lib/alexa/alexa-context.ts
lib/alexa/alexa-context.ts
import {AudioPlayer} from "./audio-player"; const uuid = require("node-uuid"); export class AlexaContext { private _applicationID: string; private _userID: string; private _audioPlayer: AudioPlayer; public constructor(public skillURL: string, audioPlayer: AudioPlayer, applicationID?: string) { this._applicationID = applicationID; this._audioPlayer = audioPlayer; } public applicationID(): string { // Generate an application ID if it is not set if (this._applicationID === undefined || this._applicationID === null) { this._applicationID = "amzn1.echo-sdk-ams.app." + uuid.v4(); } return this._applicationID; } public userID(): string { return this._userID; } public audioPlayer(): AudioPlayer { return this._audioPlayer; } public audioPlayerEnabled(): boolean { return this._audioPlayer !== null; } }
import {AudioPlayer} from "./audio-player"; const uuid = require("node-uuid"); export class AlexaContext { private _applicationID: string; private _userID: string; private _audioPlayer: AudioPlayer; public constructor(public skillURL: string, audioPlayer: AudioPlayer, applicationID?: string) { this._applicationID = applicationID; this._audioPlayer = audioPlayer; } public applicationID(): string { // Generate an application ID if it is not set if (this._applicationID === undefined || this._applicationID === null) { this._applicationID = "amzn1.echo-sdk-ams.app." + uuid.v4(); } return this._applicationID; } public userID(): string { if (this._userID === undefined || this._userID === null) { this._userID = "amzn1.ask.account." + uuid.v4(); } return this._userID; } public audioPlayer(): AudioPlayer { return this._audioPlayer; } public audioPlayerEnabled(): boolean { return this._audioPlayer !== null; } }
Make sure to initialize userID
Make sure to initialize userID
TypeScript
apache-2.0
bespoken/bst,bespoken/bst
--- +++ @@ -21,6 +21,9 @@ public userID(): string { + if (this._userID === undefined || this._userID === null) { + this._userID = "amzn1.ask.account." + uuid.v4(); + } return this._userID; }
5660399d1daadffebf7c40df7d7648c39758a39a
src/Separator/index.tsx
src/Separator/index.tsx
import * as React from "react"; import * as PropTypes from "prop-types"; export interface DataProps { direction?: "row" | "column"; disabled?: boolean; } export interface SeparatorProps extends DataProps, React.HTMLAttributes<HTMLDivElement> {} export class Separator extends React.Component<SeparatorProps> { static defaultProps: SeparatorProps = { direction: "row" }; static contextTypes = { theme: PropTypes.object }; context: { theme: ReactUWP.ThemeType }; render() { const { direction, style, className, ...attributes } = this.props; const isColumn = direction === "column"; const { theme } = this.context; const styleClasses = theme.prepareStyle({ style: theme.prefixStyle({ display: "inline-block", flex: "0 0 auto", width: isColumn ? 1 : "100%", height: isColumn ? "100%" : 1, background: theme.baseLow, margin: "0 auto", ...style }), className: "separator", extendsClassName: className }); return ( <span {...attributes} {...styleClasses} /> ); } } export default Separator;
import * as React from "react"; import * as PropTypes from "prop-types"; export interface DataProps { direction?: "row" | "column"; disabled?: boolean; } export interface SeparatorProps extends DataProps, React.HTMLAttributes<HTMLDivElement> {} export class Separator extends React.Component<SeparatorProps> { static defaultProps: SeparatorProps = { direction: "row" }; static contextTypes = { theme: PropTypes.object }; context: { theme: ReactUWP.ThemeType }; render() { const { direction, style, className, ...attributes } = this.props; const isColumn = direction === "column"; const { theme } = this.context; const styleClasses = theme.prepareStyle({ style: theme.prefixStyle({ display: isColumn ? "inline-block" : "block", flex: "0 0 auto", width: isColumn ? 1 : "100%", height: isColumn ? "100%" : 1, background: theme.baseLow, margin: "0 auto", ...style }), className: "separator", extendsClassName: className }); return ( <span {...attributes} {...styleClasses} /> ); } } export default Separator;
Update Separator row mode style
feat: Update Separator row mode style
TypeScript
mit
myxvisual/react-uwp,myxvisual/react-uwp
--- +++ @@ -27,7 +27,7 @@ const styleClasses = theme.prepareStyle({ style: theme.prefixStyle({ - display: "inline-block", + display: isColumn ? "inline-block" : "block", flex: "0 0 auto", width: isColumn ? 1 : "100%", height: isColumn ? "100%" : 1,
44f9ba9843ff0cd9e93031abee329bab31c5d91a
CeraonUI/src/Store/Reducers/CeraonReducer.ts
CeraonUI/src/Store/Reducers/CeraonReducer.ts
import CeraonState from '../../State/CeraonState'; import CeraonAction from '../../Actions/CeraonAction'; export default function ceraonReducer(state: CeraonState, action: CeraonAction) : CeraonState { return state; }
import CeraonState from '../../State/CeraonState'; import CeraonAction from '../../Actions/CeraonAction'; import CeraonActionType from '../../Actions/CeraonActionType'; import CeraonPage from '../../State/CeraonPage'; export default function ceraonReducer(state: CeraonState, action: CeraonAction) : CeraonState { if (action.type == CeraonActionType.Login) { state.activePage = CeraonPage.Loading; state.loadingPageState.loadingStatusMessage = 'Logging you in...'; } return state; }
Add support in reducer for login action
Add support in reducer for login action
TypeScript
bsd-3-clause
Rdbaker/Mealbound,Rdbaker/Mealbound,Rdbaker/Mealbound,Rdbaker/Mealbound,Rdbaker/Mealbound
--- +++ @@ -1,6 +1,14 @@ import CeraonState from '../../State/CeraonState'; import CeraonAction from '../../Actions/CeraonAction'; +import CeraonActionType from '../../Actions/CeraonActionType'; +import CeraonPage from '../../State/CeraonPage'; export default function ceraonReducer(state: CeraonState, action: CeraonAction) : CeraonState { + + if (action.type == CeraonActionType.Login) { + state.activePage = CeraonPage.Loading; + state.loadingPageState.loadingStatusMessage = 'Logging you in...'; + } + return state; }
c60bff19df24f1a4c26fa940570e20724d5ded97
types/koa-bodyparser/koa-bodyparser-tests.ts
types/koa-bodyparser/koa-bodyparser-tests.ts
import * as Koa from "koa"; import * as bodyParser from "koa-bodyparser"; const app = new Koa(); app.use(bodyParser({ strict: false })); app.listen(80)
import * as Koa from "koa"; import * as bodyParser from "koa-bodyparser"; const app = new Koa(); app.use(bodyParser({ strict: false })); app.use((ctx) => { console.log(ctx.request.body); console.log(ctx.request.rawBody); }) app.listen(80);
Use body parser request variables in tests
Use body parser request variables in tests
TypeScript
mit
abbasmhd/DefinitelyTyped,aciccarello/DefinitelyTyped,AgentME/DefinitelyTyped,jimthedev/DefinitelyTyped,benishouga/DefinitelyTyped,zuzusik/DefinitelyTyped,abbasmhd/DefinitelyTyped,arusakov/DefinitelyTyped,borisyankov/DefinitelyTyped,rolandzwaga/DefinitelyTyped,one-pieces/DefinitelyTyped,zuzusik/DefinitelyTyped,chrootsu/DefinitelyTyped,alexdresko/DefinitelyTyped,georgemarshall/DefinitelyTyped,benliddicott/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,aciccarello/DefinitelyTyped,georgemarshall/DefinitelyTyped,mcliment/DefinitelyTyped,arusakov/DefinitelyTyped,benishouga/DefinitelyTyped,jimthedev/DefinitelyTyped,benishouga/DefinitelyTyped,dsebastien/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,magny/DefinitelyTyped,georgemarshall/DefinitelyTyped,nycdotnet/DefinitelyTyped,AgentME/DefinitelyTyped,AgentME/DefinitelyTyped,nycdotnet/DefinitelyTyped,magny/DefinitelyTyped,borisyankov/DefinitelyTyped,alexdresko/DefinitelyTyped,markogresak/DefinitelyTyped,arusakov/DefinitelyTyped,rolandzwaga/DefinitelyTyped,dsebastien/DefinitelyTyped,zuzusik/DefinitelyTyped,aciccarello/DefinitelyTyped,AgentME/DefinitelyTyped,jimthedev/DefinitelyTyped,georgemarshall/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,chrootsu/DefinitelyTyped
--- +++ @@ -5,4 +5,9 @@ app.use(bodyParser({ strict: false })); -app.listen(80) +app.use((ctx) => { + console.log(ctx.request.body); + console.log(ctx.request.rawBody); +}) + +app.listen(80);
ce84c31af7b24a7c76a3859a3359c83771bc333c
src/browser/components/error/servererror.tsx
src/browser/components/error/servererror.tsx
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. import * as React from 'react'; let shell: Electron.Shell = (window as any).require('electron').remote.shell; export namespace ServerError { export interface Props { launchFromPath: () => void; } } export function ServerError(props: ServerError.Props) { return ( <div className='jpe-ServerError-body'> <div className='jpe-ServerError-content'> <div className='jpe-ServerError-icon'></div> <h1 className='jpe-ServerError-header'>Jupyter Server Not Found</h1> <p className='jpe-ServerError-subhead'>We were unable to launch a Jupyter server, which is a prerequisite for JupyterLab Native. If Jupyter is already installed, but it is not in your PATH, specify its location below. Otherwise, try installing or updating Jupyter. The Jupyter notebook version should be 4.3.0 or greater.</p> <div className='jpe-ServerError-btn-container'> <button className='jpe-ServerError-btn' onClick={props.launchFromPath}>CHOOSE PATH</button> <button className='jpe-ServerError-btn' onClick={() => { shell.openExternal('https://www.jupyter.org/install.html'); }}>INSTALL JUPYTER</button> </div> </div> </div> ); }
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. import * as React from 'react'; let shell: Electron.Shell = (window as any).require('electron').remote.shell; export namespace ServerError { export interface Props { launchFromPath: () => void; } } export function ServerError(props: ServerError.Props) { return ( <div className='jpe-ServerError-body'> <div className='jpe-ServerError-content'> <div className='jpe-ServerError-icon'></div> <h1 className='jpe-ServerError-header'>Jupyter Server Not Found</h1> <p className='jpe-ServerError-subhead'>We were unable to launch a Jupyter server, which is a prerequisite for JupyterLab Native. If Jupyter is already installed, but it is not in your PATH, specify its location below. Otherwise, try installing or updating Jupyter. The Jupyter notebook version must be 4.3.0 or greater.</p> <div className='jpe-ServerError-btn-container'> <button className='jpe-ServerError-btn' onClick={props.launchFromPath}>CHOOSE PATH</button> <button className='jpe-ServerError-btn' onClick={() => { shell.openExternal('https://www.jupyter.org/install.html'); }}>INSTALL JUPYTER</button> </div> </div> </div> ); }
Update wording of the version requirement
Update wording of the version requirement
TypeScript
bsd-3-clause
nproctor/jupyterlab_app,nproctor/jupyterlab_app,nproctor/jupyterlab_app
--- +++ @@ -20,7 +20,7 @@ <div className='jpe-ServerError-content'> <div className='jpe-ServerError-icon'></div> <h1 className='jpe-ServerError-header'>Jupyter Server Not Found</h1> - <p className='jpe-ServerError-subhead'>We were unable to launch a Jupyter server, which is a prerequisite for JupyterLab Native. If Jupyter is already installed, but it is not in your PATH, specify its location below. Otherwise, try installing or updating Jupyter. The Jupyter notebook version should be 4.3.0 or greater.</p> + <p className='jpe-ServerError-subhead'>We were unable to launch a Jupyter server, which is a prerequisite for JupyterLab Native. If Jupyter is already installed, but it is not in your PATH, specify its location below. Otherwise, try installing or updating Jupyter. The Jupyter notebook version must be 4.3.0 or greater.</p> <div className='jpe-ServerError-btn-container'> <button className='jpe-ServerError-btn' onClick={props.launchFromPath}>CHOOSE PATH</button> <button className='jpe-ServerError-btn' onClick={() => {
858526a70da00942118b4a75f6ed1e5ec35e34e1
sprinkler/app/programs/program.ts
sprinkler/app/programs/program.ts
import { Zone } from './../zones/zone'; export class Program { id: number; name: string; scheduleItems: ProgramScheduleItem[]; programScheduleType: ProgramScheduleType; startTimeHours: number; startTimeMinutes: number; monday: boolean; tuesday: boolean; wednesday: boolean; thursday: boolean; friday: boolean; saturday: boolean; sunday: boolean; constructor() { this.scheduleItems = []; } getRunningTime(): number { return this.scheduleItems .map(item => item.minutes) .reduce((prev, curr) => prev + curr, 0); } } export class ProgramScheduleItem { zone: Zone; minutes: number; } export enum ProgramScheduleType { ManualOnly = 0, AllDays = 1, OddDays = 2, EvenDays = 3, DaysOfWeek = 4 }
import { Zone } from './../zones/zone'; export class Program { id: number = 0; name: string; scheduleItems: ProgramScheduleItem[] = []; programScheduleType: ProgramScheduleType = ProgramScheduleType.ManualOnly; startTimeHours: number = 0; startTimeMinutes: number = 0; monday: boolean; tuesday: boolean; wednesday: boolean; thursday: boolean; friday: boolean; saturday: boolean; sunday: boolean; getRunningTime(): number { return this.scheduleItems .map(item => item.minutes) .reduce((prev, curr) => prev + curr, 0); } } export class ProgramScheduleItem { zone: Zone; minutes: number; } export enum ProgramScheduleType { ManualOnly = 0, AllDays = 1, OddDays = 2, EvenDays = 3, DaysOfWeek = 4 }
Add some sensible default values
Add some sensible default values
TypeScript
mit
nzjoel1234/sprinkler,nzjoel1234/sprinkler,nzjoel1234/sprinkler,nzjoel1234/sprinkler
--- +++ @@ -1,12 +1,12 @@ import { Zone } from './../zones/zone'; export class Program { - id: number; + id: number = 0; name: string; - scheduleItems: ProgramScheduleItem[]; - programScheduleType: ProgramScheduleType; - startTimeHours: number; - startTimeMinutes: number; + scheduleItems: ProgramScheduleItem[] = []; + programScheduleType: ProgramScheduleType = ProgramScheduleType.ManualOnly; + startTimeHours: number = 0; + startTimeMinutes: number = 0; monday: boolean; tuesday: boolean; wednesday: boolean; @@ -14,10 +14,6 @@ friday: boolean; saturday: boolean; sunday: boolean; - - constructor() { - this.scheduleItems = []; - } getRunningTime(): number { return this.scheduleItems
b20f4d840811dc04cf85678931d9438e6e47b875
src/Game/Object.ts
src/Game/Object.ts
///<reference path="./Messenger.ts" /> module Game { export class GameObject extends Messenger { /** * A native class that sends some useful events. * * @constructor * @extends Game.Messenger */ constructor() { super(); } /** * Called when the object is added to a state. */ public added() { // When the object is added to a state, the object will fire a create event this.fire('create'); } } }
///<reference path="./Messenger.ts" /> module Game { export class GameObject extends Messenger { /** * A native class that sends some useful events. * * @constructor * @extends Game.Messenger */ constructor() { super(); } /** * Called when the object is added to a state. */ public added() { // When the object is added to a state, the object will fire a create event this.fire('create', this); } } }
Send object as data in create event
Send object as data in create event
TypeScript
mit
eugene-bulkin/game-library,eugene-bulkin/game-library
--- +++ @@ -16,7 +16,7 @@ */ public added() { // When the object is added to a state, the object will fire a create event - this.fire('create'); + this.fire('create', this); } } }
17cb4da5ea3bebe343b330f3571b95132a24315e
addon/ng2/blueprints/ng2/files/e2e/app.po.ts
addon/ng2/blueprints/ng2/files/e2e/app.po.ts
export class <%= jsComponentName %>Page { navigateTo() { return browser.get('/'); } getParagraphText() { return element(by.css('<%= jsComponentName %>-app p')).getText(); } }
export class <%= jsComponentName %>Page { navigateTo() { return browser.get('/'); } getParagraphText() { return element(by.css('<%= htmlComponentName %>-app p')).getText(); } }
Fix Protractor test so 'ng e2e' succeeds after 'ng new'
fix(tests): Fix Protractor test so 'ng e2e' succeeds after 'ng new'
TypeScript
mit
intellix/angular-cli,hollannikas/angular-cli,catull/angular-cli,geofffilippi/angular-cli,IgorMinar/angular-cli,DevIntent/angular-cli,escorp/angular-cli,fuitattila/angular-cli,intellix/angular-cli,vsavkin/angular-cli,jimitndiaye/angular-cli,ReToCode/angular-cli,IgorMinar/angular-cli,delasteve/angular-cli,IgorMinar/angular-cli,devCrossNet/angular-cli,catull/angular-cli,devCrossNet/universal-cli,olivercs/angular-cli,vsavkin/angular-cli,filipesilva/angular-cli,Equinox/angular-cli,fuitattila/angular-cli,DevIntent/angular-cli,jeremymwells/angular-cli,hansl/angular-cli,garoyeri/angular-cli,DevIntent/angular-cli,FrozenPandaz/angular-cli,RPGillespie6/angular-cli,JeremyTCD/angular-cli,abdulmoizeng/angular-cli,ocombe/angular-cli,FrozenPandaz/angular-cli,phmello/angular-cli,niklas-dahl/angular-cli,dpmorrow/angular-cli,LasTanzen/angular-cli,jeremymwells/angular-cli,RicardoVaranda/angular-cli,gelliott181/angular-cli,gelliott181/angular-cli,ocombe/angular-cli,suau/angular-cli,manekinekko/angular-cli,LasTanzen/angular-cli,mham/angular-cli,mham/angular-cli,nickroberts/angular-cli,jkuri/angular-cli,austin94/angular-cli,Equinox/angular-cli,manekinekko/angular-cli,cthrax/angular-cli,filipesilva/angular-cli,gatalabs/angular-cli,mham/angular-cli,maxime1992/angular-cli,niklas-dahl/angular-cli,abdulmoizeng/angular-cli,Brocco/angular-cli,Brocco/angular-cli,clydin/angular-cli,DevIntent/angular-cli,olivercs/angular-cli,hollannikas/angular-cli,marc-sensenich/angular-cli,Brocco/angular-cli,kieronqtran/angular-cli,dpmorrow/angular-cli,garoyeri/angular-cli,hollannikas/angular-cli,shairez/angular-cli,jkuri/angular-cli,clydin/angular-cli,jeremymwells/angular-cli,phmello/angular-cli,splicers/angular-cli,Brocco/angular-cli,splicers/angular-cli,hansl/angular-cli,suau/angular-cli,clydin/angular-cli,austin94/angular-cli,devCrossNet/universal-cli,kieronqtran/angular-cli,shairez/angular-cli,Brocco/angular-cli,kieronqtran/angular-cli,marc-sensenich/angular-cli,intellix/angular-cli,mikkeldamm/angular-cli,geofffilippi/angular-cli,RicardoVaranda/angular-cli,JeremyTCD/angular-cli,nickroberts/angular-cli,eduesr/Angular,escorp/angular-cli,splicers/angular-cli,maxime1992/angular-cli,angular/angular-cli,maxime1992/angular-cli,phmello/angular-cli,nwronski/angular-cli,ampyc/angular-cli,austin94/angular-cli,escorp/angular-cli,ValeryVS/angular-cli,cthrax/angular-cli,hansl/angular-cli,filipesilva/angular-cli,cironunes/angular-cli,nwronski/angular-cli,suau/angular-cli,Equinox/angular-cli,zoitravel/angular-cli,delasteve/angular-cli,LasTanzen/angular-cli,mikkeldamm/angular-cli,DevIntent/angular-cli,ValeryVS/angular-cli,niklas-dahl/angular-cli,shairez/angular-cli,JeremyTCD/angular-cli,hansl/angular-cli,ampyc/angular-cli,dzonatan/angular-cli,cthrax/angular-cli,cironunes/angular-cli,jimitndiaye/angular-cli,ReToCode/angular-cli,fuitattila/angular-cli,abdulmoizeng/angular-cli,fuitattila/angular-cli,dzonatan/angular-cli,cironunes/angular-cli,cladera/angular-cli,nickroberts/angular-cli,angular/angular-cli,suau/angular-cli,cladera/angular-cli,zoitravel/angular-cli,hollannikas/angular-cli,ocombe/angular-cli,catull/angular-cli,marc-sensenich/angular-cli,delasteve/angular-cli,jeremymwells/angular-cli,mikkeldamm/angular-cli,beeman/angular-cli,garoyeri/angular-cli,ocombe/angular-cli,marc-sensenich/angular-cli,olivercs/angular-cli,FrozenPandaz/angular-cli,beeman/angular-cli,clydin/angular-cli,JeremyTCD/angular-cli,ampyc/angular-cli,geofffilippi/angular-cli,cthrax/angular-cli,beeman/angular-cli,gelliott181/angular-cli,vsavkin/angular-cli,ocombe/angular-cli,angular/angular-cli,jimitndiaye/angular-cli,gatalabs/angular-cli,dpmorrow/angular-cli,devCrossNet/angular-cli,ValeryVS/angular-cli,devCrossNet/angular-cli,angular/angular-cli,pedroapy/angular-cli,jkuri/angular-cli,beeman/angular-cli,ReToCode/angular-cli,phmello/angular-cli,pedroapy/angular-cli,splicers/angular-cli,kieronqtran/angular-cli,manekinekko/angular-cli,filipesilva/angular-cli,RPGillespie6/angular-cli,zoitravel/angular-cli,dzonatan/angular-cli,cladera/angular-cli,nwronski/angular-cli,devCrossNet/universal-cli,Equinox/angular-cli,cironunes/angular-cli,pedroapy/angular-cli,gatalabs/angular-cli,devCrossNet/universal-cli,devCrossNet/angular-cli,RPGillespie6/angular-cli,jkuri/angular-cli,eduesr/Angular,RicardoVaranda/angular-cli,eduesr/Angular,shairez/angular-cli,jimitndiaye/angular-cli,catull/angular-cli,austin94/angular-cli,geofffilippi/angular-cli,gatalabs/angular-cli
--- +++ @@ -2,8 +2,8 @@ navigateTo() { return browser.get('/'); } - + getParagraphText() { - return element(by.css('<%= jsComponentName %>-app p')).getText(); + return element(by.css('<%= htmlComponentName %>-app p')).getText(); } }
03014187ce124740c2f6857686226614ff84f7f4
packages/@angular/cli/tasks/render-universal.ts
packages/@angular/cli/tasks/render-universal.ts
import { requireProjectModule } from '../utilities/require-project-module'; import { join } from 'path'; const fs = require('fs'); const Task = require('../ember-cli/lib/models/task'); export interface RenderUniversalTaskOptions { inputIndexPath: string; route: string; serverOutDir: string; outputIndexPath: string; } export default Task.extend({ run: function(options: RenderUniversalTaskOptions): Promise<any> { require('zone.js/dist/zone-node'); const renderModuleFactory = requireProjectModule(this.project.root, '@angular/platform-server').renderModuleFactory; // Get the main bundle from the server build's output directory. const serverDir = fs.readdirSync(options.serverOutDir); const serverMainBundle = serverDir .filter((file: string) => /main\.[a-zA-Z0-9]{20}.bundle\.js/.test(file))[0]; const serverBundlePath = join(options.serverOutDir, serverMainBundle); const AppServerModuleNgFactory = require(serverBundlePath).AppServerModuleNgFactory; const index = fs.readFileSync(options.inputIndexPath, 'utf8'); // Render to HTML and overwrite the client index file. return renderModuleFactory(AppServerModuleNgFactory, {document: index, url: options.route}) .then((html: string) => fs.writeFileSync(options.outputIndexPath, html)); } });
import { requireProjectModule } from '../utilities/require-project-module'; import { join } from 'path'; const fs = require('fs'); const Task = require('../ember-cli/lib/models/task'); export interface RenderUniversalTaskOptions { inputIndexPath: string; route: string; serverOutDir: string; outputIndexPath: string; } export default Task.extend({ run: function(options: RenderUniversalTaskOptions): Promise<any> { require('zone.js/dist/zone-node'); const renderModuleFactory = requireProjectModule(this.project.root, '@angular/platform-server').renderModuleFactory; // Get the main bundle from the server build's output directory. const serverDir = fs.readdirSync(options.serverOutDir); const serverMainBundle = serverDir .filter((file: string) => /main\.(?:[a-zA-Z0-9]{20}\.)?bundle\.js/.test(file))[0]; const serverBundlePath = join(options.serverOutDir, serverMainBundle); const AppServerModuleNgFactory = require(serverBundlePath).AppServerModuleNgFactory; const index = fs.readFileSync(options.inputIndexPath, 'utf8'); // Render to HTML and overwrite the client index file. return renderModuleFactory(AppServerModuleNgFactory, {document: index, url: options.route}) .then((html: string) => fs.writeFileSync(options.outputIndexPath, html)); } });
Allow app-shell build without hashing
fix(@angular/cli): Allow app-shell build without hashing App shell builds will now work when output-hashing is none
TypeScript
mit
manekinekko/angular-cli,manekinekko/angular-cli,mham/angular-cli,DevIntent/angular-cli,clydin/angular-cli,geofffilippi/angular-cli,nickroberts/angular-cli,filipesilva/angular-cli,nwronski/angular-cli,ocombe/angular-cli,beeman/angular-cli,ocombe/angular-cli,nickroberts/angular-cli,Brocco/angular-cli,maxime1992/angular-cli,beeman/angular-cli,nwronski/angular-cli,maxime1992/angular-cli,hansl/angular-cli,DevIntent/angular-cli,ocombe/angular-cli,mham/angular-cli,ocombe/angular-cli,catull/angular-cli,catull/angular-cli,hansl/angular-cli,Brocco/angular-cli,filipesilva/angular-cli,hansl/angular-cli,maxime1992/angular-cli,angular/angular-cli,clydin/angular-cli,Brocco/angular-cli,mham/angular-cli,ocombe/angular-cli,angular/angular-cli,geofffilippi/angular-cli,catull/angular-cli,catull/angular-cli,filipesilva/angular-cli,clydin/angular-cli,DevIntent/angular-cli,Brocco/angular-cli,beeman/angular-cli,DevIntent/angular-cli,geofffilippi/angular-cli,nickroberts/angular-cli,beeman/angular-cli,Brocco/angular-cli,hansl/angular-cli,filipesilva/angular-cli,DevIntent/angular-cli,angular/angular-cli,clydin/angular-cli,nwronski/angular-cli,angular/angular-cli,geofffilippi/angular-cli,manekinekko/angular-cli
--- +++ @@ -21,7 +21,7 @@ // Get the main bundle from the server build's output directory. const serverDir = fs.readdirSync(options.serverOutDir); const serverMainBundle = serverDir - .filter((file: string) => /main\.[a-zA-Z0-9]{20}.bundle\.js/.test(file))[0]; + .filter((file: string) => /main\.(?:[a-zA-Z0-9]{20}\.)?bundle\.js/.test(file))[0]; const serverBundlePath = join(options.serverOutDir, serverMainBundle); const AppServerModuleNgFactory = require(serverBundlePath).AppServerModuleNgFactory;
51ab2f9fed0574ab5b4add0c3f0830c80823e5ba
packages/react-day-picker/src/components/Day/Day.tsx
packages/react-day-picker/src/components/Day/Day.tsx
import { isSameDay } from 'date-fns'; import * as React from 'react'; import { DayProps } from '../../types'; import { getDayComponent } from './getDayComponent'; export function Day(props: DayProps): JSX.Element | null { const el = React.useRef<HTMLTimeElement>(null); const { day, dayPickerProps, currentMonth } = props; const { locale, formatDay, focusedDay } = dayPickerProps; const { rootProps, modifiers } = getDayComponent( day, currentMonth, dayPickerProps ); if (modifiers.hidden) { return null; } React.useEffect(() => { if (focusedDay && isSameDay(focusedDay, day)) { el?.current?.focus(); } }, [dayPickerProps.focusedDay]); return ( <time {...rootProps} ref={el}> {formatDay(day, { locale })} </time> ); }
import { isSameDay } from 'date-fns'; import * as React from 'react'; import { DayProps } from '../../types'; import { getDayComponent } from './getDayComponent'; export function Day(props: DayProps): JSX.Element | null { const el = React.useRef<HTMLTimeElement>(null); const { day, dayPickerProps, currentMonth } = props; const { locale, formatDay, focusedDay, showOutsideDays } = dayPickerProps; const { rootProps, modifiers } = getDayComponent( day, currentMonth, dayPickerProps ); if (modifiers.outside && !showOutsideDays) { return null; } React.useEffect(() => { if (focusedDay && isSameDay(focusedDay, day)) { el?.current?.focus(); } }, [dayPickerProps.focusedDay]); return ( <time {...rootProps} ref={el}> {formatDay(day, { locale })} </time> ); }
Use outside modifier to hide a day
Use outside modifier to hide a day
TypeScript
mit
gpbl/react-day-picker,gpbl/react-day-picker,gpbl/react-day-picker
--- +++ @@ -7,7 +7,7 @@ export function Day(props: DayProps): JSX.Element | null { const el = React.useRef<HTMLTimeElement>(null); const { day, dayPickerProps, currentMonth } = props; - const { locale, formatDay, focusedDay } = dayPickerProps; + const { locale, formatDay, focusedDay, showOutsideDays } = dayPickerProps; const { rootProps, modifiers } = getDayComponent( day, @@ -15,7 +15,7 @@ dayPickerProps ); - if (modifiers.hidden) { + if (modifiers.outside && !showOutsideDays) { return null; } React.useEffect(() => {
f334b339067bb70d91cdc793c1a524ffe3715cad
src/extension/sdk/capabilities.ts
src/extension/sdk/capabilities.ts
import { versionIsAtLeast } from "../../shared/utils"; export class DartCapabilities { public static get empty() { return new DartCapabilities("0.0.0"); } public version: string; constructor(dartVersion: string) { this.version = dartVersion; } get supportsDevTools() { return versionIsAtLeast(this.version, "2.1.0"); } get includesSourceForSdkLibs() { return versionIsAtLeast(this.version, "2.2.1"); } get handlesBreakpointsInPartFiles() { return versionIsAtLeast(this.version, "2.2.1-edge"); } get hasDocumentationInCompletions() { return !versionIsAtLeast(this.version, "2.6.0-dev"); } get handlesPathsEverywhereForBreakpoints() { return versionIsAtLeast(this.version, "2.2.1-edge"); } get supportsDisableServiceTokens() { return versionIsAtLeast(this.version, "2.2.1-dev.4.2"); } }
import { versionIsAtLeast } from "../../shared/utils"; export class DartCapabilities { public static get empty() { return new DartCapabilities("0.0.0"); } public version: string; constructor(dartVersion: string) { this.version = dartVersion; } get supportsDevTools() { return versionIsAtLeast(this.version, "2.1.0"); } get includesSourceForSdkLibs() { return versionIsAtLeast(this.version, "2.2.1"); } get handlesBreakpointsInPartFiles() { return versionIsAtLeast(this.version, "2.2.1-edge"); } get hasDocumentationInCompletions() { return !versionIsAtLeast(this.version, "2.5.1"); } get handlesPathsEverywhereForBreakpoints() { return versionIsAtLeast(this.version, "2.2.1-edge"); } get supportsDisableServiceTokens() { return versionIsAtLeast(this.version, "2.2.1-dev.4.2"); } }
Fix version in completion tests
Fix version in completion tests
TypeScript
mit
Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code
--- +++ @@ -12,7 +12,7 @@ get supportsDevTools() { return versionIsAtLeast(this.version, "2.1.0"); } get includesSourceForSdkLibs() { return versionIsAtLeast(this.version, "2.2.1"); } get handlesBreakpointsInPartFiles() { return versionIsAtLeast(this.version, "2.2.1-edge"); } - get hasDocumentationInCompletions() { return !versionIsAtLeast(this.version, "2.6.0-dev"); } + get hasDocumentationInCompletions() { return !versionIsAtLeast(this.version, "2.5.1"); } get handlesPathsEverywhereForBreakpoints() { return versionIsAtLeast(this.version, "2.2.1-edge"); } get supportsDisableServiceTokens() { return versionIsAtLeast(this.version, "2.2.1-dev.4.2"); } }
a15c186523161e5f550a4f9d732e2d761637d512
src/mutators/Mutator.ts
src/mutators/Mutator.ts
import * as ts from 'typescript'; import { MutationContext } from '../context'; export abstract class Mutator { protected abstract kind: ts.SyntaxKind | ts.SyntaxKind[]; protected abstract mutate(node: ts.Node, context?: MutationContext): ts.Node; protected context: MutationContext; public mutateNode(node: ts.Node, context: MutationContext): ts.Node { this.context = context; if (this.getKind().indexOf(node.kind) === -1) { return node; } if (context.wasVisited(node)) { return node; } const substitution = this.mutate(node, context); context.addVisited(substitution); return substitution; } public getKind(): ts.SyntaxKind[] { if (Array.isArray(this.kind)) { return this.kind; } return [this.kind]; } }
import * as ts from 'typescript'; import { Generator } from '../generator'; import { MutationContext } from '../context'; export abstract class Mutator { protected abstract kind: ts.SyntaxKind | ts.SyntaxKind[]; protected abstract mutate(node: ts.Node, context?: MutationContext): ts.Node; protected context: MutationContext; public mutateNode(node: ts.Node, context: MutationContext): ts.Node { this.context = context; if (this.getKind().indexOf(node.kind) === -1) { return node; } if (context.wasVisited(node)) { return node; } const substitution = this.mutate(node, context); context.addVisited(substitution); return substitution; } public getKind(): ts.SyntaxKind[] { if (Array.isArray(this.kind)) { return this.kind; } return [this.kind]; } get generator(): Generator { return this.context.generator; } }
Make generator available from MutationContext through a getter.
Make generator available from MutationContext through a getter.
TypeScript
mit
fabiandev/ts-runtime,fabiandev/ts-runtime,fabiandev/ts-runtime
--- +++ @@ -1,4 +1,5 @@ import * as ts from 'typescript'; +import { Generator } from '../generator'; import { MutationContext } from '../context'; export abstract class Mutator { @@ -34,4 +35,8 @@ return [this.kind]; } + get generator(): Generator { + return this.context.generator; + } + }
d5401e30f484c35b61482c2b2b838fe773393c3f
src/util/dbUtil.ts
src/util/dbUtil.ts
import { Product } from '../models/merchant/Product'; import { Merchant } from '../models/merchant/Merchant'; import {ConnectionOptions, getConnectionManager} from 'typeorm'; import { createConnection } from 'typeorm'; import { Supplier } from '../models/merchant/Supplier'; import { Customer } from '../models/customer/Customer'; import { Comment } from '../models/customer/Comment'; import { OrderedProduct } from '../models/ordering/OrderedProduct'; import { Order } from '../models/ordering/Order'; module.exports = { getDatabaseConfig() { const connectionOptions: ConnectionOptions = { driver : { type: 'mysql', host: process.env.OPENSHIFT_MYSQL_DB_HOST || 'localhost', port: process.env.OPENSHIFT_MYSQL_DB_PORT || 3306, username: process.env.OPENSHIFT_MYSQL_DB_USERNAME || 'root', password: process.env.OPENSHIFT_MYSQL_DB_PASSWORD || 'password', database: 'testDB' }, autoSchemaSync: true, logging: { logQueries: true, }, entities: [Merchant, Product, Supplier, Customer, Comment, Order, OrderedProduct], }; return connectionOptions; }, async getConnection() { const connectionManager = getConnectionManager(); if (connectionManager.has('default')) { return connectionManager.get('default'); } let dbConnection; await createConnection(this.getDatabaseConfig()).then(connection => { dbConnection = connection; }); return dbConnection; } };
import { Product } from '../models/merchant/Product'; import { Merchant } from '../models/merchant/Merchant'; import {ConnectionOptions, getConnectionManager} from 'typeorm'; import { createConnection } from 'typeorm'; import { Supplier } from '../models/merchant/Supplier'; import { Customer } from '../models/customer/Customer'; import { Comment } from '../models/customer/Comment'; import { OrderedProduct } from '../models/ordering/OrderedProduct'; import { Order } from '../models/ordering/Order'; module.exports = { getDatabaseConfig() { const connectionOptions: ConnectionOptions = { driver : { type: 'mysql', host: process.env.OPENSHIFT_MYSQL_DB_HOST || 'localhost', port: process.env.OPENSHIFT_MYSQL_DB_PORT || 3306, username: process.env.OPENSHIFT_MYSQL_DB_USERNAME || 'root', password: process.env.OPENSHIFT_MYSQL_DB_PASSWORD || 'password', database: 'afs' }, autoSchemaSync: true, logging: { logQueries: true, }, entities: [Merchant, Product, Supplier, Customer, Comment, Order, OrderedProduct], }; return connectionOptions; }, async getConnection() { const connectionManager = getConnectionManager(); if (connectionManager.has('default')) { return connectionManager.get('default'); } let dbConnection; await createConnection(this.getDatabaseConfig()).then(connection => { dbConnection = connection; }); return dbConnection; } };
Update DB name for openshift
Update DB name for openshift
TypeScript
mit
prettyflyit/legendary-bassoon,prettyflyit/legendary-bassoon
--- +++ @@ -17,7 +17,7 @@ port: process.env.OPENSHIFT_MYSQL_DB_PORT || 3306, username: process.env.OPENSHIFT_MYSQL_DB_USERNAME || 'root', password: process.env.OPENSHIFT_MYSQL_DB_PASSWORD || 'password', - database: 'testDB' + database: 'afs' }, autoSchemaSync: true, logging: {
a16d3a303bfcfdd08ed007e524198b061b89d6ef
index.d.ts
index.d.ts
import { cleanup, act, RenderOptions, RenderResult } from 'react-testing-library' export function renderHook<P, R>( callback: (...args: [P]) => R, options?: { initialProps?: P } & RenderOptions ): { readonly result: { current: R } readonly unmount: RenderResult['unmount'] readonly rerender: (hookProps?: P) => void } export const testHook: typeof renderHook export { cleanup, act }
import { cleanup, act, RenderOptions, RenderResult } from 'react-testing-library' export function renderHook<P, R>( callback: (props: P) => R, options?: { initialProps?: P } & RenderOptions ): { readonly result: { current: R } readonly unmount: RenderResult['unmount'] readonly rerender: (hookProps?: P) => void } export const testHook: typeof renderHook export { cleanup, act }
Simplify the way to extract first argument type
Simplify the way to extract first argument type Co-Authored-By: otofu-square <[email protected]>
TypeScript
mit
testing-library/react-hooks-testing-library,testing-library/react-hooks-testing-library
--- +++ @@ -1,7 +1,7 @@ import { cleanup, act, RenderOptions, RenderResult } from 'react-testing-library' export function renderHook<P, R>( - callback: (...args: [P]) => R, + callback: (props: P) => R, options?: { initialProps?: P } & RenderOptions
95484050f0fe63f83f4f065f549def4b0c5f4544
src/app/app.component.spec.ts
src/app/app.component.spec.ts
import { it, inject, beforeEachProviders } from '@angular/core/testing'; // Load the implementations that should be tested import { AppComponent } from './app.component'; describe('App', () => { // provide our implementations or mocks to the dependency injector beforeEachProviders(() => [ AppComponent ]); it('should have an url', inject([AppComponent], (app: AppComponent) => { expect(!!app.title).toEqual(true); })); });
import { it, inject, beforeEachProviders } from '@angular/core/testing'; // Load the implementations that should be tested import { AppComponent } from './app.component'; import { StorageService } from './shared'; describe('App', () => { // provide our implementations or mocks to the dependency injector beforeEachProviders(() => [ AppComponent, StorageService ]); it('should have a title', inject([AppComponent, StorageService], (app: AppComponent, StorageService) => { expect(!!app.title).toEqual(true); })); });
Fix app component unit test
Fix app component unit test
TypeScript
mit
SBats/marvel-reading-stats-frontend,SBats/marvel-reading-stats-frontend,SBats/marvel-reading-stats-frontend
--- +++ @@ -7,13 +7,16 @@ // Load the implementations that should be tested import { AppComponent } from './app.component'; +import { StorageService } from './shared'; + describe('App', () => { // provide our implementations or mocks to the dependency injector beforeEachProviders(() => [ - AppComponent + AppComponent, + StorageService ]); - it('should have an url', inject([AppComponent], (app: AppComponent) => { + it('should have a title', inject([AppComponent, StorageService], (app: AppComponent, StorageService) => { expect(!!app.title).toEqual(true); }));
6373683820fdd756375954e9180735db620fd92e
app/src/banner/banner.tsx
app/src/banner/banner.tsx
import * as React from "react"; const styles = require("./banner.less"); export function Banner() { return ( <a className={styles.conference_banner} href="https://kotlinconf.com"> <div className={styles.conference_banner__img}/> </a> ); }
import * as React from "react"; const styles = require("./banner.less"); export function Banner() { return ( <a className={styles.conference_banner} href="https://kotlinconf.com/?utm_source=kotlinlink&utm_medium=web"> <div className={styles.conference_banner__img}/> </a> ); }
Update link to Kotlin Conf.
Update link to Kotlin Conf.
TypeScript
apache-2.0
KotlinBy/awesome-kotlin,KotlinBy/awesome-kotlin,KotlinBy/awesome-kotlin,KotlinBy/awesome-kotlin
--- +++ @@ -4,7 +4,8 @@ export function Banner() { return ( - <a className={styles.conference_banner} href="https://kotlinconf.com"> + <a className={styles.conference_banner} + href="https://kotlinconf.com/?utm_source=kotlinlink&utm_medium=web"> <div className={styles.conference_banner__img}/> </a> );
576e831b9823b80b6e70a05bdb54ba7c0675dd09
src/Properties/Resources.ts
src/Properties/Resources.ts
/* eslint-disable @typescript-eslint/no-var-requires */ import { CultureInfo, IResourceManager, MustacheResourceManager, Resource, ResourceManager } from "@manuth/resource-manager"; import Files = require("./Files"); /** * Represents the resources of the module. */ export class Resources { /** * The resources. */ private static resources: IResourceManager = null; /** * The files. */ private static files: IResourceManager = null; /** * Sets the culture of the resources. */ public static set Culture(value: CultureInfo) { this.resources.Locale = this.files.Locale = value; } /** * Gets the resources. */ public static get Resources(): IResourceManager { if (this.resources === null) { this.resources = new MustacheResourceManager( new ResourceManager( [ new Resource(require("../../Resources/MarkdownConverter.json")), new Resource(require("../../Resources/MarkdownConverter.de.json"), new CultureInfo("de")) ])); } return this.resources; } /** * Gets the files. */ public static get Files(): IResourceManager { if (this.files === null) { this.files = new ResourceManager( [ new Resource(Files as any) ]); } return this.files; } }
/* eslint-disable @typescript-eslint/no-var-requires */ import { CultureInfo, IResourceManager, MustacheResourceManager, Resource, ResourceManager } from "@manuth/resource-manager"; import { readJSONSync } from "fs-extra"; import { join } from "path"; import Files = require("./Files"); /** * Represents the resources of the module. */ export class Resources { /** * The resources. */ private static resources: IResourceManager = null; /** * The files. */ private static files: IResourceManager = null; /** * Sets the culture of the resources. */ public static set Culture(value: CultureInfo) { this.resources.Locale = this.files.Locale = value; } /** * Gets the resources. */ public static get Resources(): IResourceManager { if (this.resources === null) { this.resources = new MustacheResourceManager( new ResourceManager( [ new Resource(readJSONSync(join(__dirname, "..", "..", "Resources", "MarkdownConverter.json"))), new Resource( readJSONSync( join(__dirname, "..", "..", "Resources", "MarkdownConverter.de.json")), new CultureInfo("de")) ])); } return this.resources; } /** * Gets the files. */ public static get Files(): IResourceManager { if (this.files === null) { this.files = new ResourceManager( [ new Resource(Files as any) ]); } return this.files; } }
Read JSON data using `readJSONSync`
Read JSON data using `readJSONSync`
TypeScript
mit
manuth/MarkdownConverter,manuth/MarkdownConverter,manuth/MarkdownConverter
--- +++ @@ -1,5 +1,7 @@ /* eslint-disable @typescript-eslint/no-var-requires */ import { CultureInfo, IResourceManager, MustacheResourceManager, Resource, ResourceManager } from "@manuth/resource-manager"; +import { readJSONSync } from "fs-extra"; +import { join } from "path"; import Files = require("./Files"); /** @@ -36,8 +38,11 @@ this.resources = new MustacheResourceManager( new ResourceManager( [ - new Resource(require("../../Resources/MarkdownConverter.json")), - new Resource(require("../../Resources/MarkdownConverter.de.json"), new CultureInfo("de")) + new Resource(readJSONSync(join(__dirname, "..", "..", "Resources", "MarkdownConverter.json"))), + new Resource( + readJSONSync( + join(__dirname, "..", "..", "Resources", "MarkdownConverter.de.json")), + new CultureInfo("de")) ])); }
313efc7cf9ff553c192143e67029428aa2d274db
src/main-process/application-window.ts
src/main-process/application-window.ts
// Copyright (c) 2015 Vadim Macagon // MIT License, see LICENSE file for full terms. import * as path from 'path'; import * as electron from 'electron'; import { IAppWindowConfig } from '../common/app-window-config'; import * as AppWindowConfig from '../common/app-window-config'; export interface IApplicationWindowOpenParams { windowUrl: string; config: IAppWindowConfig; } export class ApplicationWindow { private _browserWindow: GitHubElectron.BrowserWindow; open({ windowUrl, config }: IApplicationWindowOpenParams): void { const options = <GitHubElectron.BrowserWindowOptions> { // the window will be shown later after everything is fully initialized show: false, title: 'Debug Workbench', 'web-preferences': { 'direct-write': true } }; this._browserWindow = new electron.BrowserWindow(options); this._browserWindow.loadURL(windowUrl + '#' + AppWindowConfig.encodeToUriComponent(config)); this._bindEventHandlers(); } private _bindEventHandlers(): void { this._browserWindow.on('closed', () => { this._browserWindow = null; }); } }
// Copyright (c) 2015 Vadim Macagon // MIT License, see LICENSE file for full terms. import * as path from 'path'; import * as electron from 'electron'; import { IAppWindowConfig } from '../common/app-window-config'; import * as AppWindowConfig from '../common/app-window-config'; export interface IApplicationWindowOpenParams { windowUrl: string; config: IAppWindowConfig; } export class ApplicationWindow { private _browserWindow: GitHubElectron.BrowserWindow; open({ windowUrl, config }: IApplicationWindowOpenParams): void { const options: GitHubElectron.BrowserWindowOptions = { // the window will be shown later after everything is fully initialized show: false, title: 'Debug Workbench', webPreferences: { directWrite: true } }; this._browserWindow = new electron.BrowserWindow(options); this._browserWindow.loadURL(windowUrl + '#' + AppWindowConfig.encodeToUriComponent(config)); this._bindEventHandlers(); } private _bindEventHandlers(): void { this._browserWindow.on('closed', () => { this._browserWindow = null; }); } }
Fix misnamed options being used to create BrowserWindow(s)
Fix misnamed options being used to create BrowserWindow(s) BrowserWindow option names were normalized in v0.35. I forgot to update this bit after the recent update to the Electron typings, and TypeScript didn't pick up the errors because strict checking of object literals only occurs when the variable the object literal is assigned to (`options` in this case) is declared with an explicit type (and it wasn't in this case).
TypeScript
mit
debugworkbench/hydragon,debugworkbench/hydragon,debugworkbench/hydragon
--- +++ @@ -15,12 +15,12 @@ private _browserWindow: GitHubElectron.BrowserWindow; open({ windowUrl, config }: IApplicationWindowOpenParams): void { - const options = <GitHubElectron.BrowserWindowOptions> { + const options: GitHubElectron.BrowserWindowOptions = { // the window will be shown later after everything is fully initialized show: false, title: 'Debug Workbench', - 'web-preferences': { - 'direct-write': true + webPreferences: { + directWrite: true } }; this._browserWindow = new electron.BrowserWindow(options);
55d731ce1d06ddbc0c2e9efab475376f97c05ecb
client/Components/Button.tsx
client/Components/Button.tsx
import * as React from "react"; export interface ButtonProps { text?: string; faClass?: string; onClick: React.MouseEventHandler<HTMLSpanElement>; onMouseOver?: React.MouseEventHandler<HTMLSpanElement>; } export class Button extends React.Component<ButtonProps> { public render() { const text = this.props.text || ""; const className = this.props.faClass ? `c-button fa fa-${this.props.faClass}` : "c-button fa"; return <div className={className} onClick={this.props.onClick} onMouseOver={this.props.onMouseOver}>{text}</div>; } }
import * as React from "react"; export interface ButtonProps { text?: string; faClass?: string; onClick: React.MouseEventHandler<HTMLSpanElement>; onMouseOver?: React.MouseEventHandler<HTMLSpanElement>; } export class Button extends React.Component<ButtonProps> { public render() { const text = this.props.text || ""; const classNames = ["c-button", "fa"]; if(this.props.faClass){ classNames.push(`fa-${this.props.faClass}`); } return <span className={classNames.join(" ")} onClick={this.props.onClick} onMouseOver={this.props.onMouseOver}>{text}</span>; } }
Build classNames array and concat
Build classNames array and concat
TypeScript
mit
cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative
--- +++ @@ -10,7 +10,10 @@ export class Button extends React.Component<ButtonProps> { public render() { const text = this.props.text || ""; - const className = this.props.faClass ? `c-button fa fa-${this.props.faClass}` : "c-button fa"; - return <div className={className} onClick={this.props.onClick} onMouseOver={this.props.onMouseOver}>{text}</div>; + const classNames = ["c-button", "fa"]; + if(this.props.faClass){ + classNames.push(`fa-${this.props.faClass}`); + } + return <span className={classNames.join(" ")} onClick={this.props.onClick} onMouseOver={this.props.onMouseOver}>{text}</span>; } }
f537b741b0c902b4acd9a948e1fd6a566ad20966
source/store/tests/document-variant-store.ts
source/store/tests/document-variant-store.ts
import {DocumentVariantStore} from '../document-variant-store'; describe('DocumentVariantStore', () => { const mockApplication = { renderUri: () => Promise.resolve({a: 1}) } as any; interface Variants {foo: boolean, bar: number}; it('can never contain more than the size provided in the constructor', async () => { const cache = new DocumentVariantStore<Variants>(mockApplication, 1); await cache.load('http://localhost/1', {foo: true, bar: 0}); await cache.load('http://localhost/2', {foo: true, bar: 1}); expect(cache.size).toBe(1); }); it('can retrieve based on a pair of URI and variant values', async () => { const cache = new DocumentVariantStore<Variants>(mockApplication, 3); await cache.load('http://localhost/1', {foo: true, bar: 0}); await cache.load('http://localhost/2', {foo: false, bar: 2}); await cache.load('http://localhost/3', {foo: false, bar: -1}); expect(cache.size).toBe(3); mockApplication.renderUri = () => {throw new Error('Should not be called')}; debugger; expect(await cache.load('http://localhost/2', {foo: false, bar: 2})).toEqual({a:1}); // not recreated, must be cached version }); });
import {DocumentVariantStore} from '../document-variant-store'; describe('DocumentVariantStore', () => { const mockApplication = { renderUri: () => Promise.resolve({a: 1}) } as any; interface Variants {foo: boolean, bar: number}; it('can never contain more than the size provided in the constructor', async () => { const cache = new DocumentVariantStore<Variants>(mockApplication, 1); await cache.load('http://localhost/1', {foo: true, bar: 0}); await cache.load('http://localhost/2', {foo: true, bar: 1}); expect(cache.size).toBe(1); }); it('can retrieve based on a pair of URI and variant values', async () => { const cache = new DocumentVariantStore<Variants>(mockApplication, 3); await cache.load('http://localhost/1', {foo: true, bar: 0}); await cache.load('http://localhost/2', {foo: false, bar: 2}); await cache.load('http://localhost/3', {foo: false, bar: -1}); expect(cache.size).toBe(3); mockApplication.renderUri = () => {throw new Error('Should not be called')}; expect(await cache.load('http://localhost/2', {foo: false, bar: 2})).toEqual({a:1}); // not recreated, must be cached version }); });
Remove debugger call from unit test
Remove debugger call from unit test
TypeScript
bsd-2-clause
clbond/angular-ssr,clbond/angular-ssr,clbond/angular-ssr,clbond/angular-ssr
--- +++ @@ -23,7 +23,6 @@ mockApplication.renderUri = () => {throw new Error('Should not be called')}; - debugger; expect(await cache.load('http://localhost/2', {foo: false, bar: 2})).toEqual({a:1}); // not recreated, must be cached version }); });
4b5bb3a3818ab7295fa1fa1f9020bac34f137658
app/src/app/pages/project/project-page.component.ts
app/src/app/pages/project/project-page.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'project-page', templateUrl: 'project-page.component.html' }) export class ProjectPage implements OnInit { ngOnInit() { } }
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { LocalesService } from './../../locales/services/locales.service'; @Component({ providers: [LocalesService], selector: 'project-page', templateUrl: 'project-page.component.html' }) export class ProjectPage implements OnInit { ngOnInit() { } }
Add page level service injector
Add page level service injector
TypeScript
mit
todes1/parrot,anthonynsimon/parrot,anthonynsimon/parrot,anthonynsimon/parrot,anthonynsimon/parrot,todes1/parrot,todes1/parrot,todes1/parrot,anthonynsimon/parrot,anthonynsimon/parrot,todes1/parrot,todes1/parrot
--- +++ @@ -1,7 +1,10 @@ import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; +import { LocalesService } from './../../locales/services/locales.service'; + @Component({ + providers: [LocalesService], selector: 'project-page', templateUrl: 'project-page.component.html' })
b31bc9162aa23e3c9ea79b7d6a614187203a8bf0
src/Day.ts
src/Day.ts
import * as moment from 'moment' import { Moment } from 'moment' export const FORMAT = 'YYYY-MM-DD' function isValidDate(stringValue: string): boolean { return /^\d{4}-\d{2}-\d{2}$/.test(stringValue) && moment(stringValue, FORMAT).isValid() } export default class Day { private stringValue: string constructor(value: string | Moment) { if (typeof value === 'string') { if (!isValidDate(value)) { throw new Error(`${value} isn't a valid ISO 8601 date literal`) } this.stringValue = value } else { this.stringValue = value.format(FORMAT) } } toString(): string { return this.stringValue } toMoment(): moment.Moment { return moment(this.stringValue) } next(): Day { return new Day(this.toMoment().add(1, 'days')) } previous(): Day { return new Day(this.toMoment().subtract(1, 'days')) } }
import * as moment from 'moment' import { Moment } from 'moment' export const FORMAT = 'YYYY-MM-DD' function isValidDate(stringValue: string): boolean { return /^\d{4}-\d{2}-\d{2}$/.test(stringValue) && moment.utc(stringValue, FORMAT).isValid() } export default class Day { private stringValue: string constructor(value: string | Moment) { if (typeof value === 'string') { if (!isValidDate(value)) { throw new Error(`${value} isn't a valid ISO 8601 date literal`) } this.stringValue = value } else { this.stringValue = value.format(FORMAT) } } toString(): string { return this.stringValue } toMoment(): moment.Moment { return moment(this.stringValue) } next(): Day { return new Day(this.toMoment().add(1, 'days')) } previous(): Day { return new Day(this.toMoment().subtract(1, 'days')) } }
Add a workaround for the "moment is not function" error
Add a workaround for the "moment is not function" error That happens with the parcel.js bundle. See: https://github.com/parcel-bundler/parcel/issues/1194 https://github.com/moment/moment/issues/3650 https://github.com/palantir/blueprint/issues/959
TypeScript
mit
ikr/react-period-of-stay-input,ikr/react-period-of-stay-input,ikr/react-period-of-stay-input
--- +++ @@ -4,7 +4,7 @@ export const FORMAT = 'YYYY-MM-DD' function isValidDate(stringValue: string): boolean { - return /^\d{4}-\d{2}-\d{2}$/.test(stringValue) && moment(stringValue, FORMAT).isValid() + return /^\d{4}-\d{2}-\d{2}$/.test(stringValue) && moment.utc(stringValue, FORMAT).isValid() } export default class Day {
7c1e5eb01a2a76c78debc587262c07d6165f652e
applications/drive/src/app/App.tsx
applications/drive/src/app/App.tsx
import { hot } from 'react-hot-loader/root'; import React from 'react'; import { ProtonApp, StandardSetup } from 'react-components'; import locales from 'proton-shared/lib/i18n/locales'; import sentry from 'proton-shared/lib/helpers/sentry'; import * as config from './config'; import PrivateApp from './PrivateApp'; import './app.scss'; sentry(config); const App = () => { return ( <ProtonApp config={config}> <StandardSetup PrivateApp={PrivateApp} locales={locales} /> </ProtonApp> ); }; export default hot(App);
import React from 'react'; import { ProtonApp, StandardSetup } from 'react-components'; import locales from 'proton-shared/lib/i18n/locales'; import sentry from 'proton-shared/lib/helpers/sentry'; import * as config from './config'; import PrivateApp from './PrivateApp'; import './app.scss'; sentry(config); const App = () => { return ( <ProtonApp config={config}> <StandardSetup PrivateApp={PrivateApp} locales={locales} /> </ProtonApp> ); }; export default App;
Use fast-refresh instead of hot-loader
Use fast-refresh instead of hot-loader
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -1,4 +1,3 @@ -import { hot } from 'react-hot-loader/root'; import React from 'react'; import { ProtonApp, StandardSetup } from 'react-components'; import locales from 'proton-shared/lib/i18n/locales'; @@ -19,4 +18,4 @@ ); }; -export default hot(App); +export default App;
4fb444d6a11be3942bdf2934d226c2b952f39c17
packages/cli/src/generate/utils/init-git-repo.ts
packages/cli/src/generate/utils/init-git-repo.ts
import { spawn } from 'child_process'; // This file is inspired by the Angular CLI (MIT License: https://angular.io/license). // See https://github.com/angular/angular-cli/blob/master/packages/angular_devkit/schematics/tasks/repo-init/executor.ts export async function initGitRepo(root: string) { function execute(args: string[]) { return new Promise<void>((resolve, reject) => { spawn('git', args, { cwd: root }) .on('close', (code: number) => code === 0 ? resolve() : reject(code)); }); } const hasCommand = await execute(['--version']).then(() => true, () => false); if (!hasCommand) { return; } const insideRepo = await execute(['rev-parse', '--is-inside-work-tree']) .then(() => true, () => false); if (insideRepo) { console.log('Directory is already under version control. Skipping initialization of git.'); return; } try { await execute(['init']); await execute(['add', '.']); await execute(['commit', '-m "Initial commit"']); } catch { console.log('Initialization of git failed.'); } }
import { spawn } from 'child_process'; // This file is inspired by the Angular CLI (MIT License: https://angular.io/license). // See https://github.com/angular/angular-cli/blob/master/packages/angular_devkit/schematics/tasks/repo-init/executor.ts export async function initGitRepo(root: string) { function execute(args: string[]) { return new Promise<void>((resolve, reject) => { spawn('git', args, { cwd: root, shell: true }) .on('close', (code: number) => code === 0 ? resolve() : reject(code)); }); } const hasCommand = await execute(['--version']).then(() => true, () => false); if (!hasCommand) { console.log('Git not installed. Skipping initialization of git.'); return; } const insideRepo = await execute(['rev-parse', '--is-inside-work-tree']) .then(() => true, () => false); if (insideRepo) { console.log('Directory is already under version control. Skipping initialization of git.'); return; } try { await execute(['init']); await execute(['add', '.']); await execute(['commit', '-m "Initial commit"']); } catch { console.log('Initialization of git failed.'); } }
Fix displayed when git is not installed
[@foal/cli] Fix displayed when git is not installed
TypeScript
mit
FoalTS/foal,FoalTS/foal,FoalTS/foal,FoalTS/foal
--- +++ @@ -7,13 +7,14 @@ function execute(args: string[]) { return new Promise<void>((resolve, reject) => { - spawn('git', args, { cwd: root }) + spawn('git', args, { cwd: root, shell: true }) .on('close', (code: number) => code === 0 ? resolve() : reject(code)); }); } const hasCommand = await execute(['--version']).then(() => true, () => false); if (!hasCommand) { + console.log('Git not installed. Skipping initialization of git.'); return; }
8448227cb2394787045e5a2f3ae457bbe9d77b15
app/src/lib/databases/pull-request-database.ts
app/src/lib/databases/pull-request-database.ts
import Dexie from 'dexie' export interface IPullRequestRef { readonly repoId: number readonly ref: string readonly sha: string } export interface IPullRequest { readonly id?: number readonly number: number readonly title: string readonly createdAt: string readonly head: IPullRequestRef readonly base: IPullRequestRef readonly author: string } export interface IPullRequestStatus { readonly id?: number readonly state: string readonly totalCount: number readonly pullRequestId: number readonly sha: string } export class PullRequestDatabase extends Dexie { public pullRequests: Dexie.Table<IPullRequest, number> public pullRequestStatus: Dexie.Table<IPullRequestStatus, number> public constructor(name: string) { super(name) this.version(1).stores({ pullRequests: 'id++, base.repoId', }) this.version(2).stores({ pullRequestStatus: 'id++, &[sha+pullRequestId]', }) } }
import Dexie from 'dexie' import { APIRefState } from '../api' export interface IPullRequestRef { readonly repoId: number readonly ref: string readonly sha: string } export interface IPullRequest { readonly id?: number readonly number: number readonly title: string readonly createdAt: string readonly head: IPullRequestRef readonly base: IPullRequestRef readonly author: string } export interface IPullRequestStatus { readonly id?: number readonly state: APIRefState readonly totalCount: number readonly pullRequestId: number readonly sha: string } export class PullRequestDatabase extends Dexie { public pullRequests: Dexie.Table<IPullRequest, number> public pullRequestStatus: Dexie.Table<IPullRequestStatus, number> public constructor(name: string) { super(name) this.version(1).stores({ pullRequests: 'id++, base.repoId', }) this.version(2).stores({ pullRequestStatus: 'id++, &[sha+pullRequestId]', }) } }
Use interface for ci status
Use interface for ci status
TypeScript
mit
kactus-io/kactus,say25/desktop,shiftkey/desktop,artivilla/desktop,kactus-io/kactus,j-f1/forked-desktop,desktop/desktop,desktop/desktop,say25/desktop,j-f1/forked-desktop,say25/desktop,shiftkey/desktop,desktop/desktop,desktop/desktop,shiftkey/desktop,j-f1/forked-desktop,artivilla/desktop,say25/desktop,artivilla/desktop,kactus-io/kactus,j-f1/forked-desktop,artivilla/desktop,kactus-io/kactus,shiftkey/desktop
--- +++ @@ -1,4 +1,5 @@ import Dexie from 'dexie' +import { APIRefState } from '../api' export interface IPullRequestRef { readonly repoId: number @@ -18,7 +19,7 @@ export interface IPullRequestStatus { readonly id?: number - readonly state: string + readonly state: APIRefState readonly totalCount: number readonly pullRequestId: number readonly sha: string
31d2572b2756b8f33ef76f9654d08d37da0fed9a
demo/SpikesNgComponentsDemo/src/app/spikes-timeline-demo/spikes-timeline-demo.component.ts
demo/SpikesNgComponentsDemo/src/app/spikes-timeline-demo/spikes-timeline-demo.component.ts
import { Component, OnInit } from '@angular/core'; import * as tl from 'spikes-ng2-components'; @Component({ selector: 'app-spikes-timeline-demo', templateUrl: './spikes-timeline-demo.component.html', styleUrls: ['./spikes-timeline-demo.component.css'] }) export class SpikesTimelineDemoComponent implements OnInit { timelineItems: Array<tl.ITimelineItem> = []; constructor() { } ngOnInit() { for (let i: number = 0; i < 5; i++){ this.timelineItems.push(new tl.TimelineItem({ id: i, displayText: `Item ${i.toString()}`, color: i < 3 ? 'primary' : i === 3 ? 'test' : 'grey', isActive: i === 0 ? true : false })); } } private onTimelineItemAction(item: tl.ITimelineEventArgs){ console.log('TimelineItem Clicked'); console.log(item); } }
import { Component, OnInit } from '@angular/core'; import * as tl from 'spikes-ng2-components'; @Component({ selector: 'app-spikes-timeline-demo', templateUrl: './spikes-timeline-demo.component.html', styleUrls: ['./spikes-timeline-demo.component.css'] }) export class SpikesTimelineDemoComponent implements OnInit { timelineItems: Array<tl.ITimelineItem> = []; constructor() { } ngOnInit() { this.timelineItems = [...this.createTimelineItems(5)]; } private onTimelineItemAction(item: tl.ITimelineEventArgs){ console.log('TimelineItem Clicked'); console.log(item); this.timelineItems = [...this.createTimelineItems(6)] } private createTimelineItems(maxItems: number): Array<tl.ITimelineItem>{ let items: Array<tl.ITimelineItem> = []; for (let i: number = 0; i < maxItems; i++){ items.push(new tl.TimelineItem({ id: i, displayText: `Item ${i.toString()}`, color: i < 2 ? 'primary' : i < 3 ? 'secondary' : i === 3 || i === 5 ? 'test' : 'grey', isActive: i === 0 ? true : false })); } return items; } }
Test new items in timeline
Test new items in timeline
TypeScript
mit
SpikesBE/AngularComponents,SpikesBE/AngularComponents
--- +++ @@ -14,19 +14,26 @@ constructor() { } ngOnInit() { - for (let i: number = 0; i < 5; i++){ - this.timelineItems.push(new tl.TimelineItem({ - id: i, - displayText: `Item ${i.toString()}`, - color: i < 3 ? 'primary' : i === 3 ? 'test' : 'grey', - isActive: i === 0 ? true : false - })); - } + this.timelineItems = [...this.createTimelineItems(5)]; } private onTimelineItemAction(item: tl.ITimelineEventArgs){ console.log('TimelineItem Clicked'); console.log(item); + this.timelineItems = [...this.createTimelineItems(6)] + } + + private createTimelineItems(maxItems: number): Array<tl.ITimelineItem>{ + let items: Array<tl.ITimelineItem> = []; + for (let i: number = 0; i < maxItems; i++){ + items.push(new tl.TimelineItem({ + id: i, + displayText: `Item ${i.toString()}`, + color: i < 2 ? 'primary' : i < 3 ? 'secondary' : i === 3 || i === 5 ? 'test' : 'grey', + isActive: i === 0 ? true : false + })); + } + return items; } }
243c682e2ddd6c87002ee4cce2b3d9f617eace74
lib/hooks/use-route-to.ts
lib/hooks/use-route-to.ts
import isEqual from 'lodash/isEqual' import {useRouter} from 'next/router' import {useCallback, useEffect, useState} from 'react' import {routeTo} from '../router' export default function useRouteTo(to: string, props: any = {}) { const router = useRouter() const [result, setResult] = useState(() => routeTo(to, props)) useEffect(() => { const newRouteTo = routeTo(to, props) if (!isEqual(newRouteTo, result)) { setResult(newRouteTo) // Prefetch in production router.prefetch(newRouteTo.href, newRouteTo.as) } }, [props, result, router, setResult, to]) const onClick = useCallback( (newProps?: any) => { if (newProps && !newProps.nativeEvent) { const newRoute = routeTo(to, newProps) router.push( {pathname: newRoute.href, query: newRoute.query}, newRoute.as ) } else { router.push({pathname: result.href, query: result.query}, result.as) } }, [result, router, to] ) return onClick }
import isEqual from 'lodash/isEqual' import Router from 'next/router' import {useCallback, useEffect, useState} from 'react' import {routeTo} from '../router' export default function useRouteTo(to: string, props: any = {}) { const [result, setResult] = useState(() => routeTo(to, props)) useEffect(() => { const newRouteTo = routeTo(to, props) if (!isEqual(newRouteTo, result)) { setResult(newRouteTo) // Prefetch in production Router.prefetch(newRouteTo.href, newRouteTo.as) } }, [props, result, setResult, to]) const onClick = useCallback( (newProps?: any) => { if (newProps && !newProps.nativeEvent) { const newRoute = routeTo(to, newProps) Router.push( {pathname: newRoute.href, query: newRoute.query}, newRoute.as ) } else { Router.push({pathname: result.href, query: result.query}, result.as) } }, [result, to] ) return onClick }
Fix links coming from toasts
Fix links coming from toasts
TypeScript
mit
conveyal/analysis-ui,conveyal/analysis-ui,conveyal/analysis-ui
--- +++ @@ -1,11 +1,10 @@ import isEqual from 'lodash/isEqual' -import {useRouter} from 'next/router' +import Router from 'next/router' import {useCallback, useEffect, useState} from 'react' import {routeTo} from '../router' export default function useRouteTo(to: string, props: any = {}) { - const router = useRouter() const [result, setResult] = useState(() => routeTo(to, props)) useEffect(() => { @@ -14,23 +13,23 @@ setResult(newRouteTo) // Prefetch in production - router.prefetch(newRouteTo.href, newRouteTo.as) + Router.prefetch(newRouteTo.href, newRouteTo.as) } - }, [props, result, router, setResult, to]) + }, [props, result, setResult, to]) const onClick = useCallback( (newProps?: any) => { if (newProps && !newProps.nativeEvent) { const newRoute = routeTo(to, newProps) - router.push( + Router.push( {pathname: newRoute.href, query: newRoute.query}, newRoute.as ) } else { - router.push({pathname: result.href, query: result.query}, result.as) + Router.push({pathname: result.href, query: result.query}, result.as) } }, - [result, router, to] + [result, to] ) return onClick
6916e8d68a4b7c31da976028fb0835c5e3541f98
A2/quickstart/src/app/models/race-part.model.ts
A2/quickstart/src/app/models/race-part.model.ts
// race-part.model.ts export class RacePart { id: number; name: string; date: Date; about: string; entryFee: number; isRacing: boolean; image: string; imageDescription: string; };
// race-part.model.ts export class RacePart { id: number; name: string; date: Date; about: string; entryFee: number; isRacing: boolean; image: string; imageDescription: string; quantity: number; inStock: number; };
Define two new fields: quantity: number; inStock: number;
Define two new fields: quantity: number; inStock: number;
TypeScript
mit
var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training
--- +++ @@ -9,4 +9,6 @@ isRacing: boolean; image: string; imageDescription: string; + quantity: number; + inStock: number; };
ad97bd7493758e5337b9344a88d35102e0e719db
extensions/typescript-language-features/src/utils/tsconfigProvider.ts
extensions/typescript-language-features/src/utils/tsconfigProvider.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; export interface TSConfig { readonly uri: vscode.Uri; readonly fsPath: string; readonly posixPath: string; readonly workspaceFolder?: vscode.WorkspaceFolder; } export default class TsConfigProvider { public async getConfigsForWorkspace(): Promise<Iterable<TSConfig>> { if (!vscode.workspace.workspaceFolders) { return []; } const configs = new Map<string, TSConfig>(); for (const config of await vscode.workspace.findFiles('**/tsconfig*.json', '**/node_modules/**')) { const root = vscode.workspace.getWorkspaceFolder(config); if (root) { configs.set(config.fsPath, { uri: config, fsPath: config.fsPath, posixPath: config.path, workspaceFolder: root }); } } return configs.values(); } }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; export interface TSConfig { readonly uri: vscode.Uri; readonly fsPath: string; readonly posixPath: string; readonly workspaceFolder?: vscode.WorkspaceFolder; } export default class TsConfigProvider { public async getConfigsForWorkspace(): Promise<Iterable<TSConfig>> { if (!vscode.workspace.workspaceFolders) { return []; } const configs = new Map<string, TSConfig>(); for (const config of await vscode.workspace.findFiles('**/tsconfig*.json', '**/{node_modules,.*}/**')) { const root = vscode.workspace.getWorkspaceFolder(config); if (root) { configs.set(config.fsPath, { uri: config, fsPath: config.fsPath, posixPath: config.path, workspaceFolder: root }); } } return configs.values(); } }
Exclude tsconfig files under dot file directories
Exclude tsconfig files under dot file directories Fixes #88328
TypeScript
mit
joaomoreno/vscode,microsoft/vscode,hoovercj/vscode,eamodio/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,joaomoreno/vscode,eamodio/vscode,Microsoft/vscode,microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,the-ress/vscode,joaomoreno/vscode,the-ress/vscode,eamodio/vscode,the-ress/vscode,Microsoft/vscode,hoovercj/vscode,hoovercj/vscode,microsoft/vscode,the-ress/vscode,Microsoft/vscode,joaomoreno/vscode,Krzysztof-Cieslak/vscode,joaomoreno/vscode,eamodio/vscode,hoovercj/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,hoovercj/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,the-ress/vscode,Microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,hoovercj/vscode,Microsoft/vscode,joaomoreno/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,hoovercj/vscode,the-ress/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,the-ress/vscode,eamodio/vscode,the-ress/vscode,microsoft/vscode,microsoft/vscode,hoovercj/vscode,joaomoreno/vscode,Krzysztof-Cieslak/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Microsoft/vscode,microsoft/vscode,joaomoreno/vscode,eamodio/vscode,joaomoreno/vscode,Microsoft/vscode,the-ress/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,microsoft/vscode,the-ress/vscode,microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,hoovercj/vscode,the-ress/vscode,microsoft/vscode,joaomoreno/vscode,Microsoft/vscode,eamodio/vscode,joaomoreno/vscode,joaomoreno/vscode,hoovercj/vscode,hoovercj/vscode,the-ress/vscode,eamodio/vscode,hoovercj/vscode,joaomoreno/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,hoovercj/vscode,hoovercj/vscode,Microsoft/vscode,eamodio/vscode,the-ress/vscode,eamodio/vscode,eamodio/vscode,the-ress/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,joaomoreno/vscode,joaomoreno/vscode,the-ress/vscode,joaomoreno/vscode,Microsoft/vscode,joaomoreno/vscode,the-ress/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode
--- +++ @@ -18,7 +18,7 @@ return []; } const configs = new Map<string, TSConfig>(); - for (const config of await vscode.workspace.findFiles('**/tsconfig*.json', '**/node_modules/**')) { + for (const config of await vscode.workspace.findFiles('**/tsconfig*.json', '**/{node_modules,.*}/**')) { const root = vscode.workspace.getWorkspaceFolder(config); if (root) { configs.set(config.fsPath, {
88f7f552617e8ec2c32ce7683df56d5007b6f1fa
frontend/src/app/oauth/oauth.component.spec.ts
frontend/src/app/oauth/oauth.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing' import { TranslateModule } from '@ngx-translate/core' import { OAuthComponent } from './oauth.component' describe('OAuthComponent', () => { let component: OAuthComponent let fixture: ComponentFixture<OAuthComponent> beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ OAuthComponent ], imports: [ TranslateModule.forRoot() ] }) .compileComponents() })) beforeEach(() => { fixture = TestBed.createComponent(OAuthComponent) component = fixture.componentInstance fixture.detectChanges() }) xit('should create', () => { expect(component).toBeTruthy() }) })
import { async, ComponentFixture, TestBed } from '@angular/core/testing' import { TranslateModule } from '@ngx-translate/core' import { MatCardModule } from '@angular/material/card' import { MatCheckboxModule } from '@angular/material/checkbox' import { MatFormFieldModule } from '@angular/material/form-field' import { CookieModule } from 'ngx-cookie' import { HttpClientModule } from '@angular/common/http' import { RouterTestingModule } from '@angular/router/testing' import { OAuthComponent } from './oauth.component' import { LoginComponent } from '../login/login.component' describe('OAuthComponent', () => { let component: OAuthComponent let fixture: ComponentFixture<OAuthComponent> beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ OAuthComponent, LoginComponent ], imports: [ RouterTestingModule.withRoutes([ { path: 'login', component: LoginComponent } ] ), CookieModule.forRoot(), TranslateModule.forRoot(), MatCardModule, MatFormFieldModule, MatCheckboxModule, HttpClientModule ] }) .compileComponents() })) beforeEach(() => { fixture = TestBed.createComponent(OAuthComponent) component = fixture.componentInstance fixture.detectChanges() }) it('should create', () => { expect(component).toBeTruthy() }) })
Enable oauth component unit test
Enable oauth component unit test
TypeScript
mit
bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop
--- +++ @@ -1,7 +1,14 @@ import { async, ComponentFixture, TestBed } from '@angular/core/testing' import { TranslateModule } from '@ngx-translate/core' +import { MatCardModule } from '@angular/material/card' +import { MatCheckboxModule } from '@angular/material/checkbox' +import { MatFormFieldModule } from '@angular/material/form-field' +import { CookieModule } from 'ngx-cookie' +import { HttpClientModule } from '@angular/common/http' +import { RouterTestingModule } from '@angular/router/testing' import { OAuthComponent } from './oauth.component' +import { LoginComponent } from '../login/login.component' describe('OAuthComponent', () => { let component: OAuthComponent @@ -9,9 +16,18 @@ beforeEach(async(() => { TestBed.configureTestingModule({ - declarations: [ OAuthComponent ], + declarations: [ OAuthComponent, LoginComponent ], imports: [ - TranslateModule.forRoot() + RouterTestingModule.withRoutes([ + { path: 'login', component: LoginComponent } + ] + ), + CookieModule.forRoot(), + TranslateModule.forRoot(), + MatCardModule, + MatFormFieldModule, + MatCheckboxModule, + HttpClientModule ] }) .compileComponents() @@ -23,7 +39,7 @@ fixture.detectChanges() }) - xit('should create', () => { + it('should create', () => { expect(component).toBeTruthy() }) })
d9f6049cac76661558d3698cc3f85bd0f9dd1fbe
app/app.route.ts
app/app.route.ts
import { Routes, RouterModule } from '@angular/router'; import { TabOneComponent } from './component/tabone.component' import { PendingComponent } from "./component/pending.component"; import {TabTwoComponent} from "./component/tabtwo.component"; import {TabThreeComponent} from "./component/tabthree.component"; import {IdComponent} from "./component/id.component"; const routes: Routes = [ { path: '', redirectTo: '/pending', pathMatch: 'full' }, { path: 'pending', component: PendingComponent }, { path: 'tabone', component: TabOneComponent }, { path: 'tabtwo', component: TabTwoComponent }, { path: 'tabthree', component: TabThreeComponent }, { path: 'id', component: IdComponent } ] export const routing = RouterModule.forRoot(routes);
import { Routes, RouterModule } from '@angular/router'; import { TabOneComponent } from './component/tabone.component' import { PendingComponent } from "./component/pending.component"; import {TabTwoComponent} from "./component/tabtwo.component"; import {TabThreeComponent} from "./component/tabthree.component"; import {IdComponent} from "./component/id.component"; const routes: Routes = [ { path: '', redirectTo: '/pending', pathMatch: 'full' }, { path: 'pending', component: PendingComponent }, { path: 'tabone', component: TabOneComponent }, { path: 'tabtwo', component: TabTwoComponent }, { path: 'tabthree', component: TabThreeComponent }, { path: 'id', component: IdComponent } ] export const routing = RouterModule.forRoot(routes); //
Revert "test commit from another machine"
Revert "test commit from another machine" This reverts commit 240b6fbb29cba85c1e1b2e453b2152e93dcb1af0.
TypeScript
mit
blindacai/Angular2-Web,blindacai/Angular2-Web,blindacai/Angular2-Web
--- +++ @@ -36,3 +36,4 @@ export const routing = RouterModule.forRoot(routes); +//
3187fa53d492f99b9e834ac76b12e092d1984131
src/app/core/import/import/import-catalog.ts
src/app/core/import/import/import-catalog.ts
import {Document} from 'idai-components-2'; import {DocumentDatastore} from '../../datastore/document-datastore'; export async function importCatalog(documents: Array<Document>, datastore: DocumentDatastore, username: string): Promise<{ errors: string[][], successfulImports: number }> { console.log('import catalog', documents); return { errors: [], successfulImports: documents.length }; }
import {Document} from 'idai-components-2'; import {DocumentDatastore} from '../../datastore/document-datastore'; import {update} from 'tsfun'; import {DatastoreErrors} from '../../datastore/model/datastore-errors'; // TODO batch import for speed /** * @param documents * @param datastore * @param username * * @author Daniel de Oliveira */ export async function importCatalog(documents: Array<Document>, datastore: DocumentDatastore, username: string): Promise<{ errors: string[][], successfulImports: number }> { let successfulImports = 0; for (let document of documents) { delete document[Document._REV]; delete document['modified']; delete document['created']; try { const existingDocument: Document = await datastore.get(document.resource.id); const updateDocument = update(Document.RESOURCE, document.resource, existingDocument); await datastore.update(updateDocument, username); } catch ([err]) { if (err === DatastoreErrors.DOCUMENT_NOT_FOUND) { document['readonly'] = true; // TODO let app react to that, for example by prohibiting editing await datastore.create(document, username); } else { // TODO what about the already imported ones? return { errors: [[DatastoreErrors.DOCUMENT_NOT_FOUND]], successfulImports: successfulImports } } } successfulImports++; } return { errors: [], successfulImports: successfulImports }; }
Implement preliminary version of importCatalog
Implement preliminary version of importCatalog
TypeScript
apache-2.0
codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client
--- +++ @@ -1,11 +1,43 @@ import {Document} from 'idai-components-2'; import {DocumentDatastore} from '../../datastore/document-datastore'; +import {update} from 'tsfun'; +import {DatastoreErrors} from '../../datastore/model/datastore-errors'; +// TODO batch import for speed +/** + * @param documents + * @param datastore + * @param username + * + * @author Daniel de Oliveira + */ export async function importCatalog(documents: Array<Document>, datastore: DocumentDatastore, username: string): Promise<{ errors: string[][], successfulImports: number }> { - console.log('import catalog', documents); - return { errors: [], successfulImports: documents.length }; + let successfulImports = 0; + for (let document of documents) { + delete document[Document._REV]; + delete document['modified']; + delete document['created']; + + try { + const existingDocument: Document = await datastore.get(document.resource.id); + const updateDocument = update(Document.RESOURCE, document.resource, existingDocument); + await datastore.update(updateDocument, username); + } catch ([err]) { + if (err === DatastoreErrors.DOCUMENT_NOT_FOUND) { + document['readonly'] = true; // TODO let app react to that, for example by prohibiting editing + await datastore.create(document, username); + } else { + // TODO what about the already imported ones? + return { errors: [[DatastoreErrors.DOCUMENT_NOT_FOUND]], successfulImports: successfulImports } + } + } + + successfulImports++; + } + + return { errors: [], successfulImports: successfulImports }; }
096813cc74048dfc3c537fb40446d4e71a17a5e4
src/browser/offline-support/ServiceWorker.ts
src/browser/offline-support/ServiceWorker.ts
import { EventEmitter } from "events"; type ConstructorParams = { url: string; }; export default class { public readonly events = new EventEmitter(); public enabled: boolean; private _status: string; constructor({ url }: ConstructorParams) { this.enabled = false; this.status = ""; if (!navigator.serviceWorker) { this.status = "not supported"; return; } if (navigator.serviceWorker.controller) { this.enabled = true; } else { this.status = "enabling..."; } (async () => { try { await navigator.serviceWorker.register(url, { scope: ".." }); } catch (error) { this.status = `${error}`; } finally { if (navigator.serviceWorker.controller) { this.status = ""; } else { // With a reload the service worker will take control of the page and // it will cache the page resources. this.status = "reload to cache content"; } } })(); } set status(status) { this._status = status; this.events.emit("change"); } get status() { return this._status; } }
import { EventEmitter } from "events"; type ConstructorParams = { url: string; }; export default class { public readonly events = new EventEmitter(); public enabled: boolean; private _status: string; constructor({ url }: ConstructorParams) { this.enabled = false; this.status = ""; if (!navigator.serviceWorker) { this.status = "not supported"; return; } if (navigator.serviceWorker.controller) { this.enabled = true; } else { this.status = "enabling..."; } (async () => { try { await navigator.serviceWorker.register(url, { scope: ".." }); if (navigator.serviceWorker.controller) { this.status = ""; } else { // With a reload the service worker will take control of the page and // it will cache the page resources. this.status = "reload to cache content"; } } catch (error) { this.status = `${error}`; } })(); } set status(status) { this._status = status; this.events.emit("change"); } get status() { return this._status; } }
Fix navigator.serviceWorker.register() errors not showing up
Fix navigator.serviceWorker.register() errors not showing up
TypeScript
mit
frosas/lag,frosas/lag,frosas/lag
--- +++ @@ -29,9 +29,6 @@ await navigator.serviceWorker.register(url, { scope: ".." }); - } catch (error) { - this.status = `${error}`; - } finally { if (navigator.serviceWorker.controller) { this.status = ""; } else { @@ -39,6 +36,8 @@ // it will cache the page resources. this.status = "reload to cache content"; } + } catch (error) { + this.status = `${error}`; } })(); }
162a5bdd9707898f6b8b67fa130d66a6a2f0605d
app/reducers.ts
app/reducers.ts
/** * Combine all reducers in this file and export the combined reducers. * If we were to do this in store.js, reducers wouldn't be hot reloadable. */ import { fromJS } from 'immutable'; import { combineReducers } from 'redux-immutable'; import { LOCATION_CHANGE } from 'react-router-redux'; import Redux from 'redux'; import globalReducer from 'app/containers/App/reducer'; import languageProviderReducer from 'app/containers/LanguageProvider/reducer'; /* * routeReducer * * The reducer merges route location changes into our immutable state. * The change is necessitated by moving to react-router-redux@4 * */ // Initial routing state const routeInitialState = fromJS({ locationBeforeTransitions: null, }); /** * Merge route into the global application state */ function routeReducer(state = routeInitialState, action) { switch (action.type) { /* istanbul ignore next */ case LOCATION_CHANGE: const mergeState = state.merge({ locationBeforeTransitions: action.payload, }); console.log(action, window.swUpdate); if (window.swUpdate) { window.location.reload(); } return mergeState; default: return state; } } /** * Creates the main reducer with the asynchronously loaded ones */ export default function createReducer(asyncReducers: Redux.ReducersMapObject = {}): Redux.Reducer<any> { const reducers = { route: routeReducer, global: globalReducer, language: languageProviderReducer, ...asyncReducers, }; return combineReducers(reducers); }
/** * Combine all reducers in this file and export the combined reducers. * If we were to do this in store.js, reducers wouldn't be hot reloadable. */ import { fromJS } from 'immutable'; import { combineReducers } from 'redux-immutable'; import { LOCATION_CHANGE } from 'react-router-redux'; import Redux from 'redux'; import globalReducer from 'app/containers/App/reducer'; import languageProviderReducer from 'app/containers/LanguageProvider/reducer'; /* * routeReducer * * The reducer merges route location changes into our immutable state. * The change is necessitated by moving to react-router-redux@4 * */ // Initial routing state const routeInitialState = fromJS({ locationBeforeTransitions: null, }); /** * Merge route into the global application state */ function routeReducer(state = routeInitialState, action) { switch (action.type) { /* istanbul ignore next */ case LOCATION_CHANGE: const mergeState = state.merge({ locationBeforeTransitions: action.payload, }); if (window.swUpdate) { window.location.reload(); } return mergeState; default: return state; } } /** * Creates the main reducer with the asynchronously loaded ones */ export default function createReducer(asyncReducers: Redux.ReducersMapObject = {}): Redux.Reducer<any> { const reducers = { route: routeReducer, global: globalReducer, language: languageProviderReducer, ...asyncReducers, }; return combineReducers(reducers); }
Remove a console.log for debugging OfflinePlugin auto update
Remove a console.log for debugging OfflinePlugin auto update
TypeScript
mit
StrikeForceZero/react-typescript-boilerplate,StrikeForceZero/react-typescript-boilerplate,StrikeForceZero/react-typescript-boilerplate
--- +++ @@ -34,7 +34,6 @@ const mergeState = state.merge({ locationBeforeTransitions: action.payload, }); - console.log(action, window.swUpdate); if (window.swUpdate) { window.location.reload(); }
f5c6ed4c1d1136ae6a9d8b4e1f25f98819533730
test/runTests.ts
test/runTests.ts
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // NOTE: This code is borrowed under permission from: // https://github.com/microsoft/vscode-extension-samples/tree/main/helloworld-test-sample/src/test import * as path from "path"; import { runTests } from "@vscode/test-electron"; async function main() { try { // The folder containing the Extension Manifest package.json // Passed to `--extensionDevelopmentPath` const extensionDevelopmentPath = path.resolve(__dirname, "../../"); // The path to the extension test script // Passed to --extensionTestsPath const extensionTestsPath = path.resolve(__dirname, "./index"); // Download VS Code, unzip it and run the integration test await runTests({ extensionDevelopmentPath, extensionTestsPath, launchArgs: ["--disable-extensions", "./test"], // This is necessary because the tests fail if more than once // instance of Code is running. version: "insiders" }); } catch (err) { // tslint:disable-next-line:no-console console.error("Failed to run tests"); process.exit(1); } } main();
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // NOTE: This code is borrowed under permission from: // https://github.com/microsoft/vscode-extension-samples/tree/main/helloworld-test-sample/src/test import * as path from "path"; import { runTests } from "@vscode/test-electron"; async function main() { try { // The folder containing the Extension Manifest package.json // Passed to `--extensionDevelopmentPath` const extensionDevelopmentPath = path.resolve(__dirname, "../../"); // The path to the extension test script // Passed to --extensionTestsPath const extensionTestsPath = path.resolve(__dirname, "./index"); // Download VS Code, unzip it and run the integration test await runTests({ extensionDevelopmentPath, extensionTestsPath, launchArgs: ["--disable-extensions", "./test"], // This is necessary because the tests fail if more than once // instance of Code is running. version: "insiders" }); } catch (err) { // tslint:disable-next-line:no-console console.error(`Failed to run tests: ${err}`); process.exit(1); } } main();
Print error when tests fail
Print error when tests fail
TypeScript
mit
PowerShell/vscode-powershell
--- +++ @@ -29,7 +29,7 @@ }); } catch (err) { // tslint:disable-next-line:no-console - console.error("Failed to run tests"); + console.error(`Failed to run tests: ${err}`); process.exit(1); } }
ba6f13cbdf4d9bd9d883bd6ba452dcb75706c7e0
src/app/app.routing.ts
src/app/app.routing.ts
import {Routes, RouterModule} from '@angular/router'; import {HomeComponent} from "./home/home.component"; import {ModuleWithProviders} from "@angular/core"; import {LifecycleComponent} from "./lifecycle/lifecycle.component"; import {ShowcaseComponent} from "./showcase/showcase.component"; import {ProductListComponent} from "./productList/productList.component"; import {ProductDetailsComponent} from "./productDetails/productDetails.component"; const appRoutes:Routes = [ {path: 'home', component: HomeComponent}, {path: 'lifecycle', component: LifecycleComponent}, {path: 'lifecycle/:type', component: LifecycleComponent}, {path: 'showcase', component: ShowcaseComponent}, {path: 'productList/:type', component: ProductListComponent}, {path: 'productList/:type/productDetails/:id', component: ProductDetailsComponent}, {path: '', redirectTo: '/home', pathMatch: 'full' }, {path: '**', redirectTo: '/home', pathMatch: 'full'} ]; export const appRoutingProviders:any[] = []; export const routing:ModuleWithProviders = RouterModule.forRoot(appRoutes, {useHash: true});
import {Routes, RouterModule} from '@angular/router'; import {HomeComponent} from "./home/home.component"; import {ModuleWithProviders} from "@angular/core"; import {LifecycleComponent} from "./lifecycle/lifecycle.component"; import {ShowcaseComponent} from "./showcase/showcase.component"; import {ProductListComponent} from "./productList/productList.component"; import {ProductDetailsComponent} from "./productDetails/productDetails.component"; import {ComingSoonComponent} from "./comingSoon/comingSoon.component"; const appRoutes:Routes = [ {path: 'home', component: HomeComponent}, {path: 'guides', component: ComingSoonComponent}, {path: 'policies', component: ComingSoonComponent}, {path: 'showcase', component: ComingSoonComponent}, {path: 'lifecycle', component: LifecycleComponent}, {path: 'lifecycle/:id', component: LifecycleComponent}, {path: 'showcase', component: ShowcaseComponent}, {path: 'productList/:type', component: ProductListComponent}, {path: 'productList/:type/:serviceTypeId', component: ProductListComponent}, {path: 'productList/:type/productDetails/:id', component: ProductDetailsComponent}, {path: '', redirectTo: '/home', pathMatch: 'full' }, {path: '**', redirectTo: '/home', pathMatch: 'full'} ]; export const appRoutingProviders:any[] = []; export const routing:ModuleWithProviders = RouterModule.forRoot(appRoutes, {useHash: true});
Update routes to enable specification of parameters for taxonomy types.
Update routes to enable specification of parameters for taxonomy types.
TypeScript
bsd-3-clause
UoA-eResearch/research-hub,UoA-eResearch/research-hub,UoA-eResearch/research-hub
--- +++ @@ -5,13 +5,18 @@ import {ShowcaseComponent} from "./showcase/showcase.component"; import {ProductListComponent} from "./productList/productList.component"; import {ProductDetailsComponent} from "./productDetails/productDetails.component"; +import {ComingSoonComponent} from "./comingSoon/comingSoon.component"; const appRoutes:Routes = [ {path: 'home', component: HomeComponent}, + {path: 'guides', component: ComingSoonComponent}, + {path: 'policies', component: ComingSoonComponent}, + {path: 'showcase', component: ComingSoonComponent}, {path: 'lifecycle', component: LifecycleComponent}, - {path: 'lifecycle/:type', component: LifecycleComponent}, + {path: 'lifecycle/:id', component: LifecycleComponent}, {path: 'showcase', component: ShowcaseComponent}, {path: 'productList/:type', component: ProductListComponent}, + {path: 'productList/:type/:serviceTypeId', component: ProductListComponent}, {path: 'productList/:type/productDetails/:id', component: ProductDetailsComponent}, {path: '', redirectTo: '/home', pathMatch: 'full' }, {path: '**', redirectTo: '/home', pathMatch: 'full'}
8dd865dcd58dbba9d7fb02454d9702d7e9e246c8
src/services/window.ts
src/services/window.ts
/* Copyright 2017 Geoloep Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ export type IStateChangeCallback = (newState: string) => void; export class WindowService { state: string; stateChangeCallbacks: IStateChangeCallback[] = []; constructor(public breakpoint = 911) { this.setState(); window.onresize = this.setState; } onStateChange(func: IStateChangeCallback) { this.stateChangeCallbacks.push(func); func(this.state); } private stateChange(newState: string) { if (newState !== this.state) { this.state = newState; this.stateChanged(); } } private stateChanged() { for (const callback of this.stateChangeCallbacks) { callback(this.state); } } private setState = () => { if (window.innerWidth > this.breakpoint) { this.stateChange('wide'); } else { this.stateChange('narrow'); } } }
/* Copyright 2017 Geoloep Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ export type IStateChangeCallback = (newState: string) => void; export class WindowService { state: string; stateChangeCallbacks: IStateChangeCallback[] = []; constructor(public breakpoint = 991) { this.setState(); window.onresize = this.setState; } onStateChange(func: IStateChangeCallback) { this.stateChangeCallbacks.push(func); func(this.state); } private stateChange(newState: string) { if (newState !== this.state) { this.state = newState; this.stateChanged(); } } private stateChanged() { for (const callback of this.stateChangeCallbacks) { callback(this.state); } } private setState = () => { if (window.innerWidth > this.breakpoint) { this.stateChange('wide'); } else { this.stateChange('narrow'); } } }
Bring default break point in line with bootstrap
Bring default break point in line with bootstrap
TypeScript
apache-2.0
geoloep/krite,geoloep/krite,geoloep/krite
--- +++ @@ -20,7 +20,7 @@ state: string; stateChangeCallbacks: IStateChangeCallback[] = []; - constructor(public breakpoint = 911) { + constructor(public breakpoint = 991) { this.setState(); window.onresize = this.setState;
6268ba3ecc003016d0ad9524a8f99f813fe2db2d
src/SyntaxNodes/RichInlineSyntaxNode.ts
src/SyntaxNodes/RichInlineSyntaxNode.ts
import { InlineSyntaxNode } from './InlineSyntaxNode' export abstract class RichInlineSyntaxNode implements InlineSyntaxNode { constructor(public children: InlineSyntaxNode[]) { } INLINE_SYNTAX_NODE(): void { } protected RICH_INLINE_SYNTAX_NODE(): void { } }
import { InlineSyntaxNode } from './InlineSyntaxNode' import { InlineSyntaxNodeContainer } from './InlineSyntaxNodeContainer' export abstract class RichInlineSyntaxNode implements InlineSyntaxNode, InlineSyntaxNodeContainer { constructor(public children: InlineSyntaxNode[]) { } INLINE_SYNTAX_NODE(): void { } protected RICH_INLINE_SYNTAX_NODE(): void { } }
Make rich inline node explicitly impl. container
Make rich inline node explicitly impl. container
TypeScript
mit
start/up,start/up
--- +++ @@ -1,7 +1,8 @@ import { InlineSyntaxNode } from './InlineSyntaxNode' +import { InlineSyntaxNodeContainer } from './InlineSyntaxNodeContainer' -export abstract class RichInlineSyntaxNode implements InlineSyntaxNode { +export abstract class RichInlineSyntaxNode implements InlineSyntaxNode, InlineSyntaxNodeContainer { constructor(public children: InlineSyntaxNode[]) { } INLINE_SYNTAX_NODE(): void { }
df6d7210c2b9c1a4292da3ed0c853b1b98163025
src/js/components/next-up/index.jsx
src/js/components/next-up/index.jsx
import debug from "debug"; import React, { Component } from "react"; import Track from "../track"; const log = debug("schedule:components:next-up"); export class NextUp extends Component { render() { const { getState } = this.props; const { days, time: { today, now } } = getState(); let currentDay = Object.keys(days).filter(d => today <= new Date(d)).shift(); let tracks = Object.keys(days[currentDay].tracks).map(name => ({ name, sessions: days[currentDay].tracks[name] })); let nextSessions = tracks.map(t => { return { ...t, sessions: [t.sessions.filter(s => now <= s.start).shift()] }; }). sort((a, b) => { return Number(a.sessions[0].start) - Number(b.sessions[0].start); }); return ( <div className="next-up"> { nextSessions.map(t => { return ( <div key={t.name} className="next-up__session"> <Track { ...t } /> </div> ); }) } </div> ); } } export default NextUp;
import debug from "debug"; import React, { Component } from "react"; import Track from "../track"; const log = debug("schedule:components:next-up"); export class NextUp extends Component { render() { const { getState } = this.props; const { days, time: { today, now } } = getState(); let currentDay = Object.keys(days).filter(d => today <= new Date(d)).shift(); let tracks = Object.keys(days[currentDay].tracks).map(name => ({ name, sessions: days[currentDay].tracks[name] })); let nextSessions = tracks.map(t => { return { ...t, sessions: [t.sessions.filter(s => now <= s.start).shift()] }; }). sort((a, b) => { return Number(a.sessions[0].start) - Number(b.sessions[0].start); }); return ( <div className="next-up"> { nextSessions.map(t => { return ( <div key={t.name} className="next-up__track"> <Track { ...t } /> </div> ); }) } </div> ); } } export default NextUp;
Fix correct classname for track element in next-up
Fix correct classname for track element in next-up
JSX
mit
nikcorg/schedule,orangecms/schedule,nikcorg/schedule,nikcorg/schedule,orangecms/schedule,orangecms/schedule
--- +++ @@ -27,7 +27,7 @@ { nextSessions.map(t => { return ( - <div key={t.name} className="next-up__session"> + <div key={t.name} className="next-up__track"> <Track { ...t } /> </div> );
f375130190844f0d0813b0e8dca1bf25fbcf966f
src/components/forms/input.jsx
src/components/forms/input.jsx
const bindAll = require('lodash.bindall'); const classNames = require('classnames'); const FRCInput = require('formsy-react-components').Input; const omit = require('lodash.omit'); const PropTypes = require('prop-types'); const React = require('react'); const defaultValidationHOC = require('./validations.jsx').defaultValidationHOC; const inputHOC = require('./input-hoc.jsx'); require('./input.scss'); require('./row.scss'); class Input extends React.Component { constructor (props) { super(props); bindAll(this, [ 'handleInvalid', 'handleValid' ]); this.state = { status: '' }; } handleValid () { this.setState({ status: 'pass' }); } handleInvalid () { this.setState({ status: 'fail' }); } render () { return ( <FRCInput className="input" rowClassName={classNames( this.state.status, this.props.className, {'no-label': (typeof this.props.label === 'undefined')} )} onInvalid={this.handleInvalid} onValid={this.handleValid} {...omit(this.props, ['className'])} /> ); } } Input.propTypes = { className: PropTypes.string, label: PropTypes.string }; module.exports = inputHOC(defaultValidationHOC(Input));
const classNames = require('classnames'); const FRCInput = require('formsy-react-components').Input; const omit = require('lodash.omit'); const PropTypes = require('prop-types'); const React = require('react'); const defaultValidationHOC = require('./validations.jsx').defaultValidationHOC; const inputHOC = require('./input-hoc.jsx'); require('./input.scss'); require('./row.scss'); const Input = props => ( <FRCInput className="input" rowClassName={classNames( props.className, {'no-label': (typeof props.label === 'undefined')} )} {...omit(props, ['className'])} /> ); Input.propTypes = { className: PropTypes.string, label: PropTypes.string }; module.exports = inputHOC(defaultValidationHOC(Input));
Remove unrecognized props from Input
Remove unrecognized props from Input In the process, make Input into a stateless component, since apparently this state isn't ever changed.
JSX
bsd-3-clause
LLK/scratch-www,LLK/scratch-www
--- +++ @@ -1,4 +1,3 @@ -const bindAll = require('lodash.bindall'); const classNames = require('classnames'); const FRCInput = require('formsy-react-components').Input; const omit = require('lodash.omit'); @@ -11,43 +10,16 @@ require('./input.scss'); require('./row.scss'); -class Input extends React.Component { - constructor (props) { - super(props); - bindAll(this, [ - 'handleInvalid', - 'handleValid' - ]); - this.state = { - status: '' - }; - } - handleValid () { - this.setState({ - status: 'pass' - }); - } - handleInvalid () { - this.setState({ - status: 'fail' - }); - } - render () { - return ( - <FRCInput - className="input" - rowClassName={classNames( - this.state.status, - this.props.className, - {'no-label': (typeof this.props.label === 'undefined')} - )} - onInvalid={this.handleInvalid} - onValid={this.handleValid} - {...omit(this.props, ['className'])} - /> - ); - } -} +const Input = props => ( + <FRCInput + className="input" + rowClassName={classNames( + props.className, + {'no-label': (typeof props.label === 'undefined')} + )} + {...omit(props, ['className'])} + /> +); Input.propTypes = { className: PropTypes.string,
919fe31086f37f1938840e707e0fb41051e33e66
frontend/src/metabase/components/EditBar.jsx
frontend/src/metabase/components/EditBar.jsx
import React, { Component } from 'react'; import PropTypes from "prop-types"; import cx from "classnames"; class EditBar extends Component { static propTypes = { title: PropTypes.string.isRequired, subtitle: PropTypes.string, buttons: PropTypes.oneOfType([ PropTypes.element, PropTypes.array ]).isRequired, admin: PropTypes.bool } static defaultProps = { admin: false } render () { const { admin, buttons, subtitle, title } = this.props; return ( <div className={cx( 'EditHeader wrapper py1 flex align-center', { 'EditHeader--admin' : admin } )} ref="editHeader" > <span className="EditHeader-title">{title}</span> { subtitle && ( <span className="EditHeader-subtitle mx1"> {subtitle} </span> )} <span className="flex-align-right"> {buttons} </span> </div> ) } } export default EditBar;
import React, { Component } from 'react'; import PropTypes from "prop-types"; import cx from "classnames"; class EditBar extends Component { static propTypes = { title: PropTypes.string.isRequired, subtitle: PropTypes.string, buttons: PropTypes.oneOfType([ PropTypes.element, PropTypes.array ]).isRequired, admin: PropTypes.bool } static defaultProps = { admin: false } render () { const { admin, buttons, subtitle, title } = this.props; return ( <div className={cx( 'EditHeader wrapper py1 flex align-center', { 'EditHeader--admin' : admin } )} ref="editHeader" > <span className="EditHeader-title">{title}</span> { subtitle && ( <span className="EditHeader-subtitle mx1"> {subtitle} </span> )} <span className="flex-align-right flex"> {buttons} </span> </div> ) } } export default EditBar;
Use `display: flex` for edit bar buttons, fixes IE11 layout glitch
Use `display: flex` for edit bar buttons, fixes IE11 layout glitch
JSX
agpl-3.0
blueoceanideas/metabase,blueoceanideas/metabase,blueoceanideas/metabase,blueoceanideas/metabase,blueoceanideas/metabase
--- +++ @@ -33,7 +33,7 @@ {subtitle} </span> )} - <span className="flex-align-right"> + <span className="flex-align-right flex"> {buttons} </span> </div>
288c619581961262443bed224028154e45772970
src/HashLink.jsx
src/HashLink.jsx
import _hashLink from './_hashLink'; import animateScroll from './scroll'; import React from 'react'; function _animateScroll(event, animate) { event.preventDefault(); const hash = event.target.getAttribute('href'); animateScroll(hash, animate); } export default function HashLink(props) { return <_hashLink {...props} animateScroll={_animateScroll} />; }
import _hashLink from './_hashLink'; import animateScroll from './scroll'; import React from 'react'; function _animateScroll(event, animate) { event.preventDefault(); const hash = event.target.hash; animateScroll(hash, animate); } export default function HashLink(props) { return <_hashLink {...props} animateScroll={_animateScroll} />; }
Use hash attribute instead of full href
Use hash attribute instead of full href Allow more than just the hash passed to the href attribute
JSX
mit
bySabi/react-router-hash-scroll
--- +++ @@ -4,7 +4,7 @@ function _animateScroll(event, animate) { event.preventDefault(); - const hash = event.target.getAttribute('href'); + const hash = event.target.hash; animateScroll(hash, animate); }
70ab29ce93a4c94e86190b3f94b53ad20d305395
src/components/App.jsx
src/components/App.jsx
import React, {Component} from 'react'; import {Col, Navbar} from 'react-bootstrap'; import LC3 from '../core/lc3'; import MemoryView from './memory/MemoryView'; export default class App extends Component { constructor() { super(); this.state = { lc3: LC3() }; } render() { return <div> <Navbar brand="LC-3 Simulator" inverse staticTop /> <div className="container"> <Col md={6}> <MemoryView />; </Col> </div> </div>; } }
import React, {Component} from 'react'; import {Col, Navbar} from 'react-bootstrap'; import LC3 from '../core/lc3'; import MemoryView from './memory/MemoryView'; export default class App extends Component { render() { return <div> <Navbar brand="LC-3 Simulator" inverse staticTop /> <div className="container"> <Col md={6}> <MemoryView />; </Col> </div> </div>; } }
Remove legacy constructor in main app
Remove legacy constructor in main app
JSX
mit
WChargin/lc3,WChargin/lc3
--- +++ @@ -5,13 +5,6 @@ import MemoryView from './memory/MemoryView'; export default class App extends Component { - - constructor() { - super(); - this.state = { - lc3: LC3() - }; - } render() { return <div>
3b874cb26b038d3d477afe90e810ecfff0f7b2c6
src/App.jsx
src/App.jsx
import React, { Component } from "react"; import GoogleAnalytics from "react-ga"; import { BrowserRouter, Route } from "react-router-dom"; import ListPage from "./ListPage"; import RunPage from "./RunPage"; import config from "./config"; import "./App.css"; class App extends Component { constructor(props) { super(props); if (config.GOOGLE_ANALYTICS_CODE) { GoogleAnalytics.initialize(config.GOOGLE_ANALYTICS_CODE); } } render() { return ( <BrowserRouter> <div className="App"> <Route exact path="/" component={ListPage} /> <Route exact path="/run/:rom" component={RunPage} /> <Route path="/" render={this.recordPageview} /> </div> </BrowserRouter> ); } recordPageview = ({location}) => { GoogleAnalytics.pageview(location.pathname); return null; }; } export default App;
import React, { Component } from "react"; import GoogleAnalytics from "react-ga"; import { BrowserRouter, Route } from "react-router-dom"; import ListPage from "./ListPage"; import RunPage from "./RunPage"; import config from "./config"; import "./App.css"; class App extends Component { constructor(props) { super(props); if (config.GOOGLE_ANALYTICS_CODE) { GoogleAnalytics.initialize(config.GOOGLE_ANALYTICS_CODE); } } render() { return ( <BrowserRouter> <div className="App"> <Route exact path="/" component={ListPage} /> <Route exact path="/run" component={RunPage} /> <Route exact path="/run/:rom" component={RunPage} /> <Route path="/" render={this.recordPageview} /> </div> </BrowserRouter> ); } recordPageview = ({location}) => { GoogleAnalytics.pageview(location.pathname); return null; }; } export default App;
Add route for drag & drop ROMs
Add route for drag & drop ROMs
JSX
apache-2.0
bfirsh/jsnes-web,bfirsh/jsnes-web
--- +++ @@ -19,6 +19,7 @@ <BrowserRouter> <div className="App"> <Route exact path="/" component={ListPage} /> + <Route exact path="/run" component={RunPage} /> <Route exact path="/run/:rom" component={RunPage} /> <Route path="/" render={this.recordPageview} /> </div>
57659acef580024c8789a4360ae532e465e8e0c7
client/src/Dashboard.jsx
client/src/Dashboard.jsx
import React from 'react'; import VizFlowsSankey from './VizFlowsSankey'; import promisedComponent from './promisedComponent'; class Dashboard extends React.Component { componentDidMount() { document.title = "LedgerDB"; } render() { return ( <div> {React.createElement(promisedComponent(VizFlowsSankey))} </div> ); } } export default Dashboard;
import React from 'react'; import VizFlowsSankey from './VizFlowsSankey'; import promisedComponent from './promisedComponent'; class Dashboard extends React.PureComponent { componentDidMount() { document.title = "LedgerDB"; } render() { return ( <div> {React.createElement(promisedComponent(VizFlowsSankey))} </div> ); } } export default Dashboard;
Fix javascript warning with React.PureComponent
Fix javascript warning with React.PureComponent
JSX
bsd-2-clause
sashaanderson/ledgerdb,comme-il-faut/ledgerdb,sashaanderson/ledgerdb,sashaanderson/ledgerdb,comme-il-faut/ledgerdb,sashaanderson/ledgerdb,comme-il-faut/ledgerdb
--- +++ @@ -3,7 +3,7 @@ import VizFlowsSankey from './VizFlowsSankey'; import promisedComponent from './promisedComponent'; -class Dashboard extends React.Component { +class Dashboard extends React.PureComponent { componentDidMount() { document.title = "LedgerDB";
90c839ac6efbf3d4d52caf0fac53e0a7e94e2ef0
src/react-chayns-badge/component/Badge.jsx
src/react-chayns-badge/component/Badge.jsx
import classNames from 'classnames'; import PropTypes from 'prop-types'; import React, { forwardRef, useCallback, useState } from 'react'; const Badge = forwardRef(({ children, className, ...other }, ref) => { const [minWidth, setMinWidth] = useState(); const measureRef = useCallback((node) => { if (node) { setMinWidth(node.getBoundingClientRect().height); } }, []); return ( <div className={classNames(className, 'badge')} ref={(node) => { measureRef(node); if (ref) { ref(node); } }} style={{ minWidth }} {...other} > {children} </div> ); }); export default Badge; Badge.propTypes = { children: PropTypes.node.isRequired, className: PropTypes.string, badgeRef: PropTypes.func, }; Badge.defaultProps = { className: '', badgeRef: null, }; Badge.displayName = 'Badge';
import classNames from 'classnames'; import PropTypes from 'prop-types'; import React, { forwardRef, useCallback, useState } from 'react'; const Badge = forwardRef(({ children, className, ...other }, ref) => { const [minWidth, setMinWidth] = useState(); const measureRef = useCallback((node) => { if (node) { setMinWidth(node.getBoundingClientRect().height); } }, []); return ( <div className={classNames(className, 'badge')} ref={(node) => { measureRef(node); if (ref) { ref(node); } }} style={{ minWidth }} {...other} > {children} </div> ); }); export default Badge; Badge.propTypes = { children: PropTypes.node.isRequired, className: PropTypes.string, }; Badge.defaultProps = { className: '', }; Badge.displayName = 'Badge';
Update proptypes due to forwardRef change
:label: Update proptypes due to forwardRef change
JSX
mit
TobitSoftware/chayns-components,TobitSoftware/chayns-components,TobitSoftware/chayns-components
--- +++ @@ -33,12 +33,10 @@ Badge.propTypes = { children: PropTypes.node.isRequired, className: PropTypes.string, - badgeRef: PropTypes.func, }; Badge.defaultProps = { className: '', - badgeRef: null, }; Badge.displayName = 'Badge';
75d9cbd5b41ed66ff6e4897d1e68a5471aaf00e8
src/client/components/autocomplete2/inline_list.jsx
src/client/components/autocomplete2/inline_list.jsx
import PropTypes from 'prop-types' import React, { Component } from 'react' import { Autocomplete } from '/client/components/autocomplete2/index' export class AutocompleteInlineList extends Component { static propTypes = { className: PropTypes.string, disabled: PropTypes.bool, filter: PropTypes.func, formatSelected: PropTypes.func, formatSearchResult: PropTypes.func, items: PropTypes.array, onSelect: PropTypes.func, placeholder: PropTypes.string, url: PropTypes.string } onRemoveItem = (item) => { const { items, onSelect } = this.props const newItems = items newItems.splice(item, 1) onSelect(newItems) } render () { const { items, className } = this.props return ( <div className={`Autocomplete--inline ${className ? className : ''}`}> <div className='Autocomplete__list'> {items.map((item, i) => { return ( <div className='Autocomplete__list-item' key={i} > {item} <button onClick={() => this.onRemoveItem(i)} /> </div> ) })} </div> <Autocomplete {...this.props} /> </div> ) } } AutocompleteInlineList.defaultProps = { items: [] }
import PropTypes from 'prop-types' import React, { Component } from 'react' import { Autocomplete } from '/client/components/autocomplete2/index' import { clone } from 'lodash' export class AutocompleteInlineList extends Component { static propTypes = { className: PropTypes.string, disabled: PropTypes.bool, filter: PropTypes.func, formatSelected: PropTypes.func, formatSearchResult: PropTypes.func, items: PropTypes.array, onSelect: PropTypes.func, placeholder: PropTypes.string, url: PropTypes.string } onRemoveItem = (item) => { const { items, onSelect } = this.props const newItems = clone(items) newItems.splice(item, 1) onSelect(newItems) } render () { const { items, className } = this.props return ( <div className={`Autocomplete--inline ${className ? className : ''}`}> <div className='Autocomplete__list'> {items.map((item, i) => { return ( <div className='Autocomplete__list-item' key={i} > {item} <button onClick={() => this.onRemoveItem(i)} /> </div> ) })} </div> <Autocomplete {...this.props} /> </div> ) } } AutocompleteInlineList.defaultProps = { items: [] }
Fix bug with removing inline-list
Fix bug with removing inline-list
JSX
mit
artsy/positron,craigspaeth/positron,eessex/positron,eessex/positron,craigspaeth/positron,artsy/positron,craigspaeth/positron,eessex/positron,artsy/positron,craigspaeth/positron,eessex/positron,artsy/positron
--- +++ @@ -1,6 +1,7 @@ import PropTypes from 'prop-types' import React, { Component } from 'react' import { Autocomplete } from '/client/components/autocomplete2/index' +import { clone } from 'lodash' export class AutocompleteInlineList extends Component { static propTypes = { @@ -17,7 +18,7 @@ onRemoveItem = (item) => { const { items, onSelect } = this.props - const newItems = items + const newItems = clone(items) newItems.splice(item, 1) onSelect(newItems)
004fe00f48ba855e4f5a819592206c8137d867d6
src/sentry/static/sentry/app/views/aggregateEvents.jsx
src/sentry/static/sentry/app/views/aggregateEvents.jsx
/*** @jsx React.DOM */ var React = require("react"); var Router = require("react-router"); var PropTypes = require("../proptypes"); var AggregateEvents = React.createClass({ mixins: [Router.State], propTypes: { aggregate: PropTypes.Aggregate.isRequired }, render() { return ( <div> Events </div> ); } }); module.exports = AggregateEvents;
/*** @jsx React.DOM */ var React = require("react"); var Router = require("react-router"); var api = require("../api"); var PropTypes = require("../proptypes"); var AggregateEvents = React.createClass({ mixins: [Router.State], propTypes: { aggregate: PropTypes.Aggregate.isRequired }, getInitialState() { return { eventList: null, loading: true }; }, componentWillMount() { this.fetchData(); }, fetchData() { var params = this.getParams(); this.setState({loading: true}); api.request('/groups/' + params.aggregateId + '/events/', { success: (data) => { this.setState({eventList: data}); }, error: () => { // TODO(dcramer): }, complete: () => { this.setState({loading: false}); } }); }, render() { var children = []; if (this.state.eventList) { children = this.state.eventList.map((event, eventIdx) => { return ( <tr key={eventIdx}> <td>{event.message}</td> </tr> ); }); } return ( <div> Events <table> {children} </table> </div> ); } }); module.exports = AggregateEvents;
Add basic data to events
Add basic data to events
JSX
bsd-3-clause
JackDanger/sentry,mitsuhiko/sentry,mitsuhiko/sentry,JackDanger/sentry,kevinlondon/sentry,felixbuenemann/sentry,daevaorn/sentry,mvaled/sentry,zenefits/sentry,songyi199111/sentry,zenefits/sentry,daevaorn/sentry,korealerts1/sentry,fotinakis/sentry,hongliang5623/sentry,daevaorn/sentry,mvaled/sentry,imankulov/sentry,nicholasserra/sentry,ifduyue/sentry,looker/sentry,kevinlondon/sentry,gencer/sentry,mvaled/sentry,nicholasserra/sentry,zenefits/sentry,BuildingLink/sentry,JackDanger/sentry,wong2/sentry,gencer/sentry,beeftornado/sentry,Natim/sentry,looker/sentry,BuildingLink/sentry,beeftornado/sentry,wong2/sentry,zenefits/sentry,BayanGroup/sentry,songyi199111/sentry,korealerts1/sentry,ifduyue/sentry,jean/sentry,looker/sentry,alexm92/sentry,gencer/sentry,Natim/sentry,JamesMura/sentry,jean/sentry,felixbuenemann/sentry,BuildingLink/sentry,Kryz/sentry,jean/sentry,zenefits/sentry,fuziontech/sentry,mvaled/sentry,ngonzalvez/sentry,looker/sentry,fotinakis/sentry,wong2/sentry,imankulov/sentry,felixbuenemann/sentry,BayanGroup/sentry,beeftornado/sentry,JamesMura/sentry,BuildingLink/sentry,fotinakis/sentry,jean/sentry,korealerts1/sentry,hongliang5623/sentry,looker/sentry,gencer/sentry,ifduyue/sentry,alexm92/sentry,mvaled/sentry,JamesMura/sentry,BayanGroup/sentry,alexm92/sentry,Kryz/sentry,ifduyue/sentry,ifduyue/sentry,fuziontech/sentry,JamesMura/sentry,mvaled/sentry,gencer/sentry,Natim/sentry,hongliang5623/sentry,kevinlondon/sentry,JamesMura/sentry,nicholasserra/sentry,fotinakis/sentry,ngonzalvez/sentry,ngonzalvez/sentry,fuziontech/sentry,imankulov/sentry,BuildingLink/sentry,daevaorn/sentry,jean/sentry,songyi199111/sentry,Kryz/sentry
--- +++ @@ -3,6 +3,7 @@ var React = require("react"); var Router = require("react-router"); +var api = require("../api"); var PropTypes = require("../proptypes"); var AggregateEvents = React.createClass({ @@ -12,10 +13,55 @@ aggregate: PropTypes.Aggregate.isRequired }, + getInitialState() { + return { + eventList: null, + loading: true + }; + }, + + componentWillMount() { + this.fetchData(); + }, + + fetchData() { + var params = this.getParams(); + + this.setState({loading: true}); + + api.request('/groups/' + params.aggregateId + '/events/', { + success: (data) => { + this.setState({eventList: data}); + }, + error: () => { + // TODO(dcramer): + }, + complete: () => { + this.setState({loading: false}); + } + }); + }, + + render() { + var children = []; + + if (this.state.eventList) { + children = this.state.eventList.map((event, eventIdx) => { + return ( + <tr key={eventIdx}> + <td>{event.message}</td> + </tr> + ); + }); + } + return ( <div> - Events + Events + <table> + {children} + </table> </div> ); }
0292c93f11a7ac57185d4364a9e718771d027295
src/components/UserProfile/UserProfileContainer.jsx
src/components/UserProfile/UserProfileContainer.jsx
import React, { Component } from "react"; import firebase from "../../javascripts/firebase"; import UserProfile from "./UserProfile"; import store from "../../store/configureStore"; class UserProfileContainer extends Component { constructor(props) { super(props); this.state = { sightings: [] } } componentDidMount() { let sightings; let ref = firebase.database().ref().child("sightings"); var that = this; ref.once("value").then(function(snap){ sightings = Object.values(snap.val()); that.setState({ sightings: sightings }); }) } render() { return( <div className="page"> <UserProfile user={store.getState().user} sightings={this.state.sightings} /> </div> ) } } export default UserProfileContainer;
import React, { Component } from 'react'; import firebase from '../../javascripts/firebase'; import UserProfile from './UserProfile'; import store from '../../store/configureStore'; class UserProfileContainer extends Component { constructor(props) { super(props); this.state = { sightings: [] }; } componentDidMount() { let sightings; let ref = firebase .database() .ref() .child('sightings') .child(firebase.auth().currentUser.uid); var that = this; ref.once('value').then(function(snap) { sightings = Object.values(snap.val()); that.setState({ sightings: sightings }); }); } render() { return ( <div className="page"> <UserProfile user={store.getState().user} sightings={this.state.sightings} /> </div> ); } } export default UserProfileContainer;
Add user profile reference to user's own sightings only
Add user profile reference to user's own sightings only
JSX
mit
omarcodex/butterfly-pinner,omarcodex/butterfly-pinner
--- +++ @@ -1,35 +1,39 @@ -import React, { Component } from "react"; -import firebase from "../../javascripts/firebase"; +import React, { Component } from 'react'; +import firebase from '../../javascripts/firebase'; -import UserProfile from "./UserProfile"; -import store from "../../store/configureStore"; +import UserProfile from './UserProfile'; +import store from '../../store/configureStore'; class UserProfileContainer extends Component { constructor(props) { super(props); this.state = { sightings: [] - } + }; } componentDidMount() { let sightings; - let ref = firebase.database().ref().child("sightings"); + let ref = firebase + .database() + .ref() + .child('sightings') + .child(firebase.auth().currentUser.uid); var that = this; - ref.once("value").then(function(snap){ + ref.once('value').then(function(snap) { sightings = Object.values(snap.val()); that.setState({ sightings: sightings }); - }) + }); } render() { - return( + return ( <div className="page"> <UserProfile user={store.getState().user} sightings={this.state.sightings} /> </div> - ) + ); } }
e595a390b5ed9a0f7f6b27a1ebcda964023a2ca2
www/app/script/page/Home.jsx
www/app/script/page/Home.jsx
var React = require('react'); var ReactBootstrap = require('react-bootstrap'); var ReactRouter = require('react-router'); var ReactIntl = require('react-intl'); var Reflux = require('reflux'); var TextStore = require("../store/TextStore"); var TextAction = require("../action/TextAction"); var TextList = require("../component/TextList"), Page = require("../component/Page"); var Grid = ReactBootstrap.Grid, Row = ReactBootstrap.Row, Col = ReactBootstrap.Col; var Link = ReactRouter.Link; var Home = React.createClass({ mixins: [ ReactIntl.IntlMixin, Reflux.connect(TextStore, 'texts') ], componentWillMount: function() { TextAction.showLatestTexts(); }, render: function() { return ( <div className="page-home"> <Page slug="accueil"/> <Grid> <Row> <Col md={12}> <h2>{this.getIntlMessage('text.TEXTS')}</h2> </Col> </Row> <Row> <Col md={12}> {this.state && this.state.texts ? <TextList texts={this.state.texts.getLatestTexts()} /> : <div/>} </Col> </Row> </Grid> </div> ); } }); module.exports = Home;
var React = require('react'); var ReactBootstrap = require('react-bootstrap'); var ReactRouter = require('react-router'); var ReactIntl = require('react-intl'); var Reflux = require('reflux'); var TextStore = require("../store/TextStore"); var TextAction = require("../action/TextAction"); var TextList = require("../component/TextList"), Page = require("../component/Page"); var Grid = ReactBootstrap.Grid, Row = ReactBootstrap.Row, Col = ReactBootstrap.Col; var Link = ReactRouter.Link; var Home = React.createClass({ mixins: [ ReactIntl.IntlMixin, Reflux.connect(TextStore, 'texts') ], componentWillMount: function() { TextAction.showLatestTexts(); }, render: function() { return ( <div className="page-home"> <Page slug="accueil" setDocumentTitle={true}/> <Grid> <Row> <Col md={12}> <h2>{this.getIntlMessage('text.TEXTS')}</h2> </Col> </Row> <Row> <Col md={12}> {this.state && this.state.texts ? <TextList texts={this.state.texts.getLatestTexts()} /> : <div/>} </Col> </Row> </Grid> </div> ); } }); module.exports = Home;
Fix the home page document title.
Fix the home page document title.
JSX
mit
promethe42/cocorico,promethe42/cocorico,promethe42/cocorico,promethe42/cocorico,promethe42/cocorico
--- +++ @@ -33,7 +33,7 @@ { return ( <div className="page-home"> - <Page slug="accueil"/> + <Page slug="accueil" setDocumentTitle={true}/> <Grid> <Row> <Col md={12}>
c1f56419d2ecd4d8303c715f385ef9cb0292341b
src/components/realtime-switch.jsx
src/components/realtime-switch.jsx
import React from 'react'; import {connect} from 'react-redux'; import {toggleRealtime, updateFrontendPreferences, home} from '../redux/action-creators'; const getStatusIcon = (active, status) => { if (status === 'loading') { return 'refresh'; } return active ? 'pause' : 'play'; }; const realtimeSwitch = props => { const {realtimeActive} = props.frontendPreferences; return ( <div className='realtime-switch' onClick={_ => props.toggle(props.userId, props.frontendPreferences)}> {realtimeActive ? false : 'Paused'} <span className={`glyphicon glyphicon-${getStatusIcon(realtimeActive, props.status)}`}/> </div> ); }; const mapStateToProps = (state) => { return { userId: state.user.id, frontendPreferences: state.user.frontendPreferences, status: state.frontendRealtimePreferencesForm.status, }; }; const mapDispatchToProps = (dispatch) => { return { toggle: (userId, frontendPreferences) => { const {realtimeActive} = props.frontendPreferences; //send a request to change flag dispatch(updateFrontendPreferences(userId, {...frontendPreferences, realtimeActive: !realtimeActive})); //set a flag to show dispatch(toggleRealtime()); if (!realtimeActive) { dispatch(home()); } } }; }; export default connect(mapStateToProps, mapDispatchToProps)(realtimeSwitch);
import React from 'react'; import {connect} from 'react-redux'; import {toggleRealtime, updateFrontendPreferences, home} from '../redux/action-creators'; const getStatusIcon = (active, status) => { if (status === 'loading') { return 'refresh'; } return active ? 'pause' : 'play'; }; const realtimeSwitch = props => { const {realtimeActive} = props.frontendPreferences; return ( <div className='realtime-switch' onClick={_ => props.toggle(props.userId, props.frontendPreferences)}> {realtimeActive ? false : 'Paused'} <span className={`glyphicon glyphicon-${getStatusIcon(realtimeActive, props.status)}`}/> </div> ); }; const mapStateToProps = (state) => { return { userId: state.user.id, frontendPreferences: state.user.frontendPreferences, status: state.frontendRealtimePreferencesForm.status, }; }; const mapDispatchToProps = (dispatch) => { return { toggle: (userId, frontendPreferences) => { const {realtimeActive} = frontendPreferences; //send a request to change flag dispatch(updateFrontendPreferences(userId, {...frontendPreferences, realtimeActive: !realtimeActive})); //set a flag to show dispatch(toggleRealtime()); if (!realtimeActive) { dispatch(home()); } } }; }; export default connect(mapStateToProps, mapDispatchToProps)(realtimeSwitch);
Fix reference error: props is not defined
Fix reference error: props is not defined
JSX
mit
FreeFeed/freefeed-react-client,kadmil/freefeed-react-client,kadmil/freefeed-react-client,ujenjt/freefeed-react-client,ujenjt/freefeed-react-client,kadmil/freefeed-react-client,davidmz/freefeed-react-client,ujenjt/freefeed-react-client,davidmz/freefeed-react-client,FreeFeed/freefeed-react-client,davidmz/freefeed-react-client,FreeFeed/freefeed-react-client
--- +++ @@ -30,7 +30,7 @@ const mapDispatchToProps = (dispatch) => { return { toggle: (userId, frontendPreferences) => { - const {realtimeActive} = props.frontendPreferences; + const {realtimeActive} = frontendPreferences; //send a request to change flag dispatch(updateFrontendPreferences(userId, {...frontendPreferences, realtimeActive: !realtimeActive})); //set a flag to show
12dd06512b7a7c78c0984fe3aa79f1dfdfe2b474
livedoc-ui/src/components/fetcher/DocFetcher.jsx
livedoc-ui/src/components/fetcher/DocFetcher.jsx
// @flow import React from 'react'; import { InlineForm } from '../forms/InlineForm'; type Props = { fetchDoc: (url: string) => void, } export const DocFetcher = (props: Props) => (<InlineForm hintText='URL to JSON documentation' btnLabel='Get Doc' initialValue={computeInitialUrl()} onSubmit={props.fetchDoc}/>); function computeInitialUrl(): string { const url = new URL(window.location.href); const specifiedUrl = url.searchParams.get('url'); if (specifiedUrl) { return specifiedUrl; } return window.location.href + 'jsondoc'; }
// @flow import React from 'react'; import { InlineForm } from '../forms/InlineForm'; type Props = { fetchDoc: (url: string) => void, } export const DocFetcher = (props: Props) => (<InlineForm hintText='URL to JSON documentation' btnLabel='Get Doc' initialValue={computeInitialUrl()} onSubmit={props.fetchDoc}/>); const DEFAULT_FETCH_URL = 'http://localhost:8080/jsondoc'; function computeInitialUrl(): string { const url = new URL(window.location.href); const specifiedUrl = url.searchParams.get('url'); if (specifiedUrl) { return specifiedUrl; } return DEFAULT_FETCH_URL; }
Change default fetch URL for easier dev with changing routes
Change default fetch URL for easier dev with changing routes
JSX
mit
joffrey-bion/livedoc,joffrey-bion/livedoc,joffrey-bion/livedoc,joffrey-bion/livedoc,joffrey-bion/livedoc
--- +++ @@ -10,11 +10,13 @@ initialValue={computeInitialUrl()} onSubmit={props.fetchDoc}/>); +const DEFAULT_FETCH_URL = 'http://localhost:8080/jsondoc'; + function computeInitialUrl(): string { const url = new URL(window.location.href); const specifiedUrl = url.searchParams.get('url'); if (specifiedUrl) { return specifiedUrl; } - return window.location.href + 'jsondoc'; + return DEFAULT_FETCH_URL; }
83ad95ab3dd264686c0812313438a3f37165a63b
src/components/SightingList.jsx
src/components/SightingList.jsx
import React from 'react'; // import { Card, CardMedia, CardTitle, CardText } from 'material-ui/Card'; // import styled from 'styled-components'; // const Img = styled.img` // margin: // ` const SightingList = props => { console.log(props); return ( <div> <h1>Sighting List</h1> {props.sightings.map(s => ( <ul> <li>{s.scientificName}</li> <li> Count: {s.count} </li> <li> Sex: {s.sex} </li> <li> Lat: {s.lat} </li> <li> Long: {s.lon} </li> <li> <img src={s.photoURL} alt={s.scientificName} width="300px" /> </li> </ul> ))} </div> ); }; export default SightingList;
import React from 'react'; import { Card, CardMedia, CardTitle, CardText } from 'material-ui/Card'; // import styled from 'styled-components'; // const Img = styled.img` // margin: // ` const SightingList = props => { console.log(props); return ( <div> <h1>Sighting List</h1> {props.sightings.map(s => ( <Card> <CardTitle title={s.scientificName} subtitle={'Lat: ' + s.lat + ', Long: ' + s.lon} /> <CardMedia> <img src={s.photoURL || 'https://evolution.berkeley.edu/evolibrary/images/evo/ontogenew.gif'} alt={s.scientificName} /> </CardMedia> <CardText> <h3>Count: {s.count}</h3> <h3>Sex: {s.sex}</h3> <h3>Location: {s.lat + ', ' + s.lon}</h3> </CardText> </Card> ))} </div> ); }; export default SightingList;
Add basic sighting card styling
Add basic sighting card styling
JSX
mit
omarcodex/butterfly-pinner,omarcodex/butterfly-pinner
--- +++ @@ -1,5 +1,5 @@ import React from 'react'; -// import { Card, CardMedia, CardTitle, CardText } from 'material-ui/Card'; +import { Card, CardMedia, CardTitle, CardText } from 'material-ui/Card'; // import styled from 'styled-components'; // const Img = styled.img` // margin: @@ -11,28 +11,20 @@ <div> <h1>Sighting List</h1> {props.sightings.map(s => ( - <ul> - <li>{s.scientificName}</li> - <li> - Count: - {s.count} - </li> - <li> - Sex: - {s.sex} - </li> - <li> - Lat: - {s.lat} - </li> - <li> - Long: - {s.lon} - </li> - <li> - <img src={s.photoURL} alt={s.scientificName} width="300px" /> - </li> - </ul> + <Card> + <CardTitle title={s.scientificName} subtitle={'Lat: ' + s.lat + ', Long: ' + s.lon} /> + <CardMedia> + <img + src={s.photoURL || 'https://evolution.berkeley.edu/evolibrary/images/evo/ontogenew.gif'} + alt={s.scientificName} + /> + </CardMedia> + <CardText> + <h3>Count: {s.count}</h3> + <h3>Sex: {s.sex}</h3> + <h3>Location: {s.lat + ', ' + s.lon}</h3> + </CardText> + </Card> ))} </div> );
3b7ce98f79223f910dc6272efd9e3e5f8a3fcf4e
src/app/login/Login.jsx
src/app/login/Login.jsx
import React, { Component } from 'react'; import { connect } from 'react-redux' import Layout from '../global/Layout'; class Login extends Component { constructor(props) { super(props); } render() { return ( <Layout > <div>This is login</div> </Layout> ) } } export default connect()(Layout);
import React, { Component } from 'react'; import { connect } from 'react-redux' import { post } from '../utilities/post' class Login extends Component { constructor(props) { super(props); this.state = { email: "", password: "" }; this.handleSubmit = this.handleSubmit.bind(this); this.handleEmailChange = this.handleEmailChange.bind(this); this.handlePasswordChange = this.handlePasswordChange.bind(this); } handleSubmit(event) { event.preventDefault(); const postBody = { email: this.state.email, password: this.state.password }; function setAccessTokenCookie(accessToken) { document.cookie = "access_token=" + accessToken+ ";path=/"; console.log(`Cookie: access_token: ${accessToken} set`); // TODO update state authentication property } return post('/zebedee/login', postBody) .then(function(accessToken) { setAccessTokenCookie(accessToken); }).catch(function(error) { return error; }); } handleEmailChange(event) { this.setState({email: event.target.value}); } handlePasswordChange(event) { this.setState({password: event.target.value}); } render() { return ( <div className="col--4 login-wrapper"> <h1>Login</h1> <form onSubmit={this.handleSubmit}> <label htmlFor="email">Email:</label> <input id="email" type="email" className="fl-user-and-access__email" name="email" cols="40" rows="1" onChange={this.handleEmailChange}/> <label htmlFor="password">Password:</label> <input id="password" type="password" className="fl-user-and-access__password" name="password" cols="40" rows="1" onChange={this.handlePasswordChange}/> <button type="submit" id="login" className="btn btn--primary margin-left--0 btn-florence-login fl-panel--user-and-access__login ">Log in</button> </form> </div> ) } } export default connect()(Login);
Add login form and set cookie functionality
Add login form and set cookie functionality
JSX
mit
ONSdigital/florence,ONSdigital/florence,ONSdigital/florence,ONSdigital/florence
--- +++ @@ -1,20 +1,73 @@ import React, { Component } from 'react'; import { connect } from 'react-redux' -import Layout from '../global/Layout'; +import { post } from '../utilities/post' class Login extends Component { constructor(props) { super(props); + + this.state = { + email: "", + password: "" + }; + + this.handleSubmit = this.handleSubmit.bind(this); + this.handleEmailChange = this.handleEmailChange.bind(this); + this.handlePasswordChange = this.handlePasswordChange.bind(this); + + } + + handleSubmit(event) { + event.preventDefault(); + + const postBody = { + email: this.state.email, + password: this.state.password + }; + + function setAccessTokenCookie(accessToken) { + document.cookie = "access_token=" + accessToken+ ";path=/"; + console.log(`Cookie: access_token: ${accessToken} set`); + // TODO update state authentication property + } + + return post('/zebedee/login', postBody) + .then(function(accessToken) { + setAccessTokenCookie(accessToken); + }).catch(function(error) { + return error; + }); + + + } + + + handleEmailChange(event) { + this.setState({email: event.target.value}); + } + + handlePasswordChange(event) { + this.setState({password: event.target.value}); } render() { return ( - <Layout > - <div>This is login</div> - </Layout> + <div className="col--4 login-wrapper"> + <h1>Login</h1> + + <form onSubmit={this.handleSubmit}> + <label htmlFor="email">Email:</label> + <input id="email" type="email" className="fl-user-and-access__email" name="email" cols="40" rows="1" onChange={this.handleEmailChange}/> + + <label htmlFor="password">Password:</label> + <input id="password" type="password" className="fl-user-and-access__password" name="password" cols="40" rows="1" onChange={this.handlePasswordChange}/> + + <button type="submit" id="login" className="btn btn--primary margin-left--0 btn-florence-login fl-panel--user-and-access__login ">Log in</button> + </form> + </div> ) } } -export default connect()(Layout); +export default connect()(Login);
1df07312f3d9e430ac81ba308eaee8836b50ddaf
app/scripts/components/app.jsx
app/scripts/components/app.jsx
"use strict"; var React = require('react'); var Navigation = require('react-router').Navigation; var session = require('../session/models/session'); var sessionActions = require('../session/actions'); var RouterHeader = require('./header/top-bar.jsx'); require('react-bootstrap'); var redirectToLogin = function() { if (!session.isLoggedIn()) { this.transitionTo('/login'); } }; var attemptSessionRestoration = function() { sessionActions.restore(); }; var topBarConfig = { brandName: "Gatewayd Basic", wrapperClass: "top-bar container-fluid", links: [ { text: "logout", href: "/logout" } ] }; var App = React.createClass({ mixins: [Navigation], render:function(){ if (!session.get('lastLogin')) { attemptSessionRestoration(); redirectToLogin.call(this); } return ( <div> <RouterHeader setup={topBarConfig} /> <div className="container"> {this.props.activeRouteHandler()} </div> </div> ) } }); module.exports = App;
"use strict"; var React = require('react'); var Navigation = require('react-router').Navigation; var session = require('../session/models/session'); var sessionActions = require('../session/actions'); var RouterHeader = require('./header/top-bar.jsx'); require('react-bootstrap'); var redirectToLogin = function() { if (!session.isLoggedIn()) { this.transitionTo('/login'); } }; var attemptSessionRestoration = function() { sessionActions.restore(); }; var topBarConfig = { brandName: 'Gatewayd Basic', wrapperClass: 'top-bar container-fluid', links: [ { text: 'To Ripple Network', href: '/payments' }, { text: 'To External Account', href: '/payments' }, { text: 'logout', href: '/logout' } ] }; var App = React.createClass({ mixins: [Navigation], render:function(){ if (!session.get('lastLogin')) { attemptSessionRestoration(); redirectToLogin.call(this); } return ( <div> <RouterHeader setup={topBarConfig} /> <div className="container"> {this.props.activeRouteHandler()} </div> </div> ) } }); module.exports = App;
Add links to top bar for splitting interna/external payments
[TASK] Add links to top bar for splitting interna/external payments
JSX
isc
dabibbit/dream-stack-seed,dabibbit/dream-stack-seed
--- +++ @@ -20,12 +20,20 @@ }; var topBarConfig = { - brandName: "Gatewayd Basic", - wrapperClass: "top-bar container-fluid", + brandName: 'Gatewayd Basic', + wrapperClass: 'top-bar container-fluid', links: [ { - text: "logout", - href: "/logout" + text: 'To Ripple Network', + href: '/payments' + }, + { + text: 'To External Account', + href: '/payments' + }, + { + text: 'logout', + href: '/logout' } ] };
073b68c44e22b5d2c9826d5cd51079b10f6ed6b3
src/pages/sponsors.jsx
src/pages/sponsors.jsx
import { css } from 'glamor'; import Paper from 'material-ui/Paper'; import React from 'react'; import Helmet from 'react-helmet'; import BMELogoImage from '../assets/bme-logo.svg'; import EHKLogoImage from '../assets/ehk-logo.svg'; import ArticleContainer from '../components/article-container'; import CoverImage from '../components/cover-image'; const SponsorsPage = () => { const title = 'Szponzorok'; return ( <div> <Helmet> <title>{title}</title> </Helmet> <CoverImage /> <ArticleContainer title={title}> <Paper> <div {...css({ display: 'flex', justifyContent: 'space-between', })} > <img src={BMELogoImage} alt="Műegyetem 1782" /> <img src={EHKLogoImage} alt="Egyetemi Hallgatói Képviselet" /> </div> </Paper> </ArticleContainer> </div> ); }; export default SponsorsPage;
import { css } from 'glamor'; import Paper from 'material-ui/Paper'; import React from 'react'; import Helmet from 'react-helmet'; import BMELogoImage from '../assets/bme-logo.svg'; import EHKLogoImage from '../assets/ehk-logo.svg'; import ArticleContainer from '../components/article-container'; import CoverImage from '../components/cover-image'; const SponsorsPage = () => { const title = 'Szponzorok'; return ( <div> <Helmet> <title>{title}</title> </Helmet> <CoverImage /> <ArticleContainer title={title}> <Paper> <div {...css({ display: 'flex', flexWrap: 'wrap', justifyContent: 'center', margin: '-1rem', '& > *': { height: '6rem', padding: '1rem', }, })} > <img src={BMELogoImage} alt="Műegyetem 1782" /> <img src={EHKLogoImage} alt="Egyetemi Hallgatói Képviselet" /> </div> </Paper> </ArticleContainer> </div> ); }; export default SponsorsPage;
Fix alignment of sponsor logos
Fix alignment of sponsor logos Resolves #2
JSX
mit
simonyiszk/mvk-web,simonyiszk/mvk-web
--- +++ @@ -23,7 +23,14 @@ <div {...css({ display: 'flex', - justifyContent: 'space-between', + flexWrap: 'wrap', + justifyContent: 'center', + margin: '-1rem', + + '& > *': { + height: '6rem', + padding: '1rem', + }, })} > <img src={BMELogoImage} alt="Műegyetem 1782" />