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
|
---|---|---|---|---|---|---|---|---|---|---|
d351a4f00a05b20e6e09a626a02ab33ccea8b5a9 | client/store/configureStore.ts | client/store/configureStore.ts | import * as redux from "redux";
import { AppState, AppWindow } from "../app";
import { reducer } from "./module";
export interface LocalWindow extends AppWindow {
__REDUX_DEVTOOLS_EXTENSION_COMPOSE__: any;
}
export function configureStore(initialState: AppState): redux.Store<AppState> {
if (process.env.NODE_ENV === "development") {
const composeEnhancers =
(window as LocalWindow).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ||
redux.compose;
return redux.createStore(reducer, initialState, composeEnhancers());
} else {
return redux.createStore(reducer, initialState);
}
};
export default configureStore;
| import * as redux from "redux";
import { AppState, AppWindow } from "../app";
import { reducer } from "./module";
export interface LocalWindow extends AppWindow {
__REDUX_DEVTOOLS_EXTENSION_COMPOSE__: any;
}
export function configureStore(initialState: AppState): redux.Store<AppState> {
if (process.env.NODE_ENV === "development") {
const composeEnhancers =
(window as LocalWindow).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ||
redux.compose;
return redux.createStore(reducer, initialState, composeEnhancers());
}
return redux.createStore(reducer, initialState);
};
export default configureStore;
| Fix broken change in createStore | Fix broken change in createStore
| TypeScript | mit | shuntksh/binaryscanr,shuntksh/binaryscanr,shuntksh/binaryscanr | ---
+++
@@ -13,9 +13,8 @@
(window as LocalWindow).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ||
redux.compose;
return redux.createStore(reducer, initialState, composeEnhancers());
- } else {
- return redux.createStore(reducer, initialState);
}
+ return redux.createStore(reducer, initialState);
};
export default configureStore; |
78f47b05b9de94d84c156d29e675419d4454267d | examples/aws/src/LambdaServer.ts | examples/aws/src/LambdaServer.ts | import {ServerLoader} from "@tsed/common";
import * as awsServerlessExpress from "aws-serverless-express";
import {Server} from "./Server";
// NOTE: If you get ERR_CONTENT_DECODING_FAILED in your browser, this is likely
// due to a compressed response (e.g. gzip) which has not been handled correctly
// by aws-serverless-express and/or API Gateway. Add the necessary MIME types to
// binaryMimeTypes below, then redeploy (`npm run package-deploy`)
const binaryMimeTypes = [
"application/javascript",
"application/json",
"application/octet-stream",
"application/xml",
"font/eot",
"font/opentype",
"font/otf",
"image/jpeg",
"image/png",
"image/svg+xml",
"text/comma-separated-values",
"text/css",
"text/html",
"text/javascript",
"text/plain",
"text/text",
"text/xml"
];
// The function handler to setup on AWS Lambda console -- the name of this function must match the one configured on AWS
export async function awsHanlder(event: any, context: any, done: any) {
const server = await ServerLoader.bootstrap(Server);
const lambdaServer = awsServerlessExpress.createServer(server.expressApp, null, binaryMimeTypes);
awsServerlessExpress.proxy(lambdaServer, event, context);
done();
}
| import {ServerLoader} from "@tsed/common";
import * as awsServerlessExpress from "aws-serverless-express";
import {Server} from "./Server";
// NOTE: If you get ERR_CONTENT_DECODING_FAILED in your browser, this is likely
// due to a compressed response (e.g. gzip) which has not been handled correctly
// by aws-serverless-express and/or API Gateway. Add the necessary MIME types to
// binaryMimeTypes below, then redeploy (`npm run package-deploy`)
const binaryMimeTypes = [
"application/javascript",
"application/json",
"application/octet-stream",
"application/xml",
"font/eot",
"font/opentype",
"font/otf",
"image/jpeg",
"image/png",
"image/svg+xml",
"text/comma-separated-values",
"text/css",
"text/html",
"text/javascript",
"text/plain",
"text/text",
"text/xml"
];
// The function handler to setup on AWS Lambda console -- the name of this function must match the one configured on AWS
export async function awsHanlder(event: any, context: any) {
const server = await ServerLoader.bootstrap(Server);
const lambdaServer = awsServerlessExpress.createServer(server.expressApp, null, binaryMimeTypes);
return awsServerlessExpress.proxy(lambdaServer, event, context).promise;
}
| Fix bug on AWS example reported by @pradeeptk | docs: Fix bug on AWS example reported by @pradeeptk
Closes: https://github.com/TypedProject/tsed-example-aws/issues/3
| TypeScript | mit | Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators | ---
+++
@@ -27,11 +27,9 @@
];
// The function handler to setup on AWS Lambda console -- the name of this function must match the one configured on AWS
-export async function awsHanlder(event: any, context: any, done: any) {
+export async function awsHanlder(event: any, context: any) {
const server = await ServerLoader.bootstrap(Server);
const lambdaServer = awsServerlessExpress.createServer(server.expressApp, null, binaryMimeTypes);
- awsServerlessExpress.proxy(lambdaServer, event, context);
-
- done();
+ return awsServerlessExpress.proxy(lambdaServer, event, context).promise;
} |
94755f3470c33aba7f2f88378d32c7cfcd340080 | src/app/infrastructure/startup.ts | src/app/infrastructure/startup.ts | import { Component } from "./component";
export class Startup {
static launch<T extends Component>(component: new () => T, containerId: string = 'container'): void {
let container = document.getElementById(containerId);
if(container == null) {
container = document.createElement('div');
container.setAttribute('id', 'container');
document.body.appendChild(container);
}
const c = new component();
container.innerHTML = c.template();
}
} | import { Component } from "./component";
export class Startup {
static launch<T extends Component>(component: new () => T, containerId: string = 'container'): void {
let container = document.getElementById(containerId);
if(container == null) {
container = document.createElement('div');
container.setAttribute('id', containerId);
document.body.appendChild(container);
}
const c = new component();
container.innerHTML = c.template();
}
} | Change dynamic container creation identifier | Change dynamic container creation identifier
| TypeScript | mit | Vtek/frameworkless,Vtek/frameworkless,Vtek/frameworkless | ---
+++
@@ -7,7 +7,7 @@
if(container == null) {
container = document.createElement('div');
- container.setAttribute('id', 'container');
+ container.setAttribute('id', containerId);
document.body.appendChild(container);
}
|
db1bf6cbe5b4f1405abdaff1e424625e27648571 | src/models/events.ts | src/models/events.ts | import DatabaseService from '../services/database';
export default class Events {
dbService: DatabaseService = null;
constructor() {
this.dbService = new DatabaseService();
}
getAll(): Promise<any> {
return this.dbService.connect()
.then((db: any) => {
console.log('connected to db !');
return db.collection('events').find({}, {"title": 1, "marvelId": 1, _id: 0}).sort([['title', 1]]).toArray()
.then((events: any) => {
db.close();
return events;
})
.catch((err: any) => {
db.close();
return err;
});
})
.catch((err: any) => err);
}
} | import DatabaseService from '../services/database';
export default class Events {
dbService: DatabaseService = null;
constructor() {
this.dbService = new DatabaseService();
}
getAll(): Promise<any> {
return this.dbService.connect()
.then((db: any) => {
return db.collection('events').find({}, {"title": 1, "marvelId": 1, _id: 0}).sort([['title', 1]]).toArray()
.then((events: any) => {
db.close();
return events;
})
.catch((err: any) => {
db.close();
return err;
});
})
.catch((err: any) => err);
}
getById(marvelId: string): Promise<any> {
return this.dbService.connect()
.then((db: any) => {
console.log(marvelId);
return db.collection('events')
.find({"marvelId": parseInt(marvelId)}, {
_id: 0,
"title": 1,
"description": 1,
"urls": 1,
"thumbnail": 1,
"marvelId": 1,
})
.limit(1)
.next()
.then((event: any) => {
console.log(event);
db.close();
return event;
})
.catch((err: any) => {
db.close();
return err;
});
})
.catch((err: any) => err);
}
} | Add getById method to Event model | Add getById method to Event model
| TypeScript | mit | SBats/marvel-reading-stats-backend | ---
+++
@@ -10,7 +10,6 @@
getAll(): Promise<any> {
return this.dbService.connect()
.then((db: any) => {
- console.log('connected to db !');
return db.collection('events').find({}, {"title": 1, "marvelId": 1, _id: 0}).sort([['title', 1]]).toArray()
.then((events: any) => {
db.close();
@@ -23,4 +22,32 @@
})
.catch((err: any) => err);
}
+
+ getById(marvelId: string): Promise<any> {
+ return this.dbService.connect()
+ .then((db: any) => {
+ console.log(marvelId);
+ return db.collection('events')
+ .find({"marvelId": parseInt(marvelId)}, {
+ _id: 0,
+ "title": 1,
+ "description": 1,
+ "urls": 1,
+ "thumbnail": 1,
+ "marvelId": 1,
+ })
+ .limit(1)
+ .next()
+ .then((event: any) => {
+ console.log(event);
+ db.close();
+ return event;
+ })
+ .catch((err: any) => {
+ db.close();
+ return err;
+ });
+ })
+ .catch((err: any) => err);
+ }
} |
6e0f166be7a90a74cead03310b24d502d3cef91c | src/Apps/Components/AppShell.tsx | src/Apps/Components/AppShell.tsx | import { Box } from "@artsy/palette"
import { findCurrentRoute } from "Artsy/Router/Utils/findCurrentRoute"
import { NavBar } from "Components/NavBar"
import { isFunction } from "lodash"
import React, { useEffect } from "react"
import createLogger from "Utils/logger"
const logger = createLogger("Apps/Components/AppShell")
export const AppShell = props => {
const { children, match } = props
const routeConfig = findCurrentRoute(match)
/**
* Check to see if a route has a prepare key; if so call it. Used typically to
* preload bundle-split components (import()) while the route is fetching data
* in the background.
*/
useEffect(() => {
if (isFunction(routeConfig.prepare)) {
try {
routeConfig.prepare()
} catch (error) {
logger.error(error)
}
}
}, [routeConfig])
/**
* Let our end-to-end tests know that the app is hydrated and ready to go
*/
useEffect(() => {
document.body.setAttribute("data-test-ready", "")
}, [])
return (
<Box width="100%">
<Box pb={6}>
<Box left={0} position="fixed" width="100%" zIndex={100}>
<NavBar />
</Box>
</Box>
<Box>
<Box>{children}</Box>
</Box>
</Box>
)
}
| import { Box } from "@artsy/palette"
import { findCurrentRoute } from "Artsy/Router/Utils/findCurrentRoute"
import { NavBar } from "Components/NavBar"
import { isFunction } from "lodash"
import React, { useEffect } from "react"
import createLogger from "Utils/logger"
const logger = createLogger("Apps/Components/AppShell")
export const AppShell = props => {
const { children, match } = props
const routeConfig = findCurrentRoute(match)
/**
* Check to see if a route has a prepare key; if so call it. Used typically to
* preload bundle-split components (import()) while the route is fetching data
* in the background.
*/
useEffect(() => {
if (isFunction(routeConfig.prepare)) {
try {
routeConfig.prepare()
} catch (error) {
logger.error(error)
}
}
}, [routeConfig])
/**
* Let our end-to-end tests know that the app is hydrated and ready to go
*/
useEffect(() => {
document.body.setAttribute("data-test", "AppReady")
}, [])
return (
<Box width="100%">
<Box pb={6}>
<Box left={0} position="fixed" width="100%" zIndex={100}>
<NavBar />
</Box>
</Box>
<Box>
<Box>{children}</Box>
</Box>
</Box>
)
}
| Update attribute to follow pre-established testing patterns | Update attribute to follow pre-established testing patterns
| TypeScript | mit | artsy/reaction,artsy/reaction,artsy/reaction-force,artsy/reaction-force,artsy/reaction | ---
+++
@@ -30,7 +30,7 @@
* Let our end-to-end tests know that the app is hydrated and ready to go
*/
useEffect(() => {
- document.body.setAttribute("data-test-ready", "")
+ document.body.setAttribute("data-test", "AppReady")
}, [])
return ( |
fb88741ca056176adc088220d0aeb3473bb0126d | src/settings/settings-manager.ts | src/settings/settings-manager.ts | import {Settings} from "./settings"
import * as Cookie from "js-cookie";
export function loadSettings(): Settings {
try {
const options = Cookie.getJSON("options") || {};
return Settings.createFromObject(options);
} catch (e) {
console.error("Failed to load settings: ", e);
return Settings.createFromObject({});
}
}
export function saveSettings(settings: Settings) {
Cookie.set("options", settings, {expires: 365});
}
| import {Settings} from "./settings"
import * as Cookie from "js-cookie";
export function loadSettings(): Settings {
try {
const options = Cookie.getJSON("options") || {};
return Settings.createFromObject(options);
} catch (e) {
console.error("Failed to load settings: ", e);
return Settings.createFromObject({});
}
}
export function saveSettings(settings: Settings) {
Cookie.set("options", settings, {expires: 365, sameSite: "none"});
}
| Allow cross-site usage of the options cookie | Allow cross-site usage of the options cookie
The [SameSite cookie](https://web.dev/samesite-cookies-explained/) setting (which now defaults to `lax` in Chrome) limits access of the `options` cookie.
This breaks [command.games](https://github.com/davidtorosyan/command.games), which depends on this cookie.
This change sets `sameSite` to `none`, which should fix the plugin.
See issue #58. | TypeScript | mit | blakevanlan/KingdomCreator,blakevanlan/KingdomCreator | ---
+++
@@ -12,5 +12,5 @@
}
export function saveSettings(settings: Settings) {
- Cookie.set("options", settings, {expires: 365});
+ Cookie.set("options", settings, {expires: 365, sameSite: "none"});
} |
d6dcd62c58168b3a91c1fccdc4e33f1e26145ea4 | generators/component/templates/_component.spec.ts | generators/component/templates/_component.spec.ts | /* beautify ignore:start */
import {
it,
//inject,
injectAsync,
beforeEachProviders,
TestComponentBuilder
} from 'angular2/testing';
import {<%=componentnameClass%>Component} from './<%=componentnameFile%>.component.ts';
/* beautify ignore:end */
describe('Component: <%=componentnameClass%>Component', () => {
let builder;
beforeEachProviders(() => []);
it('should be defined', injectAsync([TestComponentBuilder], (tcb) => {
return tcb.createAsync(<%=componentnameClass%>Component)
.then((fixture) => {
fixture.detectChanges();
let element = fixture.debugElement.nativeElement;
let cmpInstance = fixture.debugElement.componentInstance;
expect(cmpInstance).toBeDefined();
expect(element).toBeDefined();
});
}));
}); | /* beautify ignore:start */
import {
it,
//inject,
injectAsync,
beforeEachProviders,
TestComponentBuilder
} from 'angular2/testing';
import {<%=componentnameClass%>Component} from './<%=componentnameFile%>.component.ts';
/* beautify ignore:end */
describe('Component: <%=componentnameClass%>Component', () => {
beforeEachProviders(() => []);
it('should be defined', injectAsync([TestComponentBuilder], (tcb) => {
return tcb.createAsync(<%=componentnameClass%>Component)
.then((fixture) => {
fixture.detectChanges();
let element = fixture.debugElement.nativeElement;
let cmpInstance = fixture.debugElement.componentInstance;
expect(cmpInstance).toBeDefined();
expect(element).toBeDefined();
});
}));
}); | Fix lint issue in component test | fix(app): Fix lint issue in component test
| TypeScript | mit | mcfly-io/generator-mcfly-ng2,mcfly-io/generator-mcfly-ng2,mcfly-io/generator-mcfly-ng2 | ---
+++
@@ -10,7 +10,7 @@
/* beautify ignore:end */
describe('Component: <%=componentnameClass%>Component', () => {
- let builder;
+
beforeEachProviders(() => []);
it('should be defined', injectAsync([TestComponentBuilder], (tcb) => { |
23a6dec42b63b87b0a39b21dd4e52c4084a55697 | site/client/NotFoundPageMain.tsx | site/client/NotFoundPageMain.tsx | import {Analytics} from './Analytics'
export function runNotFoundPage() {
const query = window.location.pathname.split("/")
const searchInput = document.getElementById("search_q") as HTMLInputElement
if (searchInput && query.length) searchInput.value = decodeURIComponent(query[query.length-1])
Analytics.logEvent("NOT_FOUND", { href: window.location.href })
}
| import {Analytics} from './Analytics'
export function runNotFoundPage() {
const query = window.location.pathname.split("/")
const searchInput = document.getElementById("search_q") as HTMLInputElement
if (searchInput && query.length) searchInput.value = decodeURIComponent(query[query.length-1]).replace(/[\-_\+|]/g, ' ')
Analytics.logEvent("NOT_FOUND", { href: window.location.href })
}
| Remove separators from suggested query on 404 | Remove separators from suggested query on 404
| TypeScript | mit | OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher,owid/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher | ---
+++
@@ -3,6 +3,6 @@
export function runNotFoundPage() {
const query = window.location.pathname.split("/")
const searchInput = document.getElementById("search_q") as HTMLInputElement
- if (searchInput && query.length) searchInput.value = decodeURIComponent(query[query.length-1])
+ if (searchInput && query.length) searchInput.value = decodeURIComponent(query[query.length-1]).replace(/[\-_\+|]/g, ' ')
Analytics.logEvent("NOT_FOUND", { href: window.location.href })
} |
9b0b202e79c01231f16cb78a74e8e3272c7e1481 | src/index.ts | src/index.ts | import 'webrtc-adapter';
import { App as PeerData } from './app/App';
import { Room } from './app/Room';
import { Participant } from './app/Participant';
import { EventDispatcher } from './app/EventDispatcher';
import { Signaling, SignalingEvent, SignalingEventType } from './app/Signaling';
import { SocketChannel } from './app/SocketChannel';
export {
Room,
Participant,
EventDispatcher,
Signaling,
SignalingEvent,
SignalingEventType,
SocketChannel,
};
export default PeerData;
| // tslint:disable-next-line: no-require-imports no-var-requires
require('webrtc-adapter');
import { App as PeerData } from './app/App';
import { Room } from './app/Room';
import { Participant } from './app/Participant';
import { EventDispatcher } from './app/EventDispatcher';
import { Signaling, SignalingEvent, SignalingEventType } from './app/Signaling';
import { SocketChannel } from './app/SocketChannel';
export {
Room,
Participant,
EventDispatcher,
Signaling,
SignalingEvent,
SignalingEventType,
SocketChannel,
};
export default PeerData;
| Use require instead of import | Use require instead of import
| TypeScript | mit | Vardius/peer-data,Vardius/peer-data | ---
+++
@@ -1,4 +1,5 @@
-import 'webrtc-adapter';
+// tslint:disable-next-line: no-require-imports no-var-requires
+require('webrtc-adapter');
import { App as PeerData } from './app/App';
|
ee34aded73eb73728b7baa7f8eb9aee4995c5c88 | src/marketplace/resources/list/ProjectResourcesContainer.tsx | src/marketplace/resources/list/ProjectResourcesContainer.tsx | import { useCurrentStateAndParams } from '@uirouter/react';
import * as React from 'react';
import useAsync from 'react-use/lib/useAsync';
import { LoadingSpinner } from '@waldur/core/LoadingSpinner';
import { translate } from '@waldur/i18n';
import { getCategory } from '@waldur/marketplace/common/api';
import { useTitle } from '@waldur/navigation/title';
import { ProjectResourcesList } from './ProjectResourcesList';
async function loadData(category_uuid) {
const category = await getCategory(category_uuid, {
params: { field: ['columns', 'title'] },
});
return { columns: category.columns, title: category.title };
}
export const ProjectResourcesContainer: React.FC<{}> = () => {
const {
params: { category_uuid },
} = useCurrentStateAndParams();
const { loading, value, error } = useAsync(() => loadData(category_uuid), [
category_uuid,
]);
useTitle(
value
? translate('{category} resources', { category: value.title })
: translate('Project resources'),
);
if (loading) {
return <LoadingSpinner />;
} else if (error) {
return <>{translate('Unable to load marketplace category details')}</>;
} else {
return (
<ProjectResourcesList
columns={value.columns}
category_uuid={category_uuid}
/>
);
}
};
| import { useCurrentStateAndParams } from '@uirouter/react';
import * as React from 'react';
import { useSelector } from 'react-redux';
import useAsync from 'react-use/lib/useAsync';
import { LoadingSpinner } from '@waldur/core/LoadingSpinner';
import { translate } from '@waldur/i18n';
import { getCategory } from '@waldur/marketplace/common/api';
import { useTitle } from '@waldur/navigation/title';
import { getProject } from '@waldur/workspace/selectors';
import { ProjectResourcesList } from './ProjectResourcesList';
async function loadData(category_uuid) {
const category = await getCategory(category_uuid, {
params: { field: ['columns', 'title'] },
});
return { columns: category.columns, title: category.title };
}
export const ProjectResourcesContainer: React.FC<{}> = () => {
const {
params: { category_uuid },
} = useCurrentStateAndParams();
const { loading, value, error } = useAsync(() => loadData(category_uuid), [
category_uuid,
]);
useTitle(
value
? translate('{category} resources', { category: value.title })
: translate('Project resources'),
);
const project = useSelector(getProject);
if (!project) {
return null;
}
if (loading) {
return <LoadingSpinner />;
} else if (error) {
return <>{translate('Unable to load marketplace category details')}</>;
} else {
return (
<ProjectResourcesList
columns={value.columns}
category_uuid={category_uuid}
/>
);
}
};
| Fix crash when going resource category to details and back | Fix crash when going resource category to details and back [WAL-3190]
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -1,11 +1,13 @@
import { useCurrentStateAndParams } from '@uirouter/react';
import * as React from 'react';
+import { useSelector } from 'react-redux';
import useAsync from 'react-use/lib/useAsync';
import { LoadingSpinner } from '@waldur/core/LoadingSpinner';
import { translate } from '@waldur/i18n';
import { getCategory } from '@waldur/marketplace/common/api';
import { useTitle } from '@waldur/navigation/title';
+import { getProject } from '@waldur/workspace/selectors';
import { ProjectResourcesList } from './ProjectResourcesList';
@@ -31,6 +33,11 @@
: translate('Project resources'),
);
+ const project = useSelector(getProject);
+ if (!project) {
+ return null;
+ }
+
if (loading) {
return <LoadingSpinner />;
} else if (error) { |
920f676d3b448a84953584a344a6eaba4b462ca9 | templates/expo-template-tabs/App.tsx | templates/expo-template-tabs/App.tsx | import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import useCachedResources from './hooks/useCachedResources';
import useColorScheme from './hooks/useColorScheme';
import Navigation from './navigation';
export default function App() {
const isLoadingComplete = useCachedResources();
const colorScheme = useColorScheme();
if (!isLoadingComplete) {
return null;
} else {
return (
<SafeAreaProvider>
<Navigation colorScheme={colorScheme} />
<StatusBar />
</SafeAreaProvider>
);
}
}
| import 'react-native-gesture-handler';
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import useCachedResources from './hooks/useCachedResources';
import useColorScheme from './hooks/useColorScheme';
import Navigation from './navigation';
export default function App() {
const isLoadingComplete = useCachedResources();
const colorScheme = useColorScheme();
if (!isLoadingComplete) {
return null;
} else {
return (
<SafeAreaProvider>
<Navigation colorScheme={colorScheme} />
<StatusBar />
</SafeAreaProvider>
);
}
}
| Add react-native-gesture-handler import to tabs template | [templates] Add react-native-gesture-handler import to tabs template
| TypeScript | bsd-3-clause | exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponentjs/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent,exponent/exponent,exponent/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent | ---
+++
@@ -1,3 +1,4 @@
+import 'react-native-gesture-handler';
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { SafeAreaProvider } from 'react-native-safe-area-context'; |
dbbbdca566f4290afbbd9f23ad40fccf2ac6cc87 | test/mock-request-animation-frame.ts | test/mock-request-animation-frame.ts | /**
* Poor man's polyfill for raf.
*/
// @ts-ignore
global.window = global
window.addEventListener = () => {}
window.requestAnimationFrame = () => 1
| /**
* Poor man's polyfill for raf.
*/
// @ts-ignore
global.window = global
window.addEventListener = (): void => {}
window.requestAnimationFrame = (): number => 1
| Fix ESLint errors in test | Fix ESLint errors in test
| TypeScript | agpl-3.0 | briandk/transcriptase,briandk/transcriptase | ---
+++
@@ -4,5 +4,5 @@
// @ts-ignore
global.window = global
-window.addEventListener = () => {}
-window.requestAnimationFrame = () => 1
+window.addEventListener = (): void => {}
+window.requestAnimationFrame = (): number => 1 |
2c00c079cf1a4f0d306393c07b4372ee050adae5 | app/src/components/Post/index.tsx | app/src/components/Post/index.tsx | import * as React from 'react';
import Card from 'material-ui/Card';
import { withStyles } from 'material-ui/styles';
interface Props {
userName: string;
text: string;
channelName: string;
}
const styles = theme => ({
card: {
minWidth: 275,
},
bullet: {
display: 'inline-block',
margin: '0 2px',
transform: 'scale(0.8)',
},
title: {
marginBottom: 16,
fontSize: 14,
color: theme.palette.text.secondary,
},
pos: {
marginBottom: 12,
color: theme.palette.text.secondary,
},
});
class Post extends React.Component < any, any > {
constructor(props) {
super(props);
this.props = props;
}
render() {
return (
<div style={{ margin: '20px' }}>
<Card style={{ padding: '10px' }}>
{this.props.text}
</Card>
</div>
);
}
}
export default withStyles(styles)(Post);
| import * as React from 'react';
import Card, { CardContent } from 'material-ui/Card';
import Typography from 'material-ui/Typography';
import { withStyles } from 'material-ui/styles';
interface Props {
userName: string;
text: string;
channelName: string;
}
const styles = theme => ({
card: {
minWidth: 275,
},
title: {
marginBottom: 16,
fontSize: 14,
color: theme.palette.text.secondary,
},
});
class Post extends React.Component < any, any > {
constructor(props) {
super(props);
this.props = props;
}
render() {
return (
<div style={{ margin: '20px' }}>
<Card style={{ padding: '10px' }}>
<CardContent>
<Typography>
{this.props.channel}
{this.props.user}
</Typography>
<Typography>
{this.props.text}
</Typography>
</CardContent>
</Card>
</div>
);
}
}
export default withStyles(styles)(Post);
| Add typography for unity theme | Add typography for unity theme
| TypeScript | mit | tanishi/Slackker,tanishi/Slackker,tanishi/Slackker | ---
+++
@@ -1,5 +1,6 @@
import * as React from 'react';
-import Card from 'material-ui/Card';
+import Card, { CardContent } from 'material-ui/Card';
+import Typography from 'material-ui/Typography';
import { withStyles } from 'material-ui/styles';
@@ -13,18 +14,9 @@
card: {
minWidth: 275,
},
- bullet: {
- display: 'inline-block',
- margin: '0 2px',
- transform: 'scale(0.8)',
- },
title: {
marginBottom: 16,
fontSize: 14,
- color: theme.palette.text.secondary,
- },
- pos: {
- marginBottom: 12,
color: theme.palette.text.secondary,
},
});
@@ -39,7 +31,15 @@
return (
<div style={{ margin: '20px' }}>
<Card style={{ padding: '10px' }}>
- {this.props.text}
+ <CardContent>
+ <Typography>
+ {this.props.channel}
+ {this.props.user}
+ </Typography>
+ <Typography>
+ {this.props.text}
+ </Typography>
+ </CardContent>
</Card>
</div>
); |
041e6bf2579b964e57f3b0a80dc56d2aa9fb8d80 | src/routes/file.ts | src/routes/file.ts | import * as fs from 'fs';
import {ReadStream} from 'fs';
export default {
test: (uri: string): boolean => /^\.|^\//.test(uri) || /^[a-zA-Z]:\\[\\\S|*\S]?.*$/g.test(uri),
read: (path: string): Promise<ReadStream> => {
return new Promise((resolve, reject) => {
let readStream = null;
try {
readStream = fs.createReadStream(path);
} catch (e) {
reject(e);
}
resolve(readStream);
});
}
};
| import * as fs from 'fs';
import {ReadStream} from 'fs';
export default {
test: (uri: string): boolean => {
if (process.platform === 'win32') {
return /^[a-zA-Z]:\\[\\\S|*\S]?.*$/g.test(uri);
}
return /^\.|^\//.test(uri)
},
read: (path: string): Promise<ReadStream> => {
return new Promise((resolve, reject) => {
let readStream = null;
try {
readStream = fs.createReadStream(path);
} catch (e) {
reject(e);
}
resolve(readStream);
});
}
};
| Add path check for windows | Add path check for windows
| TypeScript | mit | kicumkicum/stupid-player,kicumkicum/stupid-player | ---
+++
@@ -2,7 +2,13 @@
import {ReadStream} from 'fs';
export default {
- test: (uri: string): boolean => /^\.|^\//.test(uri) || /^[a-zA-Z]:\\[\\\S|*\S]?.*$/g.test(uri),
+ test: (uri: string): boolean => {
+ if (process.platform === 'win32') {
+ return /^[a-zA-Z]:\\[\\\S|*\S]?.*$/g.test(uri);
+ }
+
+ return /^\.|^\//.test(uri)
+ },
read: (path: string): Promise<ReadStream> => {
return new Promise((resolve, reject) => { |
35d926b9595513d889f025b187a7da8b444252ce | src/options/fields/icon.ts | src/options/fields/icon.ts | import * as log from 'loglevel';
import { inferIcon } from '../../infer/inferIcon';
type IconParams = {
packager: {
icon?: string;
targetUrl: string;
platform?: string;
};
};
export async function icon(options: IconParams): Promise<string> {
if (options.packager.icon) {
log.debug('Got icon from options. Using it, no inferring needed');
return null;
}
try {
return await inferIcon(
options.packager.targetUrl,
options.packager.platform,
);
} catch (error) {
log.warn('Cannot automatically retrieve the app icon:', error);
return null;
}
}
| import * as log from 'loglevel';
import { inferIcon } from '../../infer/inferIcon';
type IconParams = {
packager: {
icon?: string;
targetUrl: string;
platform?: string;
};
};
export async function icon(options: IconParams): Promise<string> {
if (options.packager.icon) {
log.debug('Got icon from options. Using it, no inferring needed');
return null;
}
try {
return await inferIcon(
options.packager.targetUrl,
options.packager.platform,
);
} catch (error) {
log.warn(
'Cannot automatically retrieve the app icon:',
error.message || '',
);
return null;
}
}
| Fix inferIcon error surfacing in full since recent axios | Fix inferIcon error surfacing in full since recent axios
| TypeScript | bsd-2-clause | jiahaog/Nativefier,jiahaog/Nativefier,jiahaog/Nativefier | ---
+++
@@ -22,7 +22,10 @@
options.packager.platform,
);
} catch (error) {
- log.warn('Cannot automatically retrieve the app icon:', error);
+ log.warn(
+ 'Cannot automatically retrieve the app icon:',
+ error.message || '',
+ );
return null;
}
} |
846d0182b86bccfb0d578a42dc4318f9cf6c7eab | src/types/brand.ts | src/types/brand.ts | import { Runtype, Static, create } from '../runtype';
export declare const RuntypeName: unique symbol;
export interface RuntypeBrand<B extends string> {
[RuntypeName]: B;
}
export interface Brand<B extends string, A extends Runtype>
extends Runtype<
// TODO: replace it by nominal type when it has been released
// https://github.com/microsoft/TypeScript/pull/33038
Static<A> & RuntypeBrand<B>
> {
tag: 'brand';
brand: B;
entity: A;
}
export function Brand<B extends string, A extends Runtype>(brand: B, entity: A) {
return create<Brand<B, A>>(
value => {
const validated = entity.validate(value);
return validated.success
? { success: true, value: validated.value as Static<Brand<B, A>> }
: validated;
},
{
tag: 'brand',
brand,
entity,
},
);
}
| import { Runtype, Static, create } from '../runtype';
export declare const RuntypeName: unique symbol;
export interface RuntypeBrand<B extends string> {
[RuntypeName]: B;
}
export interface Brand<B extends string, A extends Runtype>
extends Runtype<
// TODO: replace it by nominal type when it has been released
// https://github.com/microsoft/TypeScript/pull/33038
Static<A> & RuntypeBrand<B>
> {
tag: 'brand';
brand: B;
entity: A;
}
export function Brand<B extends string, A extends Runtype>(brand: B, entity: A) {
return create<any>(value => entity.validate(value), {
tag: 'brand',
brand,
entity,
});
}
| Remove unnecessary code from `Brand` | Remove unnecessary code from `Brand`
| TypeScript | mit | pelotom/runtypes,pelotom/runtypes | ---
+++
@@ -18,17 +18,9 @@
}
export function Brand<B extends string, A extends Runtype>(brand: B, entity: A) {
- return create<Brand<B, A>>(
- value => {
- const validated = entity.validate(value);
- return validated.success
- ? { success: true, value: validated.value as Static<Brand<B, A>> }
- : validated;
- },
- {
- tag: 'brand',
- brand,
- entity,
- },
- );
+ return create<any>(value => entity.validate(value), {
+ tag: 'brand',
+ brand,
+ entity,
+ });
} |
92b23eb97a86811e45982d1232151e1e9f11d4c8 | types/koa-cors/koa-cors-tests.ts | types/koa-cors/koa-cors-tests.ts | import Koa = require('koa');
import KoaCors = require('koa-cors');
const app = new Koa();
app.use(KoaCors());
app.use(KoaCors({}));
app.use(KoaCors({ origin: '*' }));
| import Koa = require('koa');
import koaCors = require('koa-cors');
const app = new Koa();
app.use(koaCors());
app.use(koaCors({ origin: '*' }));
| Fix code style -- Remove useless test | Fix code style -- Remove useless test
| TypeScript | mit | dsebastien/DefinitelyTyped,AgentME/DefinitelyTyped,AgentME/DefinitelyTyped,borisyankov/DefinitelyTyped,markogresak/DefinitelyTyped,georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,AgentME/DefinitelyTyped,magny/DefinitelyTyped,georgemarshall/DefinitelyTyped,magny/DefinitelyTyped,mcliment/DefinitelyTyped | ---
+++
@@ -1,7 +1,6 @@
import Koa = require('koa');
-import KoaCors = require('koa-cors');
+import koaCors = require('koa-cors');
const app = new Koa();
-app.use(KoaCors());
-app.use(KoaCors({}));
-app.use(KoaCors({ origin: '*' }));
+app.use(koaCors());
+app.use(koaCors({ origin: '*' })); |
e25c1e7aaf77dcea44a22fc82e06509422df15d9 | src/devices/ArchivedDevice.tsx | src/devices/ArchivedDevice.tsx | /**
* Copyright 2018-present Facebook.
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* @format
*/
import BaseDevice from './BaseDevice';
import {DeviceType, OS, DeviceShell, DeviceLogEntry} from './BaseDevice';
export default class ArchivedDevice extends BaseDevice {
// @ts-ignore: Super needs to be on the first line
constructor(
serial: string,
deviceType: DeviceType,
title: string,
os: OS,
logEntries: Array<DeviceLogEntry>,
) {
let archivedDeviceType = deviceType;
if (archivedDeviceType === 'emulator') {
archivedDeviceType = 'archivedEmulator';
} else if (archivedDeviceType === 'physical') {
archivedDeviceType = 'archivedPhysical';
}
super(serial, archivedDeviceType, title, os);
this.logs = logEntries;
}
logs: Array<DeviceLogEntry>;
isArchived = true;
getLogs() {
return this.logs;
}
clearLogs(): Promise<void> {
this.logs = [];
return Promise.resolve();
}
spawnShell(): DeviceShell | undefined | null {
return null;
}
}
| /**
* Copyright 2018-present Facebook.
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* @format
*/
import BaseDevice from './BaseDevice';
import {DeviceType, OS, DeviceShell, DeviceLogEntry} from './BaseDevice';
function normalizeArchivedDeviceType(deviceType: DeviceType): DeviceType {
let archivedDeviceType = deviceType;
if (archivedDeviceType === 'emulator') {
archivedDeviceType = 'archivedEmulator';
} else if (archivedDeviceType === 'physical') {
archivedDeviceType = 'archivedPhysical';
}
return archivedDeviceType;
}
export default class ArchivedDevice extends BaseDevice {
constructor(
serial: string,
deviceType: DeviceType,
title: string,
os: OS,
logEntries: Array<DeviceLogEntry>,
) {
super(serial, normalizeArchivedDeviceType(deviceType), title, os);
this.logs = logEntries;
}
logs: Array<DeviceLogEntry>;
isArchived = true;
getLogs() {
return this.logs;
}
clearLogs(): Promise<void> {
this.logs = [];
return Promise.resolve();
}
spawnShell(): DeviceShell | undefined | null {
return null;
}
}
| Remove unnecessary ts-ignore for archive | Remove unnecessary ts-ignore for archive
Summary:
This is a pretty broad ignore which doesn't seem required
but could hide real bugs.
Reviewed By: jknoxville
Differential Revision: D17342033
fbshipit-source-id: c7941e383936e44e39eff3fb7eced1d85a0d6417
| TypeScript | mit | facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper | ---
+++
@@ -7,8 +7,17 @@
import BaseDevice from './BaseDevice';
import {DeviceType, OS, DeviceShell, DeviceLogEntry} from './BaseDevice';
+function normalizeArchivedDeviceType(deviceType: DeviceType): DeviceType {
+ let archivedDeviceType = deviceType;
+ if (archivedDeviceType === 'emulator') {
+ archivedDeviceType = 'archivedEmulator';
+ } else if (archivedDeviceType === 'physical') {
+ archivedDeviceType = 'archivedPhysical';
+ }
+ return archivedDeviceType;
+}
+
export default class ArchivedDevice extends BaseDevice {
- // @ts-ignore: Super needs to be on the first line
constructor(
serial: string,
deviceType: DeviceType,
@@ -16,13 +25,7 @@
os: OS,
logEntries: Array<DeviceLogEntry>,
) {
- let archivedDeviceType = deviceType;
- if (archivedDeviceType === 'emulator') {
- archivedDeviceType = 'archivedEmulator';
- } else if (archivedDeviceType === 'physical') {
- archivedDeviceType = 'archivedPhysical';
- }
- super(serial, archivedDeviceType, title, os);
+ super(serial, normalizeArchivedDeviceType(deviceType), title, os);
this.logs = logEntries;
}
|
a2e1931723d3d0df97ce65d154e7be7ca5779779 | framework/src/HandleRequest.ts | framework/src/HandleRequest.ts | import _cloneDeep from 'lodash.clonedeep';
import _merge from 'lodash.merge';
import { App, AppConfig, AppInitConfig, AppMiddlewares } from './App';
import { Extensible } from './Extensible';
import { ComponentTree, ComponentTreeNode, MiddlewareCollection, Platform } from './index';
import { Server } from './Server';
export class HandleRequest extends Extensible<AppConfig, AppMiddlewares> {
readonly componentTree!: ComponentTree;
activeComponentNode?: ComponentTreeNode;
platform!: Platform;
constructor(readonly app: App, readonly server: Server) {
super(_cloneDeep(app.config) as AppInitConfig);
_merge(this, _cloneDeep(app));
}
get platforms(): ReadonlyArray<Platform> {
return Object.values(this.plugins).filter((plugin) => plugin instanceof Platform) as Platform[];
}
// middlewareCollection will be overwritten anyways by merging with App
initializeMiddlewareCollection(): App['middlewareCollection'] {
return new MiddlewareCollection();
}
getDefaultConfig(): AppConfig {
return {
intentMap: {},
logging: {},
};
}
mount(): Promise<void> {
return this.mountPlugins();
}
dismount(): Promise<void> {
return this.dismountPlugins();
}
stopMiddlewareExecution(): void {
this.middlewareCollection.remove(...this.middlewareCollection.names);
}
}
| import _cloneDeep from 'lodash.clonedeep';
import _merge from 'lodash.merge';
import { App, AppConfig, AppInitConfig, AppMiddlewares } from './App';
import { Extensible } from './Extensible';
import { ComponentTree, ComponentTreeNode, MiddlewareCollection, Platform } from './index';
import { Server } from './Server';
export class HandleRequest extends Extensible<AppConfig, AppMiddlewares> {
readonly componentTree!: ComponentTree;
activeComponentNode?: ComponentTreeNode;
platform!: Platform;
constructor(readonly app: App, readonly server: Server) {
super(_cloneDeep(app.config) as AppInitConfig);
_merge(this, _cloneDeep(app));
}
get platforms(): ReadonlyArray<Platform> {
return Object.values(this.plugins).filter((plugin) => plugin instanceof Platform) as Platform[];
}
// middlewareCollection will be overwritten anyways by merging with App
initializeMiddlewareCollection(): App['middlewareCollection'] {
return new MiddlewareCollection();
}
getDefaultConfig(): AppConfig {
return {
intentMap: {},
logging: {},
};
}
mount(): Promise<void> {
return this.mountPlugins();
}
dismount(): Promise<void> {
return this.dismountPlugins();
}
stopMiddlewareExecution(): void {
this.middlewareCollection.clear();
Object.values(this.plugins).forEach((plugin) => {
if (plugin instanceof Extensible) {
plugin.middlewareCollection.clear();
}
});
}
}
| Update logic for stopping the middleware-execution | :necktie: Update logic for stopping the middleware-execution
- The MiddlewareCollections of the child-plugins will also be cleared. Theoretically this could be called recursively to clear **all** middlewares.
| TypeScript | apache-2.0 | jovotech/jovo-framework-nodejs,jovotech/jovo-framework-nodejs | ---
+++
@@ -40,6 +40,11 @@
}
stopMiddlewareExecution(): void {
- this.middlewareCollection.remove(...this.middlewareCollection.names);
+ this.middlewareCollection.clear();
+ Object.values(this.plugins).forEach((plugin) => {
+ if (plugin instanceof Extensible) {
+ plugin.middlewareCollection.clear();
+ }
+ });
}
} |
6361458fde9bc640c6453667f8ca560e5198b4e9 | front_end/ui/components/docs/component_docs.ts | front_end/ui/components/docs/component_docs.ts | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Ensure all image variables are defined in the component docs.
import '../Images/Images.js';
import * as CreateBreadcrumbs from './create_breadcrumbs.js';
import * as ToggleDarkMode from './toggle_dark_mode.js';
ToggleDarkMode.init();
CreateBreadcrumbs.init();
| // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Ensure all image variables are defined in the component docs.
import '../../../Images/Images.js';
import * as CreateBreadcrumbs from './create_breadcrumbs.js';
import * as ToggleDarkMode from './toggle_dark_mode.js';
ToggleDarkMode.init();
CreateBreadcrumbs.init();
| Fix component docs server image path | Fix component docs server image path
Bug: 1187573
Change-Id: Iaa8f2ca48176d0a9d59115dce460764d736139ab
Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/2826307
Commit-Queue: Jack Franklin <[email protected]>
Commit-Queue: Tim van der Lippe <[email protected]>
Auto-Submit: Jack Franklin <[email protected]>
Reviewed-by: Tim van der Lippe <[email protected]>
| TypeScript | bsd-3-clause | ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend | ---
+++
@@ -3,7 +3,7 @@
// found in the LICENSE file.
// Ensure all image variables are defined in the component docs.
-import '../Images/Images.js';
+import '../../../Images/Images.js';
import * as CreateBreadcrumbs from './create_breadcrumbs.js';
import * as ToggleDarkMode from './toggle_dark_mode.js'; |
d666a0be328fb3667864088aaf10c0fba8e0f2cb | services/QuillLessons/app/interfaces/customize.ts | services/QuillLessons/app/interfaces/customize.ts | import * as CLIntF from './ClassroomLessons'
export interface EditionMetadata {
key: string,
last_published_at: number,
lesson_id: string,
name: string,
sample_question: string,
user_id: number,
flags?: Array<string>,
lessonName?: string,
id?: string
}
export interface EditionQuestions {
questions: Array<CLIntF.Question>;
id?: string;
}
export interface EditionsMetadata {
[key:string]: EditionMetadata;
}
| import * as CLIntF from './classroomLessons'
export interface EditionMetadata {
key: string,
last_published_at: number,
lesson_id: string,
name: string,
sample_question: string,
user_id: number,
flags?: Array<string>,
lessonName?: string,
id?: string
}
export interface EditionQuestions {
questions: Array<CLIntF.Question>;
id?: string;
}
export interface EditionsMetadata {
[key:string]: EditionMetadata;
}
| Save file with correct case | Save file with correct case
| TypeScript | agpl-3.0 | empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core | ---
+++
@@ -1,4 +1,4 @@
-import * as CLIntF from './ClassroomLessons'
+import * as CLIntF from './classroomLessons'
export interface EditionMetadata {
key: string, |
6377c6294b469dd681e082d930696ceceb126379 | use-subscription/index.d.ts | use-subscription/index.d.ts | import { Context } from 'react'
type SubscribingOptions = {
/**
* Context with the store.
*/
context?: Context<object>
}
export type Channel = string | {
channel: string
[extra: string]: any
}
/**
* Hook to subscribe for channel during component render and unsubscribe
* on component unmount.
*
* ```js
* import useSubscription from '@logux/redux'
* import { useSelector } from 'react-redux'
*
* const UserPage = ({ userId }) => {
* const isSubscribing = useSubscription([`user/${ userId }`])
* const user = useSelector(state => state.users.find(i => i.id === userId))
* if (isSubscribing) {
* return <Loader />
* } else {
* return <h1>{ user.name }</h1>
* }
* }
* ```
*
* @param channels Channels to subscribe.
* @param opts Options
* @return `true` during data loading.
*/
export function useSubscription(
channels: Channel[],
opts?: SubscribingOptions
): boolean
| import { Context as ReduxContext } from 'react'
type SubscribingOptions = {
/**
* Context with the store.
*/
context?: ReduxContext<object>
}
export type Channel = string | {
channel: string
[extra: string]: any
}
/**
* Hook to subscribe for channel during component render and unsubscribe
* on component unmount.
*
* ```js
* import useSubscription from '@logux/redux'
* import { useSelector } from 'react-redux'
*
* const UserPage = ({ userId }) => {
* const isSubscribing = useSubscription([`user/${ userId }`])
* const user = useSelector(state => state.users.find(i => i.id === userId))
* if (isSubscribing) {
* return <Loader />
* } else {
* return <h1>{ user.name }</h1>
* }
* }
* ```
*
* @param channels Channels to subscribe.
* @param opts Options
* @return `true` during data loading.
*/
export function useSubscription(
channels: Channel[],
opts?: SubscribingOptions
): boolean
| Fix name conflict in useSubscription too | Fix name conflict in useSubscription too
| TypeScript | mit | logux/logux-redux | ---
+++
@@ -1,10 +1,10 @@
-import { Context } from 'react'
+import { Context as ReduxContext } from 'react'
type SubscribingOptions = {
/**
* Context with the store.
*/
- context?: Context<object>
+ context?: ReduxContext<object>
}
export type Channel = string | { |
480d83fff544a147caee4222820755e11b3c4a36 | src/actions/fetchingActions.ts | src/actions/fetchingActions.ts | import { ActionCreator } from '../types';
import 'isomorphic-fetch';
const setFetching = new ActionCreator<'SetFetching', boolean>('SetFetching');
const fetchServerData = {
create: () => {
return (dispatch: (action: any) => void) => {
dispatch(setFetching.create(true));
return fetch('/src/seedData.json')
.then((response) => response.json())
.then((json) => {
console.log(json);
dispatch(setFetching.create(false));
})
.catch((reason) => {
console.error('fetch error', reason);
window.alert('Error fetching data');
dispatch(setFetching.create(false));
});
};
},
};
export const ActionCreators = {
FetchServerData: fetchServerData,
SetFetching: setFetching,
};
| import { ActionCreator } from '../types';
import { ActionCreators as TodoActionCreators } from './todoActions';
import 'isomorphic-fetch';
const setFetching = new ActionCreator<'SetFetching', boolean>('SetFetching');
const fetchServerData = {
create: () => {
return (dispatch: (action: any) => void) => {
dispatch(setFetching.create(true));
return fetch('/src/seedData.json')
.then((response) => response.json())
.then((json) => {
dispatch(TodoActionCreators.SetTodos.create({ todos: json }));
dispatch(setFetching.create(false));
})
.catch((reason) => {
console.error('fetch error', reason);
window.alert('Error fetching data');
dispatch(setFetching.create(false));
});
};
},
};
export const ActionCreators = {
FetchServerData: fetchServerData,
SetFetching: setFetching,
};
| Set todos on server refresh | Set todos on server refresh
| TypeScript | mit | markschabacker/todoMVC_react,markschabacker/todoMVC_react,markschabacker/todoMVC_react | ---
+++
@@ -1,4 +1,5 @@
import { ActionCreator } from '../types';
+import { ActionCreators as TodoActionCreators } from './todoActions';
import 'isomorphic-fetch';
@@ -11,7 +12,7 @@
return fetch('/src/seedData.json')
.then((response) => response.json())
.then((json) => {
- console.log(json);
+ dispatch(TodoActionCreators.SetTodos.create({ todos: json }));
dispatch(setFetching.create(false));
})
.catch((reason) => { |
904df7ee400fb39e08e43eec692d842461a53653 | app/components/placeholder.tsx | app/components/placeholder.tsx | export default function Placeholder({ onClick }: { onClick: () => void }) {
return (
<div className="container">
<style jsx={true}>{`
.container {
display: flex;
flex-direction: column;
align-items: center;
}
.logo {
width: 140px;
height: 140px;
}
h1 {
font-weight: normal;
}
`}</style>
<a href="#" onClick={(e) => onClick()}>
<img src="/popcorn-large.png" className="logo" />
</a>
<h1>Welcome to Popcorn GIF</h1>
</div>
);
}
| export default function Placeholder({ onClick }: { onClick: () => void }) {
return (
<div className="container">
<style jsx={true}>{`
.container {
display: flex;
flex-direction: column;
align-items: center;
}
.logo {
width: 140px;
height: 140px;
}
h1 {
font-size: 1.536rem;
font-weight: normal;
}
`}</style>
<a href="#" onClick={(e) => onClick()}>
<img src="/popcorn-large.png" className="logo" />
</a>
<h1>Welcome to Popcorn GIF</h1>
</div>
);
}
| Tweak title text font weight | Tweak title text font weight
| TypeScript | apache-2.0 | thenickreynolds/popcorngif,thenickreynolds/popcorngif | ---
+++
@@ -14,6 +14,7 @@
}
h1 {
+ font-size: 1.536rem;
font-weight: normal;
}
`}</style> |
8e7b26f32212461b96bbd7a29b4c113110c8baaa | ui/test/config.spec.ts | ui/test/config.spec.ts | "use strict";
import chai from "chai";
import {Config} from "../src/app/config";
import {RouterConfigurationStub} from "./stubs";
describe("Config test suite", () => {
it("should initialize correctly", () => {
let routerConfiguration = new RouterConfigurationStub();
let sut = new Config();
sut.configureRouter(routerConfiguration);
chai.expect(routerConfiguration.title).to.equals("Hello World");
chai.expect(routerConfiguration.map.calledOnce).to.equals(true);
});
});
| "use strict";
import chai from "chai";
import {Config} from "../src/app/config";
import {RouterConfigurationStub} from "./stubs";
describe("Config test suite", () => {
it("should initialize correctly", () => {
let routerConfiguration = new RouterConfigurationStub();
let sut = new Config();
sut.configureRouter(routerConfiguration);
chai.expect(routerConfiguration.title).to.equals("Hello Worl1d");
chai.expect(routerConfiguration.map.calledOnce).to.equals(true);
});
});
| Test if CI fails on a broken unit test. | Test if CI fails on a broken unit test.
| TypeScript | mit | jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr | ---
+++
@@ -12,7 +12,7 @@
sut.configureRouter(routerConfiguration);
- chai.expect(routerConfiguration.title).to.equals("Hello World");
+ chai.expect(routerConfiguration.title).to.equals("Hello Worl1d");
chai.expect(routerConfiguration.map.calledOnce).to.equals(true);
});
|
a10d56bafc31602dfee9b1c52bbf26ab9aca366a | client/src/app/+admin/users/user-edit/user-edit.ts | client/src/app/+admin/users/user-edit/user-edit.ts | import { FormReactive } from '../../../shared'
export abstract class UserEdit extends FormReactive {
videoQuotaOptions = [
{ value: -1, label: 'Unlimited' },
{ value: 100 * 1024 * 1024, label: '100MB' },
{ value: 5 * 1024 * 1024, label: '500MB' },
{ value: 1024 * 1024 * 1024, label: '1GB' },
{ value: 5 * 1024 * 1024 * 1024, label: '5GB' },
{ value: 20 * 1024 * 1024 * 1024, label: '20GB' },
{ value: 50 * 1024 * 1024 * 1024, label: '50GB' }
]
abstract isCreation (): boolean
abstract getFormButtonTitle (): string
}
| import { FormReactive } from '../../../shared'
export abstract class UserEdit extends FormReactive {
videoQuotaOptions = [
{ value: -1, label: 'Unlimited' },
{ value: 0, label: '0'},
{ value: 100 * 1024 * 1024, label: '100MB' },
{ value: 5 * 1024 * 1024, label: '500MB' },
{ value: 1024 * 1024 * 1024, label: '1GB' },
{ value: 5 * 1024 * 1024 * 1024, label: '5GB' },
{ value: 20 * 1024 * 1024 * 1024, label: '20GB' },
{ value: 50 * 1024 * 1024 * 1024, label: '50GB' }
]
abstract isCreation (): boolean
abstract getFormButtonTitle (): string
}
| Add ability to forbid user to upload video | Add ability to forbid user to upload video
| TypeScript | agpl-3.0 | Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube,Green-Star/PeerTube,Chocobozzz/PeerTube,Green-Star/PeerTube,Green-Star/PeerTube,Green-Star/PeerTube | ---
+++
@@ -3,6 +3,7 @@
export abstract class UserEdit extends FormReactive {
videoQuotaOptions = [
{ value: -1, label: 'Unlimited' },
+ { value: 0, label: '0'},
{ value: 100 * 1024 * 1024, label: '100MB' },
{ value: 5 * 1024 * 1024, label: '500MB' },
{ value: 1024 * 1024 * 1024, label: '1GB' }, |
cd51a94434bf698097fbab288057d2ec1cfd0964 | src/ui/document/doc.ts | src/ui/document/doc.ts | import anchorme from 'anchorme'
import { basename } from 'path'
import { loadFile } from '../../fs/load-file'
import * as storage from '../../fs/storage'
import { openLinksInExternalBrowser, setFileMenuItemsEnable } from '../../utils/general-utils'
import { anchormeOptions } from './anchorme-options'
import * as documentStyle from './document-style'
export class Doc {
private appName: string
private document: Document
private container: HTMLElement
constructor(appName: string, document: Document) {
this.appName = appName
this.document = document
this.container = document.getElementById('app_container')!
}
public open(filePath: string): void {
this.setTitle(`${basename(filePath)} - ${this.appName}`)
this.container.scrollIntoView()
this.setText(anchorme(loadFile(filePath), anchormeOptions))
documentStyle.setLinkColor(storage.getLinkColor())
openLinksInExternalBrowser()
setFileMenuItemsEnable(true)
}
public close(): void {
this.setTitle(this.appName)
this.setText('')
setFileMenuItemsEnable(false)
}
private setTitle(title: string): void {
this.document.title = title
}
private setText(text: string): void {
this.container.innerHTML = text
}
}
| import anchorme from 'anchorme'
import { basename } from 'path'
import { loadFile } from '../../fs/load-file'
import * as storage from '../../fs/storage'
import { openLinksInExternalBrowser, setFileMenuItemsEnable } from '../../utils/general-utils'
import { anchormeOptions } from './anchorme-options'
import * as documentStyle from './document-style'
export class Doc {
private appName: string
private document: Document
private container: HTMLElement
constructor(appName: string, document: Document) {
this.appName = appName
this.document = document
this.container = document.getElementById('app_container')!
}
public open(filePath: string): void {
this.setTitle(`${basename(filePath)} - ${this.appName}`)
this.container.scrollIntoView()
this.setText(anchorme(loadFile(filePath), anchormeOptions))
documentStyle.setLinkColor(storage.getLinkColor())
openLinksInExternalBrowser()
setFileMenuItemsEnable(true)
}
public close(): void {
this.setTitle(this.appName)
this.setText('')
setFileMenuItemsEnable(false)
}
private setTitle(title: string): void {
this.document.title = title
}
// Trim trailing spaces before newlines
private setText(text: string): void {
this.container.innerHTML = text.replace(/[^\S\r\n]+$/gm, '')
}
}
| Trim trailing spaces before newlines | Trim trailing spaces before newlines
| TypeScript | mit | nrlquaker/nfov,nrlquaker/nfov | ---
+++
@@ -36,7 +36,8 @@
this.document.title = title
}
+ // Trim trailing spaces before newlines
private setText(text: string): void {
- this.container.innerHTML = text
+ this.container.innerHTML = text.replace(/[^\S\r\n]+$/gm, '')
}
} |
ff30631929d2d8e6c64e04435af5c9198faf5fa6 | src/app/app.component.spec.ts | src/app/app.component.spec.ts | import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'mysterybot'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('mysterybot');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('.content span').textContent).toContain('mysterybot app is running!');
});
});
| import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
],
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'mysterybot'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('mysterybot');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('.content span').textContent).toContain('mysterybot app is running!');
});
});
| Remove stray reference to angular router | Remove stray reference to angular router
| TypeScript | apache-2.0 | google/mysteryofthreebots,google/mysteryofthreebots,google/mysteryofthreebots | ---
+++
@@ -1,12 +1,10 @@
import { TestBed, async } from '@angular/core/testing';
-import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
- RouterTestingModule
],
declarations: [
AppComponent |
4562b21304042769d6e7f567cecfd62381a308d5 | src/utils/formatting.ts | src/utils/formatting.ts | /**
* Trims leading and trailing whitespace and line terminators and replaces all
* characters after character 90 with an ellipsis.
* @param str
*/
export const truncate = (str: string, max = 90): string => {
const trimmed = str.trim();
return trimmed.length > max ? trimmed.slice(0, max).concat(' ...') : trimmed;
};
type Variation = 'positive' | 'negative' | 'strong' | 'subdued';
export const rewardToVariation = (reward: string): Variation => {
const amount = parseFloat(reward);
if (amount >= 1.0) {
return 'strong';
} else {
return 'subdued';
}
};
export const formatAsCurrency = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2
}).format;
| const currencyFormatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2
});
/**
* Trims leading and trailing whitespace and line terminators and replaces all
* characters after character 90 with an ellipsis.
* @param str
*/
export const truncate = (str: string, max = 90): string => {
const trimmed = str.trim();
return trimmed.length > max ? trimmed.slice(0, max).concat(' ...') : trimmed;
};
type Variation = 'positive' | 'negative' | 'strong' | 'subdued';
export const rewardToVariation = (reward: string): Variation => {
const amount = parseFloat(reward);
if (amount >= 1.0) {
return 'strong';
} else {
return 'subdued';
}
};
export const formatAsCurrency = currencyFormatter.format;
export const removeCurrencyFormatting = (input: string) =>
input.replace(/[^\d.]/g, '');
| Add utility function to strip dollar symbols and separators from currency strings. | Add utility function to strip dollar symbols and separators from currency strings.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -1,3 +1,9 @@
+const currencyFormatter = new Intl.NumberFormat('en-US', {
+ style: 'currency',
+ currency: 'USD',
+ minimumFractionDigits: 2
+});
+
/**
* Trims leading and trailing whitespace and line terminators and replaces all
* characters after character 90 with an ellipsis.
@@ -19,8 +25,7 @@
}
};
-export const formatAsCurrency = new Intl.NumberFormat('en-US', {
- style: 'currency',
- currency: 'USD',
- minimumFractionDigits: 2
-}).format;
+export const formatAsCurrency = currencyFormatter.format;
+
+export const removeCurrencyFormatting = (input: string) =>
+ input.replace(/[^\d.]/g, ''); |
bc1714955f1d2021a19b6e15e6cf8a48726aacc4 | src/utils/backup.ts | src/utils/backup.ts | import * as localforage from 'localforage';
export const persistedStateToStringArray = async () => {
try {
const localForageKeys: string[] = await localforage.keys();
return await Promise.all(
localForageKeys.map(
async key => `"${key}":` + (await localforage.getItem(key))
)
);
} catch (e) {
throw new Error('Failed to read user settings.');
}
};
export const generateBackupBlob = (stateStringArray: string[]): Blob =>
new Blob([stateStringArray.join('')], {
type: 'text/plain'
});
export const generateFileName = (): string =>
`mturk-engine-backup-${new Date().toLocaleDateString()}.bak`;
// static uploadDataFromFile = (stringifedUserSettings: string[]) => {
// const x = stringifedUserSettings.reduce((acc, cur: string) => {
// const [key, value] = cur.split(/"reduxPersist:(.*?)"/).slice(1);
// return { ...acc, [key]: value };
// }, {});
// console.log(x);
// };
export const createTemporaryDownloadLink = (blob: Blob): HTMLAnchorElement => {
const userSettingsBackup = window.URL.createObjectURL(blob);
const temporaryAnchor = document.createElement('a');
temporaryAnchor.href = userSettingsBackup;
temporaryAnchor.download = generateFileName();
return temporaryAnchor;
};
| import * as localforage from 'localforage';
export const persistedStateToStringArray = async () => {
try {
const localForageKeys: string[] = await localforage.keys();
return await Promise.all(
localForageKeys.map(
async key => `"${key}":` + (await localforage.getItem(key))
)
);
} catch (e) {
throw new Error('Failed to read user settings.');
}
};
export const generateBackupBlob = (stateStringArray: string[]): Blob =>
new Blob([stateStringArray.join('')], {
type: 'text/plain'
});
export const generateFileName = (): string =>
`mturk-engine-backup-${new Date().toLocaleDateString()}.bak`;
export const uploadDataFromFile = (settingsFile: File) => {
BackupFileInput.readAsText(settingsFile);
};
export const createTemporaryDownloadLink = (blob: Blob): HTMLAnchorElement => {
const userSettingsBackup = window.URL.createObjectURL(blob);
const temporaryAnchor = document.createElement('a');
temporaryAnchor.href = userSettingsBackup;
temporaryAnchor.download = generateFileName();
return temporaryAnchor;
};
export const BackupFileInput = new FileReader();
| Create utility function to instantiate a single BackupFileInput FileReader and read settingsfile as text. | Create utility function to instantiate a single BackupFileInput FileReader and read settingsfile as text.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -21,13 +21,9 @@
export const generateFileName = (): string =>
`mturk-engine-backup-${new Date().toLocaleDateString()}.bak`;
-// static uploadDataFromFile = (stringifedUserSettings: string[]) => {
-// const x = stringifedUserSettings.reduce((acc, cur: string) => {
-// const [key, value] = cur.split(/"reduxPersist:(.*?)"/).slice(1);
-// return { ...acc, [key]: value };
-// }, {});
-// console.log(x);
-// };
+export const uploadDataFromFile = (settingsFile: File) => {
+ BackupFileInput.readAsText(settingsFile);
+};
export const createTemporaryDownloadLink = (blob: Blob): HTMLAnchorElement => {
const userSettingsBackup = window.URL.createObjectURL(blob);
@@ -36,3 +32,5 @@
temporaryAnchor.download = generateFileName();
return temporaryAnchor;
};
+
+export const BackupFileInput = new FileReader(); |
904329ed5be8e36775a904112fd53ed41c6a4066 | packages/apollo-server-testing/src/createTestClient.ts | packages/apollo-server-testing/src/createTestClient.ts | import { ApolloServerBase } from 'apollo-server-core';
import { print, DocumentNode } from 'graphql';
type StringOrAst = string | DocumentNode;
// A query must not come with a mutation (and vice versa).
type Query = { query: StringOrAst; mutation?: undefined };
type Mutation = { mutation: StringOrAst; query?: undefined };
export default (server: ApolloServerBase) => {
const executeOperation = server.executeOperation.bind(server);
const test = ({ query, mutation, ...args }: Query | Mutation) => {
const operation = query || mutation;
if ((!query && !mutation) || (query && mutation)) {
throw new Error(
'Either `query` or `mutation` must be passed, but not both.',
);
}
return executeOperation({
// Convert ASTs, which are produced by `graphql-tag` but not currently
// used by `executeOperation`, to a String using `graphql/language/print`.
query: typeof operation === 'string' ? operation : print(operation),
...args,
});
};
return { query: test, mutate: test };
};
| import { ApolloServerBase } from 'apollo-server-core';
import { print, DocumentNode } from 'graphql';
type StringOrAst = string | DocumentNode;
// A query must not come with a mutation (and vice versa).
type Query = { query: StringOrAst; mutation?: undefined };
type Mutation = { mutation: StringOrAst; query?: undefined };
export default (server: ApolloServerBase) => {
const executeOperation = server.executeOperation.bind(server);
const test = ({ query, mutation, ...args }: Query | Mutation) => {
const operation = query || mutation;
if (!operation || (query && mutation)) {
throw new Error(
'Either `query` or `mutation` must be passed, but not both.',
);
}
return executeOperation({
// Convert ASTs, which are produced by `graphql-tag` but not currently
// used by `executeOperation`, to a String using `graphql/language/print`.
query: typeof operation === 'string' ? operation : print(operation),
...args,
});
};
return { query: test, mutate: test };
};
| Fix typing issue after missing `print` typing was added | Fix typing issue after missing `print` typing was added
See https://github.com/DefinitelyTyped/DefinitelyTyped/pull/34261/commits/0160812f04cef3ff14b611af46de9f9d6e654bbf
| TypeScript | mit | apollostack/apollo-server | ---
+++
@@ -12,7 +12,7 @@
const test = ({ query, mutation, ...args }: Query | Mutation) => {
const operation = query || mutation;
- if ((!query && !mutation) || (query && mutation)) {
+ if (!operation || (query && mutation)) {
throw new Error(
'Either `query` or `mutation` must be passed, but not both.',
); |
afef02d0070d5f6b78cbf584dd11d9aac055a715 | frontend/src/app/app.module.ts | frontend/src/app/app.module.ts | import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { routing, appRoutingProviders} from './app.routing';
import { AppComponent } from './app.component';
import { LoginComponent } from './components/login.component';
import { RegisterComponent } from './components/register.component';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
RegisterComponent
],
imports: [
routing,
BrowserModule,
FormsModule,
ReactiveFormsModule
],
providers: [
appRoutingProviders
],
bootstrap: [AppComponent]
})
export class AppModule { }
| import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { routing, appRoutingProviders} from './app.routing';
import { AppComponent } from './app.component';
import { LoginComponent } from './components/login.component';
import { RegisterComponent } from './components/register.component';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
RegisterComponent
],
imports: [
routing,
BrowserModule,
HttpModule,
FormsModule,
ReactiveFormsModule
],
providers: [
appRoutingProviders
],
bootstrap: [AppComponent]
})
export class AppModule { }
| Fix al importar el modulo Http. | Fix al importar el modulo Http.
| TypeScript | mit | maurobonfietti/webapp,maurobonfietti/webapp | ---
+++
@@ -1,4 +1,5 @@
import { BrowserModule } from '@angular/platform-browser';
+import { HttpModule } from '@angular/http';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@@ -18,6 +19,7 @@
imports: [
routing,
BrowserModule,
+ HttpModule,
FormsModule,
ReactiveFormsModule
], |
7572f954e1ab6698530d12eca414e0425e1090b0 | src/client/src/rt-system/AutoBahnTypeExtensions.ts | src/client/src/rt-system/AutoBahnTypeExtensions.ts | import { ConnectionType } from './connectionType'
interface TransportDefinition {
info: {
url: string
protocols?: string[]
type: ConnectionType
}
}
declare module 'autobahn' {
interface Connection {
transport: TransportDefinition
session: Session
}
}
| import { ConnectionType } from './connectionType'
interface TransportDefinition {
info: {
url: string
protocols?: string[]
type: ConnectionType
}
}
declare module 'autobahn' {
interface Connection {
transport: TransportDefinition
}
}
| Remove session from autobahn type extension | Remove session from autobahn type extension | TypeScript | apache-2.0 | AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud | ---
+++
@@ -11,6 +11,5 @@
declare module 'autobahn' {
interface Connection {
transport: TransportDefinition
- session: Session
}
} |
b1794b746c7a6f0d9dc15aebdc0abca030352c7a | src/Components/Search/Suggestions/SuggestionItemContainer.tsx | src/Components/Search/Suggestions/SuggestionItemContainer.tsx | import { Flex } from "@artsy/palette"
import React, { SFC } from "react"
interface Props {
children: JSX.Element[] | string[] | string
}
export const SuggestionItemContainer: SFC<Props> = ({ children }) => (
<Flex flexDirection="column" justifyContent="center" height="62px" pl={3}>
{children}
</Flex>
)
| import { Flex } from "@artsy/palette"
import React, { SFC } from "react"
interface Props {
children: React.ReactNode
}
export const SuggestionItemContainer: SFC<Props> = ({ children }) => (
<Flex flexDirection="column" justifyContent="center" height="62px" pl={3}>
{children}
</Flex>
)
| Use React.ReactNode as a type for {children} | Use React.ReactNode as a type for {children}
| TypeScript | mit | artsy/reaction,xtina-starr/reaction,xtina-starr/reaction,xtina-starr/reaction,artsy/reaction-force,artsy/reaction-force,artsy/reaction,artsy/reaction,xtina-starr/reaction | ---
+++
@@ -2,7 +2,7 @@
import React, { SFC } from "react"
interface Props {
- children: JSX.Element[] | string[] | string
+ children: React.ReactNode
}
export const SuggestionItemContainer: SFC<Props> = ({ children }) => ( |
3d5714b664b2daa8c97ba3f11f5808cfcf3570cb | test/converter/class/class.ts | test/converter/class/class.ts | /// <reference path="../lib.core.d.ts" />
/**
* TestClass comment short text.
*
* TestClass comment text.
*
* @see [[TestClass]] @ fixtures
*/
export class TestClass {
/**
* publicProperty short text.
*/
public publicProperty:string;
/**
* privateProperty short text.
*/
private privateProperty:number[];
/**
* privateProperty short text.
*/
static staticProperty:TestClass;
/**
* Constructor short text.
*/
constructor() { }
/**
* publicMethod short text.
*/
public publicMethod() {}
/**
* protectedMethod short text.
*/
protected protectedMethod() {}
/**
* privateMethod short text.
*/
private privateMethod() {}
/**
* staticMethod short text.
*/
static staticMethod() {}
}
export class TestSubClass extends TestClass
{
/**
* publicMethod short text.
*/
public publicMethod() {}
/**
* protectedMethod short text.
*/
protected protectedMethod() {}
} | /// <reference path="../lib.core.d.ts" />
/**
* TestClass comment short text.
*
* TestClass comment text.
*
* @see [[TestClass]] @ fixtures
*/
export class TestClass {
/**
* publicProperty short text.
*/
public publicProperty:string;
/**
* privateProperty short text.
*/
private privateProperty:number[];
/**
* privateProperty short text.
*/
static staticProperty:TestClass;
/**
* Constructor short text.
*/
constructor() { }
/**
* publicMethod short text.
*/
public publicMethod() {}
/**
* protectedMethod short text.
*/
protected protectedMethod() {}
/**
* privateMethod short text.
*/
private privateMethod() {}
/**
* staticMethod short text.
*/
static staticMethod() {}
}
export class TestSubClass extends TestClass
{
/**
* publicMethod short text.
*/
public publicMethod() {}
/**
* protectedMethod short text.
*/
protected protectedMethod() {}
/**
* Constructor short text.
*
* @param p1 Constructor param
* @param p2 Private string property
* @param p3 Public number property
* @param p4 Public implicit any property
*/
constructor(p1, private p2: string, public p3: number, public p4) {
super();
}
} | Update test file to cover constructor parameter properties | Update test file to cover constructor parameter properties
| TypeScript | apache-2.0 | aciccarello/typedoc,aciccarello/typedoc,sebilasse/typedoc,aciccarello/typedoc,TypeStrong/typedoc,adamhickey/typedoc,darkartur/typedoc,dominic31/typedoc,adamhickey/typedoc,sebilasse/typedoc,igor-bezkrovny/typedoc,sebastian-lenz/typedoc,SierraSoftworks/typedoc,dominic31/typedoc,sebastian-lenz/typedoc,TypeStrong/typedoc,sebastian-lenz/typedoc,igor-bezkrovny/typedoc,igor-bezkrovny/typedoc,adamhickey/typedoc,dominic31/typedoc,innerverse/typedoc,PolymerLabs/typedoc,sebilasse/typedoc,igor-bezkrovny/typedoc,PolymerLabs/typedoc,innerverse/typedoc,innerverse/typedoc,SierraSoftworks/typedoc,darkartur/typedoc,PolymerLabs/typedoc,SierraSoftworks/typedoc,darkartur/typedoc,TypeStrong/typedoc | ---
+++
@@ -63,4 +63,16 @@
* protectedMethod short text.
*/
protected protectedMethod() {}
+
+ /**
+ * Constructor short text.
+ *
+ * @param p1 Constructor param
+ * @param p2 Private string property
+ * @param p3 Public number property
+ * @param p4 Public implicit any property
+ */
+ constructor(p1, private p2: string, public p3: number, public p4) {
+ super();
+ }
} |
c5fa12d8cd7bf2266e21221d99a0d870e4edfd74 | src/React.Sample.Mvc4/types/index.d.ts | src/React.Sample.Mvc4/types/index.d.ts | import {
Component as _Component,
useState as _useState,
Dispatch,
SetStateAction,
} from 'react';
// Globally available modules must be declared here
// Copy type definitions from @types/react/index.d.ts, because namespaces can't be re-exported
declare global {
namespace React {
function useState<S>(
initialState: S | (() => S),
): [S, Dispatch<SetStateAction<S>>];
function useState<S = undefined>(): [
S | undefined,
Dispatch<SetStateAction<S | undefined>>
];
interface Component<P = {}, S = {}, SS = any>
extends ComponentLifecycle<P, S, SS> {}
}
const Reactstrap: any;
const PropTypes: any;
}
export const test = 1;
| import _React from 'react';
import _Reactstrap from 'reactstrap';
import _PropTypes from 'prop-types';
declare global {
const React: typeof _React;
const Reactstrap: typeof _Reactstrap;
const PropTypes: typeof _PropTypes;
}
| Improve type resolution for UMD libraries | Improve type resolution for UMD libraries
😎 found a way to make it "just work" with existing types
| TypeScript | mit | reactjs/React.NET,reactjs/React.NET,reactjs/React.NET,reactjs/React.NET,reactjs/React.NET,reactjs/React.NET | ---
+++
@@ -1,27 +1,9 @@
-import {
- Component as _Component,
- useState as _useState,
- Dispatch,
- SetStateAction,
-} from 'react';
-
-// Globally available modules must be declared here
-// Copy type definitions from @types/react/index.d.ts, because namespaces can't be re-exported
+import _React from 'react';
+import _Reactstrap from 'reactstrap';
+import _PropTypes from 'prop-types';
declare global {
- namespace React {
- function useState<S>(
- initialState: S | (() => S),
- ): [S, Dispatch<SetStateAction<S>>];
- function useState<S = undefined>(): [
- S | undefined,
- Dispatch<SetStateAction<S | undefined>>
- ];
- interface Component<P = {}, S = {}, SS = any>
- extends ComponentLifecycle<P, S, SS> {}
- }
- const Reactstrap: any;
- const PropTypes: any;
+ const React: typeof _React;
+ const Reactstrap: typeof _Reactstrap;
+ const PropTypes: typeof _PropTypes;
}
-
-export const test = 1; |
49f2aef8d806cb64e8f7967250217e544b93ac18 | src/permissions.directive.spec.ts | src/permissions.directive.spec.ts | import { PermissionsDirective } from './permissions.directive';
describe('PermissionsDirective', () => {
it('should create an instance', () => {
// const directive = new PermissionsDirective();
expect(true).toBeTruthy();
});
});
| import { PermissionsDirective } from './permissions.directive';
import { Component } from '@angular/core';
import { NgxPermissionsModule } from './index';
import { TestBed } from '@angular/core/testing';
import { PermissionsService } from './permissions.service';
enum PermissionsTestEnum {
ADMIN = <any> 'ADMIN',
GUEST = <any> 'GUEST'
}
describe('PermissionsDirective', () => {
it('should create an instance', () => {
// const directive = new PermissionsDirective();
expect(true).toBeTruthy();
});
});
describe('Permission directive angular except', () => {
@Component({selector: 'test-comp',
template: `<ng-template permissions [permissionsExcept]="'ADMIN'"><div>123</div></ng-template>`})
class TestComp {
data: any;
}
let permissionService;
let permissions;
let fixture;
let comp;
beforeEach(() => {
TestBed.configureTestingModule({declarations: [TestComp], imports: [NgxPermissionsModule.forRoot()]});
fixture = TestBed.createComponent(TestComp);
comp = fixture.componentInstance;
permissionService = fixture.debugElement.injector.get(PermissionsService);
});
it('Should not show component', () => {
permissionService.loadPermissions([PermissionsTestEnum.ADMIN, PermissionsTestEnum.GUEST]);
fixture.detectChanges();
let content = fixture.debugElement.nativeElement.querySelector('div');
expect(content).toEqual(null);
})
it ('Should show the component', () => {
permissionService.loadPermissions([PermissionsTestEnum.GUEST]);
fixture.detectChanges();
let content = fixture.debugElement.nativeElement.querySelector('div');
expect(content).toBeTruthy();
expect(content.innerHTML).toEqual('123');
})
});
describe('Permission directive angular only', () => {
@Component({selector: 'test-comp',
template: `<ng-template permissions [permissionsOnly]="'ADMIN'"><div>123</div></ng-template>`})
class TestComp {
data: any;
}
let permissionService;
let permissions;
let fixture;
let comp;
beforeEach(() => {
TestBed.configureTestingModule({declarations: [TestComp], imports: [NgxPermissionsModule.forRoot()]});
fixture = TestBed.createComponent(TestComp);
comp = fixture.componentInstance;
permissionService = fixture.debugElement.injector.get(PermissionsService);
});
it('Should show the component', () => {
permissionService.loadPermissions([PermissionsTestEnum.ADMIN, PermissionsTestEnum.GUEST]);
fixture.detectChanges();
let content = fixture.debugElement.nativeElement.querySelector('div');
expect(content).toBeTruthy();
expect(content.innerHTML).toEqual('123');
});
it ('Should not show the component', () => {
permissionService.loadPermissions([PermissionsTestEnum.GUEST]);
fixture.detectChanges();
let content = fixture.debugElement.nativeElement.querySelector('div');
expect(content).toEqual(null);
})
}); | Add tests for permissions directive | Add tests for permissions directive
| TypeScript | mit | AlexKhymenko/ngx-permissions,AlexKhymenko/ngx-permissions,AlexKhymenko/ngx-permissions | ---
+++
@@ -1,4 +1,13 @@
import { PermissionsDirective } from './permissions.directive';
+import { Component } from '@angular/core';
+import { NgxPermissionsModule } from './index';
+import { TestBed } from '@angular/core/testing';
+import { PermissionsService } from './permissions.service';
+
+enum PermissionsTestEnum {
+ ADMIN = <any> 'ADMIN',
+ GUEST = <any> 'GUEST'
+}
describe('PermissionsDirective', () => {
it('should create an instance', () => {
@@ -6,3 +15,81 @@
expect(true).toBeTruthy();
});
});
+
+describe('Permission directive angular except', () => {
+ @Component({selector: 'test-comp',
+ template: `<ng-template permissions [permissionsExcept]="'ADMIN'"><div>123</div></ng-template>`})
+ class TestComp {
+ data: any;
+ }
+
+ let permissionService;
+ let permissions;
+ let fixture;
+ let comp;
+ beforeEach(() => {
+ TestBed.configureTestingModule({declarations: [TestComp], imports: [NgxPermissionsModule.forRoot()]});
+
+ fixture = TestBed.createComponent(TestComp);
+ comp = fixture.componentInstance;
+
+ permissionService = fixture.debugElement.injector.get(PermissionsService);
+
+ });
+
+
+ it('Should not show component', () => {
+ permissionService.loadPermissions([PermissionsTestEnum.ADMIN, PermissionsTestEnum.GUEST]);
+
+ fixture.detectChanges();
+ let content = fixture.debugElement.nativeElement.querySelector('div');
+ expect(content).toEqual(null);
+ })
+ it ('Should show the component', () => {
+ permissionService.loadPermissions([PermissionsTestEnum.GUEST]);
+
+ fixture.detectChanges();
+ let content = fixture.debugElement.nativeElement.querySelector('div');
+ expect(content).toBeTruthy();
+ expect(content.innerHTML).toEqual('123');
+ })
+});
+
+describe('Permission directive angular only', () => {
+ @Component({selector: 'test-comp',
+ template: `<ng-template permissions [permissionsOnly]="'ADMIN'"><div>123</div></ng-template>`})
+ class TestComp {
+ data: any;
+ }
+
+ let permissionService;
+ let permissions;
+ let fixture;
+ let comp;
+ beforeEach(() => {
+ TestBed.configureTestingModule({declarations: [TestComp], imports: [NgxPermissionsModule.forRoot()]});
+
+ fixture = TestBed.createComponent(TestComp);
+ comp = fixture.componentInstance;
+
+ permissionService = fixture.debugElement.injector.get(PermissionsService);
+
+ });
+
+
+ it('Should show the component', () => {
+ permissionService.loadPermissions([PermissionsTestEnum.ADMIN, PermissionsTestEnum.GUEST]);
+
+ fixture.detectChanges();
+ let content = fixture.debugElement.nativeElement.querySelector('div');
+ expect(content).toBeTruthy();
+ expect(content.innerHTML).toEqual('123');
+ });
+ it ('Should not show the component', () => {
+ permissionService.loadPermissions([PermissionsTestEnum.GUEST]);
+
+ fixture.detectChanges();
+ let content = fixture.debugElement.nativeElement.querySelector('div');
+ expect(content).toEqual(null);
+ })
+}); |
2ec192a10a46e724556138854993de45aa659a9d | packages/bms/src/notes/note.ts | packages/bms/src/notes/note.ts | import DataStructure from 'data-structure'
/** A single note in a notechart. */
export interface BMSNote {
beat: number
endBeat?: number
column?: string
keysound: string
}
export const Note = DataStructure<BMSNote>({
beat: 'number',
endBeat: DataStructure.maybe<number>('number'),
column: DataStructure.maybe<string>('string'),
keysound: 'string',
})
| import DataStructure from 'data-structure'
/** A single note in a notechart. */
export interface BMSNote {
beat: number
endBeat?: number
column?: string
keysound: string
/**
* [bmson] The number of seconds into the sound file to start playing
*/
keysoundStart?: number
/**
* [bmson] The {Number} of seconds into the sound file to stop playing.
* This may be `undefined` to indicate that the sound file should play until the end.
*/
keysoundEnd?: number
}
export const Note = DataStructure<BMSNote>({
beat: 'number',
endBeat: DataStructure.maybe<number>('number'),
column: DataStructure.maybe<string>('string'),
keysound: 'string',
})
| Add some extra bmson fields (for convenience) | :sparkles: Add some extra bmson fields (for convenience)
| TypeScript | agpl-3.0 | bemusic/bemuse,bemusic/bemuse,bemusic/bemuse,bemusic/bemuse,bemusic/bemuse | ---
+++
@@ -6,6 +6,17 @@
endBeat?: number
column?: string
keysound: string
+
+ /**
+ * [bmson] The number of seconds into the sound file to start playing
+ */
+ keysoundStart?: number
+
+ /**
+ * [bmson] The {Number} of seconds into the sound file to stop playing.
+ * This may be `undefined` to indicate that the sound file should play until the end.
+ */
+ keysoundEnd?: number
}
export const Note = DataStructure<BMSNote>({ |
aad51530abe79ea70ccc12b97de85bc197a98491 | ng2-timetable/app/schedule/events-list.component.ts | ng2-timetable/app/schedule/events-list.component.ts | import {View, Component, OnInit, provide} from 'angular2/core';
import {ROUTER_DIRECTIVES} from 'angular2/router';
import {MATERIAL_DIRECTIVES} from 'ng2-material/all';
import {EventsService} from './events.service';
import {Event} from './event';
@Component({
selector: 'events-list',
templateUrl: '/static/templates/events-list.html',
directives: [ROUTER_DIRECTIVES],
providers: [
EventsService,
MATERIAL_DIRECTIVES
]
})
export class EventsListComponent implements OnInit {
constructor(private _eventsService: EventsService) {}
errorMessage: string;
events: Event[];
ngOnInit() {
// TODO: connect to the service
this.getEvents();
}
getEvents() {
this._eventsService.getEvents()
.then(
events => this.events = events,
error => this.errorMessage = <any>error);
}
}
| import {View, Component, OnInit} from 'angular2/core';
import {ROUTER_DIRECTIVES} from 'angular2/router';
import {MATERIAL_DIRECTIVES, MATERIAL_PROVIDERS} from 'ng2-material/all';
import {EventsService} from './events.service';
import {Event} from './event';
@Component({
selector: 'events-list',
templateUrl: '/static/templates/events-list.html',
directives: [ROUTER_DIRECTIVES, MATERIAL_DIRECTIVES],
providers: [
EventsService,
MATERIAL_PROVIDERS
]
})
export class EventsListComponent implements OnInit {
constructor(private _eventsService: EventsService) {}
errorMessage: string;
events: Event[];
ngOnInit() {
this.getEvents();
}
getEvents() {
this._eventsService.getEvents()
.then(
events => this.events = events,
error => this.errorMessage = <any>error);
}
}
| Fix directives & providers of EventsListComponent | Fix directives & providers of EventsListComponent
| TypeScript | mit | bluebirrrrd/nau-timetable,bluebirrrrd/nau-timetable,bluebirrd/nau-timetable,bluebirrd/nau-timetable,bluebirrrrd/nau-timetable,bluebirrrrd/nau-timetable,bluebirrd/nau-timetable,bluebirrd/nau-timetable | ---
+++
@@ -1,7 +1,7 @@
-import {View, Component, OnInit, provide} from 'angular2/core';
+import {View, Component, OnInit} from 'angular2/core';
import {ROUTER_DIRECTIVES} from 'angular2/router';
-import {MATERIAL_DIRECTIVES} from 'ng2-material/all';
+import {MATERIAL_DIRECTIVES, MATERIAL_PROVIDERS} from 'ng2-material/all';
import {EventsService} from './events.service';
import {Event} from './event';
@@ -10,10 +10,10 @@
@Component({
selector: 'events-list',
templateUrl: '/static/templates/events-list.html',
- directives: [ROUTER_DIRECTIVES],
+ directives: [ROUTER_DIRECTIVES, MATERIAL_DIRECTIVES],
providers: [
EventsService,
- MATERIAL_DIRECTIVES
+ MATERIAL_PROVIDERS
]
})
@@ -24,14 +24,13 @@
events: Event[];
ngOnInit() {
- // TODO: connect to the service
this.getEvents();
}
getEvents() {
- this._eventsService.getEvents()
- .then(
- events => this.events = events,
- error => this.errorMessage = <any>error);
+ this._eventsService.getEvents()
+ .then(
+ events => this.events = events,
+ error => this.errorMessage = <any>error);
}
} |
7ad73e649d4bdfd92717cc139cf11ac678c3ff17 | types/components/CollapsibleItem.d.ts | types/components/CollapsibleItem.d.ts | import * as React from "react";
import { SharedBasic } from "./utils";
export interface CollapsibleItemProps extends SharedBasic {
expanded?: boolean;
node?: React.ReactNode;
header: any;
icon?: React.ReactNode;
iconClassName?: string;
onSelect: (eventKey: any) => any;
eventKey?: any;
}
/**
* React Materialize: CollapsibleItem
*/
declare const CollapsibleItem: React.FC<CollapsibleItemProps>;
export default CollapsibleItem;
| import * as React from "react";
import { SharedBasic } from "./utils";
export interface CollapsibleItemProps extends SharedBasic {
expanded?: boolean;
node?: React.ReactNode;
header: any;
icon?: React.ReactNode;
iconClassName?: string;
onSelect?: (eventKey: any) => any;
eventKey?: any;
}
/**
* React Materialize: CollapsibleItem
*/
declare const CollapsibleItem: React.FC<CollapsibleItemProps>;
export default CollapsibleItem;
| Make onSelect on CollapsibleItem optional | Make onSelect on CollapsibleItem optional
This change partially reverts the changes made in 4308d86fbc99e28eaff7d676c44a18d1c823be6d | TypeScript | mit | react-materialize/react-materialize,react-materialize/react-materialize,react-materialize/react-materialize | ---
+++
@@ -7,7 +7,7 @@
header: any;
icon?: React.ReactNode;
iconClassName?: string;
- onSelect: (eventKey: any) => any;
+ onSelect?: (eventKey: any) => any;
eventKey?: any;
}
|
88173702b109460959c708143bec0a3d5437fca8 | src/dialog.component.ts | src/dialog.component.ts | import {
Component, OnDestroy
} from '@angular/core';
import {Observable, Observer} from 'rxjs';
import {DialogWrapperComponent} from "./dialog-wrapper.component";
import {DialogService} from "./dialog.service";
@Component({
selector: 'pagination'
})
export abstract class DialogComponent implements OnDestroy {
/**
* Observer to return result from dialog
*/
private observer: Observer<any>;
/**
* Dialog result
* @type {any}
*/
protected result: any;
/**
* Dialog wrapper (modal placeholder)
*/
wrapper: DialogWrapperComponent;
/**
* Constructor
* @param {DialogService} dialogService - instance of DialogService
*/
constructor(protected dialogService: DialogService) {}
/**
*
* @param {any} data
* @return {Observable<any>}
*/
fillData(data:any = {}): Observable<any> {
let keys = Object.keys(data);
for(let i=0, length=keys.length; i<length; i++) {
let key = keys[i];
this[key] = data[key];
}
return Observable.create((observer)=>{
this.observer = observer;
return ()=>{
this.close();
}
});
}
/**
* Closes dialog
*/
close():void {
this.dialogService.removeDialog(this);
}
/**
* OnDestroy handler
*/
ngOnDestroy(): void {
this.observer.next(this.result);
}
}
| import {
Component, OnDestroy
} from '@angular/core';
import {Observable, Observer} from 'rxjs';
import {DialogWrapperComponent} from "./dialog-wrapper.component";
import {DialogService} from "./dialog.service";
@Component({
selector: 'pagination'
})
export abstract class DialogComponent implements OnDestroy {
/**
* Observer to return result from dialog
*/
private observer: Observer<any>;
/**
* Dialog result
* @type {any}
*/
protected result: any;
/**
* Dialog wrapper (modal placeholder)
*/
wrapper: DialogWrapperComponent;
/**
* Constructor
* @param {DialogService} dialogService - instance of DialogService
*/
constructor(protected dialogService: DialogService) {}
/**
*
* @param {any} data
* @return {Observable<any>}
*/
fillData(data:any = {}): Observable<any> {
let keys = Object.keys(data);
for(let i=0, length=keys.length; i<length; i++) {
let key = keys[i];
this[key] = data[key];
}
return Observable.create((observer)=>{
this.observer = observer;
return ()=>{
this.close();
}
});
}
/**
* Closes dialog
*/
close():void {
this.dialogService.removeDialog(this);
}
/**
* OnDestroy handler
*/
ngOnDestroy(): void {
if(this.observer) {
this.observer.next(this.result);
}
}
}
| Fix crash if no subscription on dialog result | Fix crash if no subscription on dialog result
| TypeScript | mit | ankosoftware/ng2-bootstrap-modal,ankosoftware/ng2-bootstrap-modal,ankosoftware/ng2-bootstrap-modal | ---
+++
@@ -61,6 +61,8 @@
* OnDestroy handler
*/
ngOnDestroy(): void {
- this.observer.next(this.result);
+ if(this.observer) {
+ this.observer.next(this.result);
+ }
}
} |
724acad12c5593242dbb1d5d58b6c8c49ea4e62a | lib/components/map/gridualizer.tsx | lib/components/map/gridualizer.tsx | import {Coords, DoneCallback, GridLayer as LeafletGridLayer} from 'leaflet'
import {GridLayer, GridLayerProps, withLeaflet} from 'react-leaflet'
type DrawTileFn = (
canvas: HTMLCanvasElement,
coords: Coords,
z: number
) => HTMLElement
class MutableGridLayer extends LeafletGridLayer {
drawTile: DrawTileFn
constructor(options) {
super(options)
this.drawTile = options.drawTile
}
createTile(coords: Coords, _: DoneCallback) {
const canvas = document.createElement('canvas')
canvas.width = canvas.height = 256
this.drawTile(canvas, coords, coords.z)
return canvas
}
}
interface GridualizerLayerProps extends GridLayerProps {
drawTile: DrawTileFn
}
class GridualizerLayer extends GridLayer<
GridualizerLayerProps,
MutableGridLayer
> {
createLeafletElement(props: GridualizerLayerProps) {
return new MutableGridLayer({drawTile: props.drawTile})
}
}
export default withLeaflet(GridualizerLayer)
| import {Coords, DoneCallback, GridLayer as LeafletGridLayer} from 'leaflet'
import {GridLayer, GridLayerProps, withLeaflet} from 'react-leaflet'
export type DrawTileFn = (
canvas: HTMLCanvasElement,
coords: Coords,
z: number
) => void
class MutableGridLayer extends LeafletGridLayer {
drawTile: DrawTileFn
constructor(options) {
super(options)
this.drawTile = options.drawTile
}
createTile(coords: Coords, _: DoneCallback) {
const canvas = document.createElement('canvas')
canvas.width = canvas.height = 256
this.drawTile(canvas, coords, coords.z)
return canvas
}
}
interface GridualizerLayerProps extends GridLayerProps {
drawTile: DrawTileFn
}
class GridualizerLayer extends GridLayer<
GridualizerLayerProps,
MutableGridLayer
> {
createLeafletElement(props: GridualizerLayerProps) {
return new MutableGridLayer({drawTile: props.drawTile})
}
}
export default withLeaflet(GridualizerLayer)
| Correct return type of DrawTileFn | Correct return type of DrawTileFn
| TypeScript | mit | conveyal/analysis-ui,conveyal/analysis-ui,conveyal/analysis-ui | ---
+++
@@ -1,11 +1,11 @@
import {Coords, DoneCallback, GridLayer as LeafletGridLayer} from 'leaflet'
import {GridLayer, GridLayerProps, withLeaflet} from 'react-leaflet'
-type DrawTileFn = (
+export type DrawTileFn = (
canvas: HTMLCanvasElement,
coords: Coords,
z: number
-) => HTMLElement
+) => void
class MutableGridLayer extends LeafletGridLayer {
drawTile: DrawTileFn |
114a3a5e7fbb435ced5cb33ffcf21005ec0b68d0 | src/app/shared/services/auth.service.ts | src/app/shared/services/auth.service.ts | import {Injectable} from '@angular/core';
import {CanActivate, Router} from '@angular/router';
import {JwtHelperService} from '@auth0/angular-jwt';
import {ProfileService} from '@shared/services/profile.service';
@Injectable()
export class AuthService implements CanActivate {
helper = new JwtHelperService();
constructor(private router: Router, private profileService: ProfileService) {
}
async loggedIn() {
const token = localStorage.getItem('id_token');
if (token != null) {
const expired = this.helper.decodeToken(token).expires;
const isNotExpired = new Date().getMilliseconds() < expired;
let profile = this.profileService.getProfileFromLocal();
if (isNotExpired) {
if (profile == null || (profile != null && profile.userId == null)) {
profile = await this.profileService.getProfile().toPromise();
this.profileService.setProfile(profile);
}
}
return isNotExpired;
}
return false;
}
async canActivate() {
if (await this.loggedIn()) {
return true;
} else {
this.router.navigate(['unauthorized']);
return false;
}
}
}
| import {Injectable} from '@angular/core';
import {CanActivate, Router} from '@angular/router';
import {JwtHelperService} from '@auth0/angular-jwt';
import {ProfileService} from '@shared/services/profile.service';
@Injectable()
export class AuthService implements CanActivate {
helper = new JwtHelperService();
constructor(private router: Router, private profileService: ProfileService) {
}
async loggedIn() {
const token = localStorage.getItem('id_token');
if (token != null) {
const expired = this.helper.decodeToken(token).expires;
const isNotExpired = new Date().getMilliseconds() < expired;
let profile = this.profileService.getProfileFromLocal();
if (isNotExpired) {
if (profile == null || (profile != null && profile.userId == null)) {
profile = await this.profileService.getProfile().toPromise();
if (profile.userId == null) {
// Token expired on the server (i.e restarted server)
localStorage.removeItem('id_token');
this.profileService.removeProfile();
return false;
}
this.profileService.setProfile(profile);
}
}
return isNotExpired;
}
return false;
}
async canActivate() {
if (await this.loggedIn()) {
return true;
} else {
this.router.navigate(['unauthorized']);
return false;
}
}
}
| Fix token expired before timeout | Fix token expired before timeout
| TypeScript | unknown | OmicsDI/ddi-web-app,BD2K-DDI/ddi-web-app,OmicsDI/ddi-web-app,BD2K-DDI/ddi-web-app,OmicsDI/ddi-web-app | ---
+++
@@ -20,6 +20,12 @@
if (isNotExpired) {
if (profile == null || (profile != null && profile.userId == null)) {
profile = await this.profileService.getProfile().toPromise();
+ if (profile.userId == null) {
+ // Token expired on the server (i.e restarted server)
+ localStorage.removeItem('id_token');
+ this.profileService.removeProfile();
+ return false;
+ }
this.profileService.setProfile(profile);
}
} |
300f7b70bb3aa74f635f489ef0027e35b1275e2d | src/definitions/Handler.ts | src/definitions/Handler.ts | import * as Big from "bignumber.js";
import * as Frames from "../definitions/FrameDirectory";
import {ItemTypes} from "./Inventory";
import {Attributes, RequestContext} from "./SkillContext";
export class Frame {
constructor(id: string, entry: ReturnsResponseContext, unhandled: ReturnsFrame, FrameMap: ActionMap) {
this.id = id;
this.entry = entry;
this.actions = FrameMap;
this.unhandled = unhandled;
Frames[id] = this;
}
id: string;
entry: ReturnsResponseContext;
unhandled: ReturnsFrame;
actions: ActionMap;
}
export class ResponseContext {
constructor(model: ResponseModel) {
this.model = model;
}
model: ResponseModel;
}
export class ResponseModel {
constructor() {
this.cookieCount = new Big(0);
this.upgrades = [];
}
speech: string;
reprompt?: string;
cookieCount: Big.BigNumber;
upgrades: Array<ItemTypes>;
}
export interface ReturnsResponseContext {
(Attributes: Attributes, Context?: RequestContext): ResponseContext | Promise<ResponseContext>;
}
export interface ActionMap {
[key: string]: ReturnsFrame | undefined;
}
export interface ReturnsFrame {
(Attributes: Attributes, Context?: RequestContext): Frame | Promise<Frame>;
} | import * as Big from "bignumber.js";
import * as Frames from "../definitions/FrameDirectory";
import {ItemTypes} from "./Inventory";
import {Attributes, RequestContext} from "./SkillContext";
export class Frame {
constructor(id: string, entry: ReturnsResponseContext, unhandled: ReturnsFrame, FrameMap: ActionMap) {
this.id = id;
this.entry = entry;
this.actions = FrameMap;
this.unhandled = unhandled;
Frames[id] = this;
}
id: string;
entry: ReturnsResponseContext;
unhandled: ReturnsFrame;
actions: ActionMap;
}
export class ResponseContext {
constructor(model: ResponseModel) {
this.model = model;
}
model: ResponseModel;
}
export class ResponseModel {
constructor() {
this.cookieCount = new Big(0);
this.upgrades = [];
}
speech: string;
reprompt?: string;
cardText: string;
cardTitle: string;
cardSubtitle: string;
cookieCount: Big.BigNumber;
upgrades: Array<ItemTypes>;
}
export interface ReturnsResponseContext {
(Attributes: Attributes, Context?: RequestContext): ResponseContext | Promise<ResponseContext>;
}
export interface ActionMap {
[key: string]: ReturnsFrame | undefined;
}
export interface ReturnsFrame {
(Attributes: Attributes, Context?: RequestContext): Frame | Promise<Frame>;
} | Add card attributes to model. | Add card attributes to model.
| TypeScript | agpl-3.0 | deegles/cookietime,deegles/cookietime | ---
+++
@@ -38,6 +38,9 @@
speech: string;
reprompt?: string;
+ cardText: string;
+ cardTitle: string;
+ cardSubtitle: string;
cookieCount: Big.BigNumber;
upgrades: Array<ItemTypes>;
} |
bf9ce5a438d1cf4bb9a54f067dc3e9900cf9a532 | app/overview/overview-home.component.ts | app/overview/overview-home.component.ts | import {Component, OnInit, Inject, ViewChild, TemplateRef} from '@angular/core';
import {Router} from '@angular/router';
import {IdaiFieldDocument} from '../model/idai-field-document';
import {ObjectList} from "./object-list";
import {Messages} from "idai-components-2/idai-components-2";
import {M} from "../m";
import {DocumentEditChangeMonitor} from "idai-components-2/idai-components-2";
import {Validator} from "../model/validator";
import {NgbModal, NgbModalRef} from '@ng-bootstrap/ng-bootstrap';
import {PersistenceService} from "./persistence-service";
@Component({
moduleId: module.id,
template: `<h1>Overview home</h1>`
})
/**
*/
export class OverviewHomeComponent implements OnInit {}
| import {Component} from "@angular/core";
@Component({
moduleId: module.id,
template: ``
})
/**
*/
export class OverviewHomeComponent {}
| Make overview home showing just blank space. | Make overview home showing just blank space.
| TypeScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -1,19 +1,10 @@
-import {Component, OnInit, Inject, ViewChild, TemplateRef} from '@angular/core';
-import {Router} from '@angular/router';
-import {IdaiFieldDocument} from '../model/idai-field-document';
-import {ObjectList} from "./object-list";
-import {Messages} from "idai-components-2/idai-components-2";
-import {M} from "../m";
-import {DocumentEditChangeMonitor} from "idai-components-2/idai-components-2";
-import {Validator} from "../model/validator";
-import {NgbModal, NgbModalRef} from '@ng-bootstrap/ng-bootstrap';
-import {PersistenceService} from "./persistence-service";
+import {Component} from "@angular/core";
@Component({
moduleId: module.id,
- template: `<h1>Overview home</h1>`
+ template: ``
})
/**
*/
-export class OverviewHomeComponent implements OnInit {}
+export class OverviewHomeComponent {} |
834432d4361bde9ac7b1fee6f3e3e366209ddb56 | src/sources/esri/tiledMapLayer.ts | src/sources/esri/tiledMapLayer.ts | import * as esri from 'esri-leaflet';
import { ILayer } from '../../types';
import { ESRISource } from './source';
export class ESRITiledMapLayer implements ILayer {
previewSet = 0;
previewCol = 0;
previewRow = 0;
private _leaflet: L.Layer;
constructor(readonly url: string, readonly capabilities: any) {
}
get title() {
return this.capabilities.documentInfo.Title;
}
get name() {
return this.capabilities.documentInfo.Title;
}
get abstract() {
return this.capabilities.description;
}
get bounds(): undefined {
return undefined;
}
get preview() {
return `<img src="${this.url}tile/${this.previewSet}/${this.previewCol}/${this.previewSet}">`;
}
get leaflet() {
if (this._leaflet) {
return this._leaflet;
} else {
this._leaflet = esri.tiledMapLayer({
url: this.url,
});
return this._leaflet;
}
}
get legend() {
return ``;
}
}
| import * as esri from 'esri-leaflet';
import { ILayer } from '../../types';
import { ESRISource } from './source';
import pool from '../../servicePool';
import { MapService } from '../../services/map';
const map = pool.getService<MapService>('MapService');
export class ESRITiledMapLayer implements ILayer {
previewSet = 0;
previewCol = 0;
previewRow = 0;
hasOperations = true;
private _leaflet: any;
constructor(readonly url: string, readonly capabilities: any) {
}
get title() {
return this.capabilities.documentInfo.Title;
}
get name() {
return this.capabilities.documentInfo.Title;
}
get abstract() {
return this.capabilities.description;
}
get bounds(): undefined {
return undefined;
}
get preview() {
return `<img src="${this.url}tile/${this.previewSet}/${this.previewCol}/${this.previewSet}">`;
}
get leaflet() {
if (this._leaflet) {
return this._leaflet;
} else {
this._leaflet = esri.tiledMapLayer({
url: this.url,
});
return this._leaflet;
}
}
get legend() {
return ``;
}
async intersectsPoint?(point: L.Point) {
const features = await new Promise((resolve, reject) => {
this._leaflet.identify().on(map.map).at([point.x, point.y]).layers('top').run((error: boolean, features: any) => {
resolve(features);
});
});
return features;
}
}
| Add first inspection function to esri layer | Add first inspection function to esri layer
| TypeScript | apache-2.0 | geoloep/krite,geoloep/krite,geoloep/krite | ---
+++
@@ -2,13 +2,20 @@
import { ILayer } from '../../types';
import { ESRISource } from './source';
+
+import pool from '../../servicePool';
+import { MapService } from '../../services/map';
+
+const map = pool.getService<MapService>('MapService');
export class ESRITiledMapLayer implements ILayer {
previewSet = 0;
previewCol = 0;
previewRow = 0;
- private _leaflet: L.Layer;
+ hasOperations = true;
+
+ private _leaflet: any;
constructor(readonly url: string, readonly capabilities: any) {
}
@@ -47,4 +54,14 @@
get legend() {
return ``;
}
+
+ async intersectsPoint?(point: L.Point) {
+ const features = await new Promise((resolve, reject) => {
+ this._leaflet.identify().on(map.map).at([point.x, point.y]).layers('top').run((error: boolean, features: any) => {
+ resolve(features);
+ });
+ });
+
+ return features;
+ }
} |
0a24b4a5bd5d89bb61ba211c7709bd5b8f65abe7 | tool/gulpfile-dev.ts | tool/gulpfile-dev.ts | import * as browserSync from 'browser-sync';
import * as del from 'del';
import * as gulp from 'gulp';
import * as runSequence from 'run-sequence';
import {DIR_TMP, DIR_DST, DIR_SRC, typescriptTask} from './common.ts';
gulp.task('clean', del.bind(null, [DIR_TMP, DIR_DST]));
gulp.task('ts', () => typescriptTask());
gulp.task('ts-watch', ['ts'], browserSync.reload);
gulp.task('serve', () => {
browserSync.init({
notify: false,
server: {
baseDir: [DIR_TMP, DIR_SRC],
routes: {
'/bower_components': 'bower_components',
'/node_modules': 'node_modules'
}
}
});
gulp.watch(`${DIR_SRC}/**/*.ts`, ['ts-watch']);
gulp.watch(`${DIR_SRC}/**/*.{css,html}`, []).on('change', browserSync.reload);
});
gulp.task('default', done => runSequence('clean', 'ts', 'serve', done));
| import * as browserSync from 'browser-sync';
import * as del from 'del';
import * as gulp from 'gulp';
import * as runSequence from 'run-sequence';
import {DIR_TMP, DIR_DST, DIR_SRC, typescriptTask} from './common.ts';
gulp.task('clean', del.bind(null, [DIR_TMP, DIR_DST]));
gulp.task('ts', () => typescriptTask());
gulp.task('ts-watch', ['ts'], browserSync.reload);
gulp.task('serve', () => {
browserSync.init({
notify: false,
server: {
baseDir: [DIR_TMP, DIR_SRC],
routes: {
'/bower_components': 'bower_components',
'/node_modules': 'node_modules'
}
}
});
gulp.watch(`${DIR_SRC}/**/*.ts`, ['ts-watch']);
gulp.watch(`${DIR_SRC}/**/*.{css,html}`, null).on('change', browserSync.reload);
});
gulp.task('default', done => runSequence('clean', 'ts', 'serve', done));
| Fix issue with starting multiple instances of browser-sync when HTML or CSS is changed | Fix issue with starting multiple instances of browser-sync when HTML or CSS is changed
| TypeScript | mit | Farata/polymer-typescript-starter,Farata/polymer-typescript-starter | ---
+++
@@ -22,7 +22,7 @@
}
});
gulp.watch(`${DIR_SRC}/**/*.ts`, ['ts-watch']);
- gulp.watch(`${DIR_SRC}/**/*.{css,html}`, []).on('change', browserSync.reload);
+ gulp.watch(`${DIR_SRC}/**/*.{css,html}`, null).on('change', browserSync.reload);
});
gulp.task('default', done => runSequence('clean', 'ts', 'serve', done)); |
bb128ddbd901b09aeaeaab840bae7ff596265680 | front/components/reducers/index.ts | front/components/reducers/index.ts | import {ActionType} from '../actions/types';
export default function store(state: ApplicationState = { containers: [], hosts: [] }, action: ActionType): ApplicationState {
switch (action.kind) {
case 'ADD_CONTAINER':
return Object.assign(
{},
state,
{ containers: [...state.containers, action.container] }
)
case 'ADD_HOST':
return Object.assign(
{},
state,
{ hosts: [...state.hosts, action.host] }
)
case 'REMOVE_CONTAINER':
return Object.assign(
{},
state,
{ containers: state.containers.filter(c => c.id !== action.id) }
)
case 'REMOVE_CONTAINER':
return Object.assign(
{},
state,
{ hosts: state.hosts.filter(c => c.id !== action.id) }
)
}
}
interface ApplicationState {
containers: Array<Concierge.APIContainer>;
hosts: Array<Concierge.APIHost>;
}
| import * as Actions from '../actions/types';
import ActionType = Actions.ActionType;
export default function store(state: ApplicationState = { containers: [], hosts: [] }, action: ActionType): ApplicationState {
switch (action.kind) {
case Actions.ADD_CONTAINER:
return Object.assign(
{},
state,
{ containers: [...state.containers, action.container] }
)
case Actions.ADD_HOST:
return Object.assign(
{},
state,
{ hosts: [...state.hosts, action.host] }
)
case Actions.REMOVE_HOST:
return Object.assign(
{},
state,
{ containers: state.containers.filter(c => c.id !== action.id) }
)
case Actions.REMOVE_CONTAINER:
return Object.assign(
{},
state,
{ hosts: state.hosts.filter(c => c.id !== action.id) }
)
}
}
interface ApplicationState {
containers: Array<Concierge.APIContainer>;
hosts: Array<Concierge.APIHost>;
}
| Use action kind references in reducers | Use action kind references in reducers
| TypeScript | mit | paypac/node-concierge,the-concierge/concierge,the-concierge/concierge,paypac/node-concierge,paypac/node-concierge,paypac/node-concierge,the-concierge/concierge | ---
+++
@@ -1,26 +1,27 @@
-import {ActionType} from '../actions/types';
+import * as Actions from '../actions/types';
+import ActionType = Actions.ActionType;
export default function store(state: ApplicationState = { containers: [], hosts: [] }, action: ActionType): ApplicationState {
switch (action.kind) {
- case 'ADD_CONTAINER':
+ case Actions.ADD_CONTAINER:
return Object.assign(
{},
state,
{ containers: [...state.containers, action.container] }
)
- case 'ADD_HOST':
+ case Actions.ADD_HOST:
return Object.assign(
{},
state,
{ hosts: [...state.hosts, action.host] }
)
- case 'REMOVE_CONTAINER':
+ case Actions.REMOVE_HOST:
return Object.assign(
{},
state,
{ containers: state.containers.filter(c => c.id !== action.id) }
)
- case 'REMOVE_CONTAINER':
+ case Actions.REMOVE_CONTAINER:
return Object.assign(
{},
state, |
930e32c52c1c340136c0df137b659f01b065bfa8 | e2e/app.e2e-spec.ts | e2e/app.e2e-spec.ts | import { Ng2CiAppPage } from './app.po';
describe('ng2-ci-app App', function () {
let page: Ng2CiAppPage;
beforeEach(() => {
page = new Ng2CiAppPage();
});
it('should display message saying app works', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('NG Friends!');
});
it('should display some ng friends', () => {
page.navigateTo();
expect(page.getFriends()).toEqual(9);
});
});
| import { Ng2CiAppPage } from './app.po';
describe('ng2-ci-app App', function () {
let page: Ng2CiAppPage;
beforeEach(() => {
page = new Ng2CiAppPage();
});
it('should display message saying app works', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('NG Friends!');
});
it('should display some ng friends', () => {
page.navigateTo();
expect(page.getFriends()).toEqual(10);
});
});
| Fix e2e tests for new api | fix(tests): Fix e2e tests for new api
Fix e2e tests for new api
| TypeScript | mit | Elecash/ng2-ci-app,Elecash/ng2-ci-app,Elecash/ng2-ci-app,Elecash/ng2-ci-app | ---
+++
@@ -14,6 +14,6 @@
it('should display some ng friends', () => {
page.navigateTo();
- expect(page.getFriends()).toEqual(9);
+ expect(page.getFriends()).toEqual(10);
});
}); |
4dd0feb99fef8672cb443a8a746b520ef9f74357 | tests/src/debugger.spec.ts | tests/src/debugger.spec.ts | import { expect } from 'chai';
import {
CodeMirrorEditorFactory,
CodeMirrorMimeTypeService
} from '@jupyterlab/codemirror';
import { CommandRegistry } from '@phosphor/commands';
import { Debugger } from '../../lib/debugger';
import { DebugService } from '../../lib/service';
class TestPanel extends Debugger {}
describe('Debugger', () => {
const service = new DebugService();
const registry = new CommandRegistry();
const factoryService = new CodeMirrorEditorFactory();
const mimeTypeService = new CodeMirrorMimeTypeService();
let panel: TestPanel;
beforeEach(() => {
panel = new TestPanel({
debugService: service,
callstackCommands: {
registry,
continue: '',
terminate: '',
next: '',
stepIn: '',
stepOut: ''
},
editorServices: {
factoryService,
mimeTypeService
}
});
});
afterEach(() => {
panel.dispose();
});
describe('#constructor()', () => {
it('should create a new debugger panel', () => {
expect(panel).to.be.an.instanceOf(Debugger);
});
});
});
| import { expect } from 'chai';
import {
CodeMirrorEditorFactory,
CodeMirrorMimeTypeService
} from '@jupyterlab/codemirror';
import { CommandRegistry } from '@phosphor/commands';
import { Debugger } from '../../lib/debugger';
import { DebugService } from '../../lib/service';
class TestSidebar extends Debugger.Sidebar {}
describe('Debugger', () => {
const service = new DebugService();
const registry = new CommandRegistry();
const factoryService = new CodeMirrorEditorFactory();
const mimeTypeService = new CodeMirrorMimeTypeService();
let sidebar: TestSidebar;
beforeEach(() => {
sidebar = new TestSidebar({
service,
callstackCommands: {
registry,
continue: '',
terminate: '',
next: '',
stepIn: '',
stepOut: ''
},
editorServices: {
factoryService,
mimeTypeService
}
});
});
afterEach(() => {
sidebar.dispose();
});
describe('#constructor()', () => {
it('should create a new debugger sidebar', () => {
expect(sidebar).to.be.an.instanceOf(Debugger.Sidebar);
});
});
});
| Fix tests to instantiate a Debugger.Sidebar | Fix tests to instantiate a Debugger.Sidebar
| TypeScript | bsd-3-clause | jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab | ---
+++
@@ -11,7 +11,7 @@
import { DebugService } from '../../lib/service';
-class TestPanel extends Debugger {}
+class TestSidebar extends Debugger.Sidebar {}
describe('Debugger', () => {
const service = new DebugService();
@@ -19,11 +19,11 @@
const factoryService = new CodeMirrorEditorFactory();
const mimeTypeService = new CodeMirrorMimeTypeService();
- let panel: TestPanel;
+ let sidebar: TestSidebar;
beforeEach(() => {
- panel = new TestPanel({
- debugService: service,
+ sidebar = new TestSidebar({
+ service,
callstackCommands: {
registry,
continue: '',
@@ -40,12 +40,12 @@
});
afterEach(() => {
- panel.dispose();
+ sidebar.dispose();
});
describe('#constructor()', () => {
- it('should create a new debugger panel', () => {
- expect(panel).to.be.an.instanceOf(Debugger);
+ it('should create a new debugger sidebar', () => {
+ expect(sidebar).to.be.an.instanceOf(Debugger.Sidebar);
});
});
}); |
e957e4b81e72268b2432e11cec3bf112d797b804 | src/edmKit/connection.ts | src/edmKit/connection.ts | /**
* Created by grischa on 12/8/16.
*
* Get a connection to the Backend to run GraphQL query
*
*/
/// <reference path="../types.d.ts" />
import {createNetworkInterface, default as ApolloClient} from "apollo-client";
export class EDMConnection extends ApolloClient {
constructor(host: string, token: string) {
const graphqlEndpoint = `http://${host}/api/v1/graphql`;
const networkInterface = createNetworkInterface(graphqlEndpoint);
networkInterface.use([{
applyMiddleware(req, next) {
if (!req.options.headers) {
req.options.headers = {};
}
req.options.headers["authorization"] = `Bearer ${token}`;
// TODO: Set proxy for requests
//req.options.host = systemProxy.host;
//req.options.port = systemProxy.port;
next();
}
}]);
super({networkInterface: networkInterface});
}
}
| /**
* Created by grischa on 12/8/16.
*
* Get a connection to the Backend to run GraphQL query
*
*/
/// <reference path="../types.d.ts" />
import {createNetworkInterface, default as ApolloClient} from "apollo-client";
import {NetworkInterfaceOptions} from "apollo-client/transport/networkInterface";
export class EDMConnection extends ApolloClient {
constructor(host: string, token: string) {
const graphqlEndpoint = `http://${host}/api/v1/graphql`;
const networkInterface = createNetworkInterface(<NetworkInterfaceOptions>{uri: graphqlEndpoint});
networkInterface.use([{
applyMiddleware(req, next) {
if (!req.options.headers) {
req.options.headers = {};
}
req.options.headers["authorization"] = `Bearer ${token}`;
// TODO: Set proxy for requests
//req.options.host = systemProxy.host;
//req.options.port = systemProxy.port;
next();
}
}]);
super({networkInterface: networkInterface});
}
}
| Update deprecated method signature for apollo-client 0.5.8. | Update deprecated method signature for apollo-client 0.5.8.
| TypeScript | bsd-3-clause | mytardis/edm-client | ---
+++
@@ -6,13 +6,13 @@
*/
/// <reference path="../types.d.ts" />
import {createNetworkInterface, default as ApolloClient} from "apollo-client";
-
+import {NetworkInterfaceOptions} from "apollo-client/transport/networkInterface";
export class EDMConnection extends ApolloClient {
constructor(host: string, token: string) {
const graphqlEndpoint = `http://${host}/api/v1/graphql`;
- const networkInterface = createNetworkInterface(graphqlEndpoint);
+ const networkInterface = createNetworkInterface(<NetworkInterfaceOptions>{uri: graphqlEndpoint});
networkInterface.use([{
applyMiddleware(req, next) {
if (!req.options.headers) { |
29de5b72b5f9ef16b8827baff9c5bd268f8743f8 | app/components/editor.component.ts | app/components/editor.component.ts | import { Component, AfterViewInit, ElementRef } from '@angular/core';
import { TabService } from '../services/index';
import * as CodeMirror from 'codemirror';
@Component({
selector: 'rm-editor',
template: `
<div class="rm-editor">
<textarea></textarea>
</div>
`
})
export class EditorComponent implements AfterViewInit {
documents: any = {};
sessionId: string;
mirror: any;
constructor(
private tabs: TabService,
private elm: ElementRef
) {
}
ngAfterViewInit() {
const txtElm = this.elm.nativeElement.querySelector('textarea');
this.mirror = CodeMirror.fromTextArea(txtElm, this.editorOptions());
this.tabs.currentSessionId.subscribe(id => {
let doc = null;
if (!this.documents[id]) {
doc = CodeMirror.Doc('');
this.documents[id] = doc;
}
doc = this.documents[id];
const oldDoc = this.mirror.swapDoc(doc);
this.documents[this.sessionId] = oldDoc;
this.sessionId = id;
});
}
private editorOptions() {
return {
lineNumbers: false,
gutters: ['CodeMirror-lint-markers'],
lint: true,
smartIndent: false,
matchBrackets: true,
viewportMargin: Infinity,
showCursorWhenSelecting: true,
mode: 'text/x-csharp'
};
}
}
| import { Component, AfterViewInit, ElementRef } from '@angular/core';
import { TabService } from '../services/index';
import * as CodeMirror from 'codemirror';
import 'codemirror/mode/clike/clike';
@Component({
selector: 'rm-editor',
template: `
<div class="rm-editor">
<textarea></textarea>
</div>
`
})
export class EditorComponent implements AfterViewInit {
documents: any = {};
sessionId: string;
mirror: any;
constructor(
private tabs: TabService,
private elm: ElementRef
) {
}
ngAfterViewInit() {
const txtElm = this.elm.nativeElement.querySelector('textarea');
this.mirror = CodeMirror.fromTextArea(txtElm, this.editorOptions());
this.tabs.currentSessionId.subscribe(id => {
let doc = null;
if (!this.documents[id]) {
doc = CodeMirror.Doc('');
this.documents[id] = doc;
}
doc = this.documents[id];
const oldDoc = this.mirror.swapDoc(doc);
this.mirror.setOption('mode', 'text/x-csharp');
this.documents[this.sessionId] = oldDoc;
this.sessionId = id;
});
}
private editorOptions() {
return {
lineNumbers: false,
gutters: ['CodeMirror-lint-markers'],
lint: true,
smartIndent: false,
matchBrackets: true,
viewportMargin: Infinity,
showCursorWhenSelecting: true,
mode: 'text/x-csharp'
};
}
}
| Set mode when switching docs | Set mode when switching docs
| TypeScript | mit | stofte/linq-editor,stofte/ream-editor,stofte/ream-editor,stofte/ream-editor,stofte/ream-editor | ---
+++
@@ -1,6 +1,7 @@
import { Component, AfterViewInit, ElementRef } from '@angular/core';
import { TabService } from '../services/index';
import * as CodeMirror from 'codemirror';
+import 'codemirror/mode/clike/clike';
@Component({
selector: 'rm-editor',
@@ -30,6 +31,7 @@
}
doc = this.documents[id];
const oldDoc = this.mirror.swapDoc(doc);
+ this.mirror.setOption('mode', 'text/x-csharp');
this.documents[this.sessionId] = oldDoc;
this.sessionId = id;
}); |
d27b2f220f2ad538e28e2c45d9c4b549ba0f8869 | src/gracetabnote.ts | src/gracetabnote.ts | // [VexFlow](http://vexflow.com) - Copyright (c) Mohit Muthanna 2010.
// @author Balazs Forian-Szabo
//
// ## Description
//
// A basic implementation of grace notes
// to be rendered on a tab stave.
//
// See `tests/gracetabnote_tests.js` for usage examples.
import { TabNote, TabNoteStruct } from './tabnote';
/** Implements Crace Tab Note. */
export class GraceTabNote extends TabNote {
static get CATEGORY(): string {
return 'gracetabnotes';
}
/** Constructor providing a stave note struct */
constructor(note_struct: TabNoteStruct) {
super(note_struct, false);
this.setAttribute('type', 'GraceTabNote');
this.render_options = {
...this.render_options,
...{
// vertical shift from stave line
y_shift: 0.3,
// grace glyph scale
scale: 0.6,
// grace tablature font
font: '7.5pt Arial',
},
};
this.updateWidth();
}
/** Returns the category. */
getCategory(): string {
return GraceTabNote.CATEGORY;
}
/** Draws the note. */
draw(): void {
super.draw();
this.setRendered();
}
}
| // [VexFlow](http://vexflow.com) - Copyright (c) Mohit Muthanna 2010.
// @author Balazs Forian-Szabo
//
// ## Description
//
// A basic implementation of grace notes
// to be rendered on a tab stave.
//
// See `tests/gracetabnote_tests.js` for usage examples.
import { TabNote, TabNoteStruct } from './tabnote';
export class GraceTabNote extends TabNote {
static get CATEGORY(): string {
return 'gracetabnotes';
}
constructor(note_struct: TabNoteStruct) {
super(note_struct, false);
this.setAttribute('type', 'GraceTabNote');
this.render_options = {
...this.render_options,
...{
// vertical shift from stave line
y_shift: 0.3,
// grace glyph scale
scale: 0.6,
// grace tablature font
font: '7.5pt Arial',
},
};
this.updateWidth();
}
getCategory(): string {
return GraceTabNote.CATEGORY;
}
draw(): void {
super.draw();
this.setRendered();
}
}
| Remove comments that are redundant / incorrect / have typos. | Remove comments that are redundant / incorrect / have typos.
| TypeScript | mit | Tails/vexflow,Tails/vexflow,Tails/vexflow | ---
+++
@@ -10,13 +10,11 @@
import { TabNote, TabNoteStruct } from './tabnote';
-/** Implements Crace Tab Note. */
export class GraceTabNote extends TabNote {
static get CATEGORY(): string {
return 'gracetabnotes';
}
- /** Constructor providing a stave note struct */
constructor(note_struct: TabNoteStruct) {
super(note_struct, false);
this.setAttribute('type', 'GraceTabNote');
@@ -36,12 +34,10 @@
this.updateWidth();
}
- /** Returns the category. */
getCategory(): string {
return GraceTabNote.CATEGORY;
}
- /** Draws the note. */
draw(): void {
super.draw();
this.setRendered(); |
bd3b2e2d2c3f0287ac69927ccefe43942338d7b9 | validation/ValidationResults.ts | validation/ValidationResults.ts | import * as joi from 'joi';
import CtrlError from '../util/CtrlError';
export interface ProviderValidationResult<T> extends joi.ValidationResult<T> {
provider?: string;
}
export default class ValidationResults extends Array {
/**
* Returns if no validation contains at least one error.
*
* @type {boolean}
* @readonly
*/
get isValid() {
return !this.some(v => v.error);
}
/**
* Adds the provided validation result to the collection.
* dataProvider must be a srting describing the source of the validated
* data (ie. body, headers, query, params, etc.)
*
* @param {any} dataProvider The source of the validated data.
* @param {any} validationResult The result generated by joi.
*/
addValidation<T>(dataProvider: string, validationResult: ProviderValidationResult<T>) {
/*if (this.some(v => v.provider === dataProvider)) {
throw CtrlError.server('Validation result already contains provider.')
.code('dublicate_validation')
.blob({ provider: dataProvider });
}*/
validationResult.provider = dataProvider;
this.push(validationResult);
}
} | import * as joi from 'joi';
import CtrlError from '../util/CtrlError';
export interface ProviderValidationResult<T> extends joi.ValidationResult<T> {
provider?: string;
}
export default class ValidationResults extends Array {
/**
* Returns if no validation contains at least one error.
*
* @type {boolean}
* @readonly
*/
get isValid() {
return !this.some(v => v.error);
}
/**
* Adds the provided validation result to the collection.
* dataProvider must be a srting describing the source of the validated
* data (ie. body, headers, query, params, etc.)
*
* @param {any} dataProvider The source of the validated data.
* @param {any} validationResult The result generated by joi.
*/
addValidation<T>(dataProvider: string, validationResult: ProviderValidationResult<T>) {
this.push(Object.assign({}, validationResult, { provider: dataProvider }));
}
} | Copy validation result instance before editing it | Copy validation result instance before editing it
| TypeScript | mit | remolueoend/ctrl-connect | ---
+++
@@ -25,12 +25,6 @@
* @param {any} validationResult The result generated by joi.
*/
addValidation<T>(dataProvider: string, validationResult: ProviderValidationResult<T>) {
- /*if (this.some(v => v.provider === dataProvider)) {
- throw CtrlError.server('Validation result already contains provider.')
- .code('dublicate_validation')
- .blob({ provider: dataProvider });
- }*/
- validationResult.provider = dataProvider;
- this.push(validationResult);
+ this.push(Object.assign({}, validationResult, { provider: dataProvider }));
}
} |
badabe9a4e84805a2491073be2b66bd4cc76ff3f | packages/element-react/src/index.ts | packages/element-react/src/index.ts | import define, { getName } from '@skatejs/define';
import Element from '@skatejs/element';
import { createElement } from 'react';
import { render } from 'react-dom';
export default class extends Element {
disconnectedCallback() {
if (super.disconnectedCallback) {
super.disconnectedCallback();
}
render(null, this.renderRoot);
}
renderer() {
render(this.render(), this.renderRoot);
}
}
export function h(name, props, ...chren) {
if (name.prototype instanceof HTMLElement) {
name = getName(define(name));
}
return createElement(name, props, ...chren);
}
const symRef = Symbol();
export function setProps(domProps, refCallback = e => {}) {
return (
refCallback[symRef] ||
(refCallback[symRef] = e => {
refCallback(e);
if (e) {
Object.assign(e, domProps);
}
})
);
}
export declare namespace h {
namespace JSX {
interface Element {}
type LibraryManagedAttributes<E, _> = E extends {
props: infer Props;
prototype: infer Prototype;
}
? Pick<Prototype, Extract<keyof Prototype, keyof Props>>
: _;
}
}
| import define, { getName } from '@skatejs/define';
import Element from '@skatejs/element';
import { createElement } from 'react';
import { render } from 'react-dom';
export default class extends Element {
disconnectedCallback() {
if (super.disconnectedCallback) {
super.disconnectedCallback();
}
render(null, this.renderRoot);
}
renderer() {
render(this.render(), this.renderRoot);
}
}
export function h(name, props, ...chren) {
if (name.prototype instanceof HTMLElement) {
name = getName(define(name));
}
return createElement(name, props, ...chren);
}
const symRef = Symbol();
export function setProps(domProps, refCallback?) {
refCallback = refCallback || (refCallback = e => {});
return (
refCallback[symRef] ||
(refCallback[symRef] = e => {
refCallback(e);
if (e) {
Object.assign(e, domProps);
}
})
);
}
export declare namespace h {
namespace JSX {
interface Element {}
type LibraryManagedAttributes<E, _> = E extends {
props: infer Props;
prototype: infer Prototype;
}
? Pick<Prototype, Extract<keyof Prototype, keyof Props>>
: _;
}
}
| Improve refCallback handling by not using default args. | Improve refCallback handling by not using default args.
| TypeScript | mit | skatejs/skatejs,skatejs/skatejs,skatejs/skatejs | ---
+++
@@ -23,7 +23,8 @@
}
const symRef = Symbol();
-export function setProps(domProps, refCallback = e => {}) {
+export function setProps(domProps, refCallback?) {
+ refCallback = refCallback || (refCallback = e => {});
return (
refCallback[symRef] ||
(refCallback[symRef] = e => { |
9743d5b01069433ee45f38d3637a8e2a5e7b307b | src/app/units/states/edit/directives/unit-students-editor/student-tutorial-select/student-tutorial-select.component.ts | src/app/units/states/edit/directives/unit-students-editor/student-tutorial-select/student-tutorial-select.component.ts | import { Unit } from './../../../../../../ajs-upgraded-providers';
import { Component, Input } from '@angular/core';
import { TutorialStream } from 'src/app/api/models/tutorial-stream/tutorial-stream';
import { Tutorial } from 'src/app/api/models/tutorial/tutorial';
@Component({
selector: 'student-tutorial-select',
templateUrl: 'student-tutorial-select.component.html',
styleUrls: ['student-tutorial-select.component.scss']
})
export class StudentTutorialSelectComponent {
@Input() unit: any;
@Input() student: any;
/**
* Compare a tutorial with an enrolment
*
* @param aEntity The tutorial itself
* @param bEntity The tutorial enrolment
*/
compareSelection(aEntity: Tutorial, bEntity: any) {
if (!aEntity || !bEntity) {
return;
}
return aEntity.id === bEntity.tutorial_id;
}
public tutorialsForStreamAndStudent(student: any, stream: TutorialStream = undefined) {
return this.unit.tutorials.filter(tutorial => {
if (tutorial.tutorial_stream && stream) {
return tutorial.tutorial_stream.abbreviation === stream.abbreviation
&& student.campus_id === tutorial.campus.id;
} else if (!tutorial.tutorial_stream && !stream) {
return student.campus_id === tutorial.campus.id;
}
});
}
}
| import { Unit } from './../../../../../../ajs-upgraded-providers';
import { Component, Input } from '@angular/core';
import { TutorialStream } from 'src/app/api/models/tutorial-stream/tutorial-stream';
import { Tutorial } from 'src/app/api/models/tutorial/tutorial';
@Component({
selector: 'student-tutorial-select',
templateUrl: 'student-tutorial-select.component.html',
styleUrls: ['student-tutorial-select.component.scss']
})
export class StudentTutorialSelectComponent {
@Input() unit: any;
@Input() student: any;
/**
* Compare a tutorial with an enrolment
*
* @param aEntity The tutorial itself
* @param bEntity The tutorial enrolment
*/
compareSelection(aEntity: Tutorial, bEntity: any) {
if (!aEntity || !bEntity) {
return;
}
return aEntity.id === bEntity.tutorial_id;
}
private switchToTutorial(tutorial: Tutorial) {
this.student.switchToTutorial(tutorial);
}
public tutorialsForStreamAndStudent(student: any, stream: TutorialStream = undefined) {
return this.unit.tutorials.filter(tutorial => {
var result: boolean = student.campus_id == null || tutorial.campus == null || student.campus_id === tutorial.campus.id;
if (!result) return result;
if (tutorial.tutorial_stream && stream) {
return tutorial.tutorial_stream.abbreviation === stream.abbreviation;
} else if (!tutorial.tutorial_stream && !stream) {
return true;
} else {
return false;
}
});
}
}
| Correct switch tutorial and tutorial list in tutorial select | FIX: Correct switch tutorial and tutorial list in tutorial select
| TypeScript | agpl-3.0 | doubtfire-lms/doubtfire-web,doubtfire-lms/doubtfire-web,doubtfire-lms/doubtfire-web,doubtfire-lms/doubtfire-web | ---
+++
@@ -12,7 +12,6 @@
@Input() unit: any;
@Input() student: any;
-
/**
* Compare a tutorial with an enrolment
*
@@ -26,13 +25,20 @@
return aEntity.id === bEntity.tutorial_id;
}
+ private switchToTutorial(tutorial: Tutorial) {
+ this.student.switchToTutorial(tutorial);
+ }
+
public tutorialsForStreamAndStudent(student: any, stream: TutorialStream = undefined) {
return this.unit.tutorials.filter(tutorial => {
+ var result: boolean = student.campus_id == null || tutorial.campus == null || student.campus_id === tutorial.campus.id;
+ if (!result) return result;
if (tutorial.tutorial_stream && stream) {
- return tutorial.tutorial_stream.abbreviation === stream.abbreviation
- && student.campus_id === tutorial.campus.id;
+ return tutorial.tutorial_stream.abbreviation === stream.abbreviation;
} else if (!tutorial.tutorial_stream && !stream) {
- return student.campus_id === tutorial.campus.id;
+ return true;
+ } else {
+ return false;
}
});
} |
e14987f154790054dca997ce443f95da3da12f92 | packages/ng/demo/app/shared/redirect/redirect.component.ts | packages/ng/demo/app/shared/redirect/redirect.component.ts | import { Component, OnInit } from '@angular/core';
import {
RedirectService,
RedirectEnvironment,
RedirectStatus,
} from './redirect.service';
@Component({
selector: 'demo-redirect',
templateUrl: './redirect.component.html',
})
export class RedirectComponent implements OnInit {
url = 'lucca.local.dev';
login = 'passepartout';
password = '';
status$ = this.env.status$;
url$ = this.env.url$;
login$ = this.env.login$;
connected$ = this.status$.map(s => s === RedirectStatus.connected);
connecting$ = this.status$.map(s => s === RedirectStatus.connecting);
disconnected$ = this.status$.map(s => s === RedirectStatus.disconnected);
loading = false;
constructor(
private service: RedirectService,
private env: RedirectEnvironment,
) {}
ngOnInit() {
if (!this.env.redirect) {
this.connect();
}
}
connect() {
this.loading = true;
this.service.login(this.url, this.login, this.password).subscribe(() => {
this.loading = false;
});
}
}
| import { Component, OnInit } from '@angular/core';
import {
RedirectService,
RedirectEnvironment,
RedirectStatus,
} from './redirect.service';
@Component({
selector: 'demo-redirect',
templateUrl: './redirect.component.html',
})
export class RedirectComponent implements OnInit {
url = 'lucca.local.dev';
login = 'passepartout';
password = '';
status$ = this.env.status$;
url$ = this.env.url$;
login$ = this.env.login$;
connected$ = this.status$.map(s => s === RedirectStatus.connected);
connecting$ = this.status$.map(s => s === RedirectStatus.connecting);
disconnected$ = this.status$.map(s => s === RedirectStatus.disconnected);
loading = false;
constructor(
private service: RedirectService,
private env: RedirectEnvironment,
) {}
ngOnInit() {
/*
Comment in order to let people choose to connect and enter the right env before connecting
if (!this.env.redirect) {
this.connect();
}
*/
}
connect() {
this.loading = true;
this.service.login(this.url, this.login, this.password).subscribe(() => {
this.loading = false;
});
}
}
| Update auto connect in demo => remove auto connect to let people change the environement before connecting | [NG] Update auto connect in demo => remove auto connect to let people change the environement before connecting
| TypeScript | mit | LuccaSA/lucca-front,LuccaSA/lucca-front,LuccaSA/lucca-front,LuccaSA/lucca-front | ---
+++
@@ -29,9 +29,12 @@
) {}
ngOnInit() {
+ /*
+ Comment in order to let people choose to connect and enter the right env before connecting
if (!this.env.redirect) {
this.connect();
}
+ */
}
connect() { |
8ffa707bd32f08f6e4b78535a3f98d81760b5796 | src/button/index.ts | src/button/index.ts | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TlButton } from './button';
export * from './button';
@NgModule({
imports: [
CommonModule,
],
declarations: [
TlButton
],
exports: [
TlButton
]
})
export class ButtonModule {}
| import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TlButton } from './button';
import { ToneColorGenerator } from '../core/helper/tonecolor-generator';
export * from './button';
@NgModule({
imports: [
CommonModule,
],
declarations: [
TlButton
],
exports: [
TlButton
],
providers: [
ToneColorGenerator
]
})
export class ButtonModule {}
| Add helper provider for tone color generator | feat(button): Add helper provider for tone color generator
| TypeScript | mit | TemainfoSistemas/truly-ui,TemainfoSistemas/truly-ui,TemainfoSistemas/truly-ui | ---
+++
@@ -2,6 +2,7 @@
import { CommonModule } from '@angular/common';
import { TlButton } from './button';
+import { ToneColorGenerator } from '../core/helper/tonecolor-generator';
export * from './button';
@@ -14,6 +15,9 @@
],
exports: [
TlButton
+ ],
+ providers: [
+ ToneColorGenerator
]
})
export class ButtonModule {} |
b467ca185ab0505098e80aa6a7657995a33ba2b6 | desktop/src/main/menu/window.ts | desktop/src/main/menu/window.ts | import { MenuItemConstructorOptions } from 'electron'
import { openLauncherWindow } from '../launcher/window'
import { showLogs } from '../logging/window'
import { isMac } from './utils'
export const baseWindowSubMenu: MenuItemConstructorOptions[] = [
{ role: 'minimize' },
{ role: 'zoom' },
{ type: 'separator' },
{
label: 'Launcher',
accelerator: 'Shift+CommandOrControl+1',
click: () => {
openLauncherWindow()
},
},
...(isMac
? [
{ type: 'separator' as const },
{ role: 'front' as const },
{ type: 'separator' as const },
{ role: 'window' as const },
]
: [{ role: 'close' as const }]),
{ type: 'separator' },
{
label: 'Advanced',
submenu: [
{
label: 'Debug Logs',
click: () => {
showLogs()
},
},
{ type: 'separator' },
{ role: 'reload' },
{ role: 'forceReload' },
{ role: 'toggleDevTools' },
],
},
]
export const baseWindowMenu: MenuItemConstructorOptions = {
label: 'Window',
submenu: baseWindowSubMenu,
}
| import { MenuItemConstructorOptions } from 'electron'
import { openLauncherWindow } from '../launcher/window'
import { showLogs } from '../logging/window'
import { isMac } from './utils'
export const baseWindowSubMenu: MenuItemConstructorOptions[] = [
{ role: 'minimize' },
{ role: 'zoom' },
{ type: 'separator' },
{
label: 'Launcher',
accelerator: 'Shift+CommandOrControl+1',
click: () => {
openLauncherWindow()
},
},
...(isMac
? [
{ type: 'separator' as const },
{ role: 'front' as const },
{ type: 'separator' as const },
{ role: 'window' as const },
]
: []),
{ type: 'separator' },
{
label: 'Advanced',
submenu: [
{
label: 'Debug Logs',
click: () => {
showLogs()
},
},
{ type: 'separator' },
{ role: 'reload' },
{ role: 'forceReload' },
{ role: 'toggleDevTools' },
],
},
]
export const baseWindowMenu: MenuItemConstructorOptions = {
label: 'Window',
submenu: baseWindowSubMenu,
}
| Remove duplicated Window Close menu item | fix(Desktop): Remove duplicated Window Close menu item
Close #1176
| TypeScript | apache-2.0 | stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila | ---
+++
@@ -21,7 +21,7 @@
{ type: 'separator' as const },
{ role: 'window' as const },
]
- : [{ role: 'close' as const }]),
+ : []),
{ type: 'separator' },
{
label: 'Advanced', |
2523989bbfcf92b4dd7514afa320d7469a1ecf3a | src/components/Queue/QueueTimer.tsx | src/components/Queue/QueueTimer.tsx | import * as React from 'react';
import { Caption } from '@shopify/polaris';
import { displaySecondsAsHHMMSS } from '../../utils/dates';
interface Props {
readonly initialTimeLeft: number;
}
interface State {
readonly secondsUntilExpiration: number;
}
class QueueTimer extends React.PureComponent<Props, State> {
private static readonly tickRate = 500;
private timerId: number;
private dateNumExpiration: number;
constructor(props: Props) {
super(props);
this.state = { secondsUntilExpiration: props.initialTimeLeft };
}
componentDidMount() {
this.startTimer();
}
componentWillUnmount() {
clearInterval(this.timerId);
}
private resetDateNumExpiration = (timeLeft: number) =>
(this.dateNumExpiration = Date.now() + timeLeft * 1000);
private startTimer = () => {
clearInterval(this.timerId);
this.resetDateNumExpiration(this.props.initialTimeLeft);
this.timerId = window.setInterval(() => this.tick(), QueueTimer.tickRate);
};
private tick = () =>
this.setState({
secondsUntilExpiration: (this.dateNumExpiration - Date.now()) / 1000
});
public render() {
return (
<Caption>
{displaySecondsAsHHMMSS(this.state.secondsUntilExpiration)}
</Caption>
);
}
}
export default QueueTimer;
| import * as React from 'react';
import { Caption } from '@shopify/polaris';
import { displaySecondsAsHHMMSS } from '../../utils/dates';
interface Props {
readonly initialTimeLeft: number;
}
interface State {
readonly secondsUntilExpiration: number;
}
class QueueTimer extends React.PureComponent<Props, State> {
private static readonly tickRate = 500;
private timerId: number;
private dateNumExpiration: number;
constructor(props: Props) {
super(props);
this.state = { secondsUntilExpiration: props.initialTimeLeft };
}
static getDerivedStateFromProps(nextProps: Props): Partial<State> {
return {
secondsUntilExpiration: nextProps.initialTimeLeft
};
}
componentDidMount() {
this.startTimer();
}
componentWillUnmount() {
clearInterval(this.timerId);
}
private resetDateNumExpiration = (timeLeft: number) =>
(this.dateNumExpiration = Date.now() + timeLeft * 1000);
private startTimer = () => {
clearInterval(this.timerId);
this.resetDateNumExpiration(this.props.initialTimeLeft);
this.timerId = window.setInterval(this.tick, QueueTimer.tickRate);
};
private tick = () =>
this.setState({
secondsUntilExpiration: (this.dateNumExpiration - Date.now()) / 1000
});
public render() {
return (
<Caption>
{displaySecondsAsHHMMSS(this.state.secondsUntilExpiration)}
</Caption>
);
}
}
export default QueueTimer;
| Fix items in queue showing incorrect time remaining when added via watcher. | Fix items in queue showing incorrect time remaining when added via watcher.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -20,6 +20,12 @@
this.state = { secondsUntilExpiration: props.initialTimeLeft };
}
+ static getDerivedStateFromProps(nextProps: Props): Partial<State> {
+ return {
+ secondsUntilExpiration: nextProps.initialTimeLeft
+ };
+ }
+
componentDidMount() {
this.startTimer();
}
@@ -34,7 +40,7 @@
private startTimer = () => {
clearInterval(this.timerId);
this.resetDateNumExpiration(this.props.initialTimeLeft);
- this.timerId = window.setInterval(() => this.tick(), QueueTimer.tickRate);
+ this.timerId = window.setInterval(this.tick, QueueTimer.tickRate);
};
private tick = () => |
8d381d1f680e76489f9e5385387d3f66075235d2 | lib/src/hooks/useOnScrollHandle.ts | lib/src/hooks/useOnScrollHandle.ts | import { useCallback } from 'react';
import {
Animated,
LayoutChangeEvent,
NativeSyntheticEvent,
NativeScrollEvent,
} from 'react-native';
import { StretchyOnScroll } from '../types';
import { useImageWrapperLayout } from './useImageWrapperLayout';
import { useStretchyAnimation } from './useStretchyAnimation';
export type UseOnScrollHandle = (
listener?: StretchyOnScroll,
) => {
animation: Animated.Value;
onImageWrapperLayout(event: LayoutChangeEvent): void;
onScroll(event: NativeSyntheticEvent<NativeScrollEvent>): void;
};
export const useOnScrollHandle: UseOnScrollHandle = (listener) => {
const [imageWrapperLayout, onImageWrapperLayout] = useImageWrapperLayout();
const animationListener = useCallback(
(offsetY) => {
if (listener) {
if (imageWrapperLayout && offsetY >= imageWrapperLayout?.height) {
listener(offsetY, true);
} else {
listener(offsetY, false);
}
}
},
[imageWrapperLayout],
);
const { animation, onAnimationEvent } = useStretchyAnimation(
animationListener,
);
return {
animation,
onImageWrapperLayout,
onScroll: onAnimationEvent,
};
};
| import { useCallback } from 'react';
import {
Animated,
LayoutChangeEvent,
NativeSyntheticEvent,
NativeScrollEvent,
} from 'react-native';
import { StretchyOnScroll } from '../types';
import { useImageWrapperLayout } from './useImageWrapperLayout';
import { useStretchyAnimation } from './useStretchyAnimation';
export type UseOnScrollHandle = (
listener?: StretchyOnScroll,
) => {
animation: Animated.Value;
onImageWrapperLayout(event: LayoutChangeEvent): void;
onScroll(event: NativeSyntheticEvent<NativeScrollEvent>): void;
};
export const useOnScrollHandle: UseOnScrollHandle = (listener) => {
const [imageWrapperLayout, onImageWrapperLayout] = useImageWrapperLayout();
const animationListener = useCallback(
(offsetY: number) => {
if (listener) {
if (imageWrapperLayout && offsetY >= imageWrapperLayout?.height) {
listener(offsetY, true);
} else {
listener(offsetY, false);
}
}
},
[imageWrapperLayout],
);
const { animation, onAnimationEvent } = useStretchyAnimation(
animationListener,
);
return {
animation,
onImageWrapperLayout,
onScroll: onAnimationEvent,
};
};
| Add missing type to animationListener | Add missing type to animationListener
| TypeScript | mit | hamidhadi/react-native-stretchy,hamidhadi/react-native-stretchy,hamidhadi/react-native-stretchy,hamidhadi/react-native-stretchy | ---
+++
@@ -21,7 +21,7 @@
const [imageWrapperLayout, onImageWrapperLayout] = useImageWrapperLayout();
const animationListener = useCallback(
- (offsetY) => {
+ (offsetY: number) => {
if (listener) {
if (imageWrapperLayout && offsetY >= imageWrapperLayout?.height) {
listener(offsetY, true); |
42d6108e8d932c73b75866b936aca57245f69553 | app/src/lib/enterprise.ts | app/src/lib/enterprise.ts | /**
* The oldest officially supported version of GitHub Enterprise.
* This information is used in user-facing text and shouldn't be
* considered a hard limit, i.e. older versions of GitHub Enterprise
* might (and probably do) work just fine but this should be a fairly
* recent version that we can safely say that we'll work well with.
*
* I picked the current minimum (2.8) because it was the version
* running on our internal GitHub Enterprise instance at the time
* we implemented Enterprise sign in (desktop/desktop#664)
*/
export const minimumSupportedEnterpriseVersion = '2.8.0'
| /**
* The oldest officially supported version of GitHub Enterprise.
* This information is used in user-facing text and shouldn't be
* considered a hard limit, i.e. older versions of GitHub Enterprise
* might (and probably do) work just fine but this should be a fairly
* recent version that we can safely say that we'll work well with.
*/
export const minimumSupportedEnterpriseVersion = '3.0.0'
| Bump minimum supported version for workflow scope | Bump minimum supported version for workflow scope
| TypeScript | mit | desktop/desktop,desktop/desktop,shiftkey/desktop,j-f1/forked-desktop,j-f1/forked-desktop,j-f1/forked-desktop,shiftkey/desktop,shiftkey/desktop,j-f1/forked-desktop,desktop/desktop,shiftkey/desktop,desktop/desktop | ---
+++
@@ -4,9 +4,5 @@
* considered a hard limit, i.e. older versions of GitHub Enterprise
* might (and probably do) work just fine but this should be a fairly
* recent version that we can safely say that we'll work well with.
- *
- * I picked the current minimum (2.8) because it was the version
- * running on our internal GitHub Enterprise instance at the time
- * we implemented Enterprise sign in (desktop/desktop#664)
*/
-export const minimumSupportedEnterpriseVersion = '2.8.0'
+export const minimumSupportedEnterpriseVersion = '3.0.0' |
b546a1cbe2d4fb4b719daed038401e2252c5a040 | src/app/leaflet/leaflet-zoom/leaflet-zoom.component.ts | src/app/leaflet/leaflet-zoom/leaflet-zoom.component.ts | /*!
* Leaflet Zoom Component
*
* Copyright(c) Exequiel Ceasar Navarrete <[email protected]>
* Licensed under MIT
*/
import { Component, OnInit, ViewChild, ElementRef, Renderer } from '@angular/core';
import { LeafletMapService } from '../leaflet-map.service';
import * as L from 'leaflet';
@Component({
selector: 'app-leaflet-zoom',
templateUrl: './leaflet-zoom.component.html',
styleUrls: ['./leaflet-zoom.component.sass']
})
export class LeafletZoomComponent implements OnInit {
public control: L.Control;
@ViewChild('controlwrapper') controlWrapper: ElementRef;
constructor(
private _mapService: LeafletMapService,
private _renderer: Renderer
) { }
ngOnInit() {
this.control = new (L as any).Control.Zoom();
this._mapService
.getMap()
.then((map: L.Map) => {
// add to the map
this.control.addTo(map);
// remove the default container
this.control.getContainer().remove();
let container = this.control.onAdd(map);
// append the element container to the controlWrapper
this._renderer.invokeElementMethod(this.controlWrapper.nativeElement, 'appendChild', [
container
]);
})
;
}
}
| /*!
* Leaflet Zoom Component
*
* Copyright(c) Exequiel Ceasar Navarrete <[email protected]>
* Licensed under MIT
*/
import { Component, OnInit, ViewChild, ElementRef, Renderer } from '@angular/core';
import { LeafletMapService } from '../leaflet-map.service';
import * as L from 'leaflet';
@Component({
selector: 'app-leaflet-zoom',
templateUrl: './leaflet-zoom.component.html',
styleUrls: ['./leaflet-zoom.component.sass']
})
export class LeafletZoomComponent implements OnInit {
public control: L.Control;
@ViewChild('controlwrapper') controlWrapper: ElementRef;
constructor(
private _mapService: LeafletMapService,
private _renderer: Renderer
) { }
ngOnInit() {
this.control = new (L as any).Control.Zoom();
this._mapService
.getMap()
.then((map: L.Map) => {
// add to the map
this.control.addTo(map);
// remove the default container
this._renderer.invokeElementMethod(this.control.getContainer(), 'remove');
let container = this.control.onAdd(map);
// append the element container to the controlWrapper
this._renderer.invokeElementMethod(this.controlWrapper.nativeElement, 'appendChild', [
container
]);
})
;
}
}
| Use renderer to remove the container of zoom control | Use renderer to remove the container of zoom control
| TypeScript | mit | ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2 | ---
+++
@@ -34,7 +34,7 @@
this.control.addTo(map);
// remove the default container
- this.control.getContainer().remove();
+ this._renderer.invokeElementMethod(this.control.getContainer(), 'remove');
let container = this.control.onAdd(map);
|
5590ea7ddb420e8d6946ded51b902bbdff587b4d | src/extension.ts | src/extension.ts | 'use strict';
import * as vscode from 'vscode';
import * as fs from 'fs-extra';
import * as path from 'path';
import { run as convertToTypeScript } from 'react-js-to-ts';
export function activate(context: vscode.ExtensionContext) {
let disposable = vscode.commands.registerCommand('extension.convertReactToTypeScript', async () => {
const editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
const input = editor.document.getText();
const inputPath = path.join(__dirname, randomFileName());
await fs.writeFile(inputPath, input);
const result = convertToTypeScript(inputPath);
editor.edit(async (builder) => {
const start = new vscode.Position(0, 0);
const lines = result.split(/\n|\r\n/);
const end = new vscode.Position(lines.length, lines[lines.length - 1].length)
const allRange = new vscode.Range(start, end);
builder.replace(allRange, result);
// vscode
// Delete temp file
await fs.remove(inputPath);
})
});
context.subscriptions.push(disposable);
}
// this method is called when your extension is deactivated
export function deactivate() {
}
function randomFileName() {
return Math.random().toString(36).substring(2) + '.ts';
}
| 'use strict';
import * as vscode from 'vscode';
import * as fs from 'fs-extra';
import * as path from 'path';
import { run as convertToTypeScript } from 'react-js-to-ts';
export function activate(context: vscode.ExtensionContext) {
let disposable = vscode.commands.registerCommand('extension.convertReactToTypeScript', async () => {
const editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
// Rename file to .tsx
const filePath = getFilePath();
const tsxPath = getTSXFileName(filePath);
await fs.rename(filePath, tsxPath);
const input = editor.document.getText();
const result = convertToTypeScript(tsxPath);
editor.edit(async (builder) => {
const start = new vscode.Position(0, 0);
const lines = result.split(/\n|\r\n/);
const end = new vscode.Position(lines.length, lines[lines.length - 1].length)
const allRange = new vscode.Range(start, end);
builder.replace(allRange, result);
})
});
context.subscriptions.push(disposable);
}
function getFilePath(): string {
const activeEditor: vscode.TextEditor = vscode.window.activeTextEditor;
const document: vscode.TextDocument = activeEditor && activeEditor.document;
return document && document.fileName;
}
function getTSXFileName(fileName: string) {
const ext = path.extname(fileName).replace(/^\./, '');
const extNameRegex = new RegExp(`${ext}$`);
return fileName.replace(extNameRegex, 'tsx');
}
// this method is called when your extension is deactivated
export function deactivate() {
}
| Rename file and don't use temp files | Rename file and don't use temp files
| TypeScript | apache-2.0 | mohsen1/react-javascript-to-typescript-transform-vscode | ---
+++
@@ -13,31 +13,39 @@
return;
}
+ // Rename file to .tsx
+ const filePath = getFilePath();
+ const tsxPath = getTSXFileName(filePath);
+ await fs.rename(filePath, tsxPath);
+
const input = editor.document.getText();
- const inputPath = path.join(__dirname, randomFileName());
- await fs.writeFile(inputPath, input);
- const result = convertToTypeScript(inputPath);
+ const result = convertToTypeScript(tsxPath);
+
editor.edit(async (builder) => {
const start = new vscode.Position(0, 0);
const lines = result.split(/\n|\r\n/);
const end = new vscode.Position(lines.length, lines[lines.length - 1].length)
const allRange = new vscode.Range(start, end);
builder.replace(allRange, result);
-
- // vscode
-
- // Delete temp file
- await fs.remove(inputPath);
})
});
context.subscriptions.push(disposable);
}
+function getFilePath(): string {
+ const activeEditor: vscode.TextEditor = vscode.window.activeTextEditor;
+ const document: vscode.TextDocument = activeEditor && activeEditor.document;
+
+ return document && document.fileName;
+}
+
+function getTSXFileName(fileName: string) {
+ const ext = path.extname(fileName).replace(/^\./, '');
+ const extNameRegex = new RegExp(`${ext}$`);
+ return fileName.replace(extNameRegex, 'tsx');
+}
+
// this method is called when your extension is deactivated
export function deactivate() {
}
-
-function randomFileName() {
- return Math.random().toString(36).substring(2) + '.ts';
-} |
f0297f075abf6753f0aebc22d698808aff78581d | src/store/localStoragePersister.ts | src/store/localStoragePersister.ts | import { IRootState } from '../types';
const localStorageKey = 'todoState';
export class LocalStoragePersister {
public loadPersistedState(): IRootState {
return JSON.parse(localStorage.getItem(localStorageKey) || '{ todos: [] }') as IRootState;
}
public persistState(state: IRootState): void {
localStorage.setItem(localStorageKey, JSON.stringify(state));
}
}
| import { IRootState } from '../types';
const localStorageKey = 'todoState';
export class LocalStoragePersister {
public loadPersistedState(): IRootState {
return JSON.parse(localStorage.getItem(localStorageKey) || '{ "todos": [] }') as IRootState;
}
public persistState(state: IRootState): void {
localStorage.setItem(localStorageKey, JSON.stringify(state));
}
}
| Fix initial state load in IE | Fix initial state load in IE
| TypeScript | mit | markschabacker/todoMVC_react,markschabacker/todoMVC_react,markschabacker/todoMVC_react | ---
+++
@@ -5,7 +5,7 @@
export class LocalStoragePersister {
public loadPersistedState(): IRootState {
- return JSON.parse(localStorage.getItem(localStorageKey) || '{ todos: [] }') as IRootState;
+ return JSON.parse(localStorage.getItem(localStorageKey) || '{ "todos": [] }') as IRootState;
}
public persistState(state: IRootState): void { |
0144d7f42c9ba892d76f559a06e724fbc6473577 | lib/addons/src/public_api.ts | lib/addons/src/public_api.ts | export * from './make-decorator';
export * from '.';
export * from './storybook-channel-mock';
// There can only be 1 default export per entry point and it has to be directly from public_api
// Exporting this twice in order to to be able to import it like { addons } instead of 'addons'
// prefer import { addons } from '@storybook/addons' over import addons from '@storybook/addons'
//
// See index.ts
import { addons } from '.';
export default addons;
| export * from './make-decorator';
export * from './index';
export * from './storybook-channel-mock';
// There can only be 1 default export per entry point and it has to be directly from public_api
// Exporting this twice in order to to be able to import it like { addons } instead of 'addons'
// prefer import { addons } from '@storybook/addons' over import addons from '@storybook/addons'
//
// See index.ts
import { addons } from './index';
export default addons;
| Fix "lib/addons" default export for react-native. | Fix "lib/addons" default export for react-native. | TypeScript | mit | storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook | ---
+++
@@ -1,5 +1,5 @@
export * from './make-decorator';
-export * from '.';
+export * from './index';
export * from './storybook-channel-mock';
// There can only be 1 default export per entry point and it has to be directly from public_api
@@ -7,5 +7,5 @@
// prefer import { addons } from '@storybook/addons' over import addons from '@storybook/addons'
//
// See index.ts
-import { addons } from '.';
+import { addons } from './index';
export default addons; |
98380ef6712d5708916d5b7db502f8dda7d11c9e | test/extension.test.ts | test/extension.test.ts | import * as fs from 'fs';
import * as vscode from 'vscode';
import * as tmp from 'tmp';
import * as util from './util';
const extension = vscode.extensions.getExtension('dlang-vscode.dlang');
before(function (done) {
this.timeout(0);
extension.activate()
.then(() => new Promise((resolve) =>
tmp.tmpName({ postfix: '.d' }, (err, path) => {
util.setTmpUri(path);
resolve();
})))
.then(() => done());
});
after(function (done) {
this.timeout(0);
extension.exports.dcd.server.stop();
fs.unlink(util.tmpUri.fsPath, done);
});
| import * as fs from 'fs';
import * as vscode from 'vscode';
import * as tmp from 'tmp';
import * as util from './util';
const extension = vscode.extensions.getExtension('dlang-vscode.dlang');
before(function (done) {
this.timeout(0);
extension.activate()
.then(() => new Promise((resolve) =>
tmp.tmpName({ postfix: '.d' }, (err, path) => {
util.setTmpUri(path);
resolve();
})))
.then(() => done());
});
after(function (done) {
this.timeout(0);
extension.exports.dcd.server.stop();
vscode.commands.executeCommand('workbench.action.closeActiveEditor')
.then(() => fs.unlink(util.tmpUri.fsPath, done));
});
| Fix removing temporary D file | Fix removing temporary D file
| TypeScript | mit | dlang-vscode/dlang-vscode,mattiascibien/dlang-vscode | ---
+++
@@ -19,5 +19,6 @@
after(function (done) {
this.timeout(0);
extension.exports.dcd.server.stop();
- fs.unlink(util.tmpUri.fsPath, done);
+ vscode.commands.executeCommand('workbench.action.closeActiveEditor')
+ .then(() => fs.unlink(util.tmpUri.fsPath, done));
}); |
fbddf94debbb15053880a83f14449c581b5c69cc | src/app/task/task-dashboard/task-dashboard.component.ts | src/app/task/task-dashboard/task-dashboard.component.ts | import { Component, OnInit } from '@angular/core';
import { Task, TaskService } from './../../core/core.module';
@Component({
selector: 'app-task-dashboard',
templateUrl: './task-dashboard.component.html',
styleUrls: ['./task-dashboard.component.scss']
})
export class TaskDashboardComponent implements OnInit {
tasks$;
constructor(private taskService: TaskService) { }
ngOnInit() {
this.updateTaskList();
}
taskReceived(task){
this.taskService.upsert(task).subscribe(r => {
this.updateTaskList();
});
}
updateTaskList(){
this.tasks$ = this.getTasks();
}
deleteTask(task: Task) {
this.tasks$ = this.taskService.remove(task).switchMap(_ => this.getTasks());
}
getTasks(){
return this.taskService.getTasks().map(tasks => tasks.sort((a, b) => a.tag > b.tag ? +1 : -1));
}
}
| import { TaskListComponent } from './../task-list/task-list.component';
import { Component, OnInit, ViewChild } from '@angular/core';
import { Task, TaskService } from './../../core/core.module';
@Component({
selector: 'app-task-dashboard',
templateUrl: './task-dashboard.component.html',
styleUrls: ['./task-dashboard.component.scss']
})
export class TaskDashboardComponent implements OnInit {
@ViewChild(TaskListComponent) taskList: TaskListComponent;
tasks$;
constructor(private taskService: TaskService) { }
ngOnInit() {
this.updateTaskList();
}
taskReceived(task){
this.taskService.upsert(task).subscribe(r => {
this.updateTaskList();
});
}
updateTaskList(){
this.tasks$ = this.getTasks();
}
deleteTask(task: Task) {
this.tasks$ = this.taskService.remove(task).switchMap(_ => this.getTasks());
}
getTasks(){
return this.taskService.getTasks().map(tasks => tasks.sort((a, b) => a.tag > b.tag ? +1 : -1));
}
}
| Add task list reference to task dashboard. | Add task list reference to task dashboard.
| TypeScript | mit | s-soltys/RewardYourselfApp,s-soltys/RewardYourselfApp,s-soltys/RewardYourselfApp | ---
+++
@@ -1,4 +1,5 @@
-import { Component, OnInit } from '@angular/core';
+import { TaskListComponent } from './../task-list/task-list.component';
+import { Component, OnInit, ViewChild } from '@angular/core';
import { Task, TaskService } from './../../core/core.module';
@Component({
@@ -7,6 +8,8 @@
styleUrls: ['./task-dashboard.component.scss']
})
export class TaskDashboardComponent implements OnInit {
+ @ViewChild(TaskListComponent) taskList: TaskListComponent;
+
tasks$;
constructor(private taskService: TaskService) { } |
eeef76eac5e60050c4086212a302b3fb26075a52 | test/basic/lib/externalLib.d.ts | test/basic/lib/externalLib.d.ts | declare module externalLib {
export function doSomething2(arg: any): void;
}
declare module 'externalLib' {
export = externalLib
} | declare module externalLib {
export function doSomething(arg: any): void;
}
declare module 'externalLib' {
export = externalLib
} | Fix typo in basic test | Fix typo in basic test
| TypeScript | mit | basarat/ts-loader,MortenHoustonLudvigsen/ts-loader,use-strict/ts-loader,bjfletcher/ts-loader,gsteacy/ts-loader,TypeStrong/ts-loader,thomasguillory/ts-loader,gsteacy/ts-loader,jbrantly/ts-loader,jbrantly/ts-loader,use-strict/ts-loader,jbrantly/ts-loader,TypeStrong/ts-loader,gsteacy/ts-loader,thomasguillory/ts-loader,MortenHoustonLudvigsen/ts-loader,bjfletcher/ts-loader,jaysoo/ts-loader,jaysoo/ts-loader,basarat/ts-loader,MortenHoustonLudvigsen/ts-loader | ---
+++
@@ -1,5 +1,5 @@
declare module externalLib {
- export function doSomething2(arg: any): void;
+ export function doSomething(arg: any): void;
}
declare module 'externalLib' { |
c4d6ae05fb74bcc5ac97837949ff82660c11baca | client/Components/Button.tsx | client/Components/Button.tsx | import * as React from "react";
export interface ButtonProps {
text?: string;
faClass?: string;
tooltip?: string;
additionalClassNames?: string;
disabled?: boolean;
onClick: React.MouseEventHandler<HTMLSpanElement>;
onMouseOver?: React.MouseEventHandler<HTMLSpanElement>;
}
export class Button extends React.Component<ButtonProps> {
public render() {
const text = this.props.text || "";
const disabled = this.props.disabled || false;
const classNames = [disabled ? "c-button--disabled" : "c-button"];
if (this.props.additionalClassNames) {
classNames.push(this.props.additionalClassNames);
}
const faElement = this.props.faClass && <span className={`fa fa-${this.props.faClass}`} />;
return <span
className={classNames.join(" ")}
onClick={!disabled && this.props.onClick}
onMouseOver={!disabled && this.props.onMouseOver}
title={this.props.tooltip}
>{faElement}{text}</span>;
}
} | import * as React from "react";
export interface ButtonProps {
text?: string;
faClass?: string;
tooltip?: string;
additionalClassNames?: string;
disabled?: boolean;
onClick: React.MouseEventHandler<HTMLSpanElement>;
onMouseOver?: React.MouseEventHandler<HTMLSpanElement>;
}
export class Button extends React.Component<ButtonProps> {
public render() {
const text = this.props.text || "";
const disabled = this.props.disabled || false;
const classNames = ["c-button"];
if (disabled) {
classNames.push("c-button--disabled");
}
if (this.props.additionalClassNames) {
classNames.push(this.props.additionalClassNames);
}
const faElement = this.props.faClass && <span className={`fa fa-${this.props.faClass}`} />;
return <span
className={classNames.join(" ")}
onClick={!disabled && this.props.onClick}
onMouseOver={!disabled && this.props.onMouseOver}
title={this.props.tooltip}
>{faElement}{text}</span>;
}
} | Use both class names on disabled button | Use both class names on disabled button
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -15,8 +15,12 @@
const text = this.props.text || "";
const disabled = this.props.disabled || false;
+
+ const classNames = ["c-button"];
- const classNames = [disabled ? "c-button--disabled" : "c-button"];
+ if (disabled) {
+ classNames.push("c-button--disabled");
+ }
if (this.props.additionalClassNames) {
classNames.push(this.props.additionalClassNames);
} |
2fd95b81720b8a46d0997d857dcf198d5dcfb14d | src/models/message.ts | src/models/message.ts | import mongoose from 'mongoose';
import Message from '@/interfaces/Message';
export interface IUserRessourceModel extends mongoose.Types.Subdocument {
name: string;
mail: string;
language: string;
payload: any;
};
export interface IMessageModel extends Message, mongoose.Document {
_receivers: mongoose.Types.DocumentArray<IUserRessourceModel>;
}
export const userRessourceSchema = new mongoose.Schema({
name: String,
mail: String,
language: String,
payload: Object,
});
export const messageSchema = new mongoose.Schema({
platform: String,
template: String,
sender: {
name: String,
mail: String,
},
payload: [
{
language: String,
payload: Object,
},
],
receivers: [ userRessourceSchema ],
trackLinks: Boolean,
});
const messageModel: mongoose.Model<IMessageModel> = mongoose.model('Message', messageSchema);
export default messageModel;
| import mongoose from 'mongoose';
import Message from '@/interfaces/Message';
export interface IUserRessourceModel extends mongoose.Types.Subdocument {
name: string;
mail: string;
language: string;
payload: any;
}
export interface IMessageModel extends Message, mongoose.Document {
_receivers: mongoose.Types.DocumentArray<IUserRessourceModel>;
}
export const userRessourceSchema = new mongoose.Schema({
name: String,
mail: String,
language: String,
payload: Object,
});
export const messageSchema = new mongoose.Schema({
platform: String,
template: String,
sender: {
name: String,
mail: String,
},
payload: [
{
language: String,
payload: Object,
},
],
receivers: [ userRessourceSchema ],
trackLinks: Boolean,
});
const messageModel: mongoose.Model<IMessageModel> = mongoose.model('Message', messageSchema);
export default messageModel;
| Undo unwanted change in MessageModel | Undo unwanted change in MessageModel | TypeScript | mit | schulcloud/node-notification-service,schulcloud/node-notification-service,schulcloud/node-notification-service | ---
+++
@@ -6,7 +6,7 @@
mail: string;
language: string;
payload: any;
-};
+}
export interface IMessageModel extends Message, mongoose.Document {
_receivers: mongoose.Types.DocumentArray<IUserRessourceModel>; |
3602601174fe34a3af6c0b6403afd4ac96be5129 | types/gzip-size/gzip-size-tests.ts | types/gzip-size/gzip-size-tests.ts | import * as fs from 'fs';
import * as gzipSize from 'gzip-size';
const string = 'Lorem ipsum dolor sit amet.';
console.log(string.length);
gzipSize(string).then(size => console.log(size));
console.log(gzipSize.sync(string));
const stream = fs.createReadStream("index.d.ts");
const gstream = stream.pipe(gzipSize.stream()).on("gzip-size", size => console.log(size));
console.log(gstream.gzipSize); // Could be a number or undefined. Recommended to use "gzip-size" event instead
gzipSize.file("index.d.ts").then(size => console.log(size));
| import fs = require('fs');
import gzipSize = require('gzip-size');
const string = 'Lorem ipsum dolor sit amet.';
console.log(string.length);
gzipSize(string).then(size => console.log(size));
console.log(gzipSize.sync(string));
const stream = fs.createReadStream("index.d.ts");
const gstream = stream.pipe(gzipSize.stream()).on("gzip-size", size => console.log(size));
console.log(gstream.gzipSize); // Could be a number or undefined. Recommended to use "gzip-size" event instead
gzipSize.file("index.d.ts").then(size => console.log(size));
| Revert usage of ES6 modules in gzip-size tests | Revert usage of ES6 modules in gzip-size tests
| TypeScript | mit | chrootsu/DefinitelyTyped,aciccarello/DefinitelyTyped,borisyankov/DefinitelyTyped,arusakov/DefinitelyTyped,aciccarello/DefinitelyTyped,AgentME/DefinitelyTyped,chrootsu/DefinitelyTyped,alexdresko/DefinitelyTyped,georgemarshall/DefinitelyTyped,zuzusik/DefinitelyTyped,rolandzwaga/DefinitelyTyped,zuzusik/DefinitelyTyped,AgentME/DefinitelyTyped,magny/DefinitelyTyped,markogresak/DefinitelyTyped,borisyankov/DefinitelyTyped,dsebastien/DefinitelyTyped,AgentME/DefinitelyTyped,arusakov/DefinitelyTyped,zuzusik/DefinitelyTyped,one-pieces/DefinitelyTyped,alexdresko/DefinitelyTyped,aciccarello/DefinitelyTyped,magny/DefinitelyTyped,rolandzwaga/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,mcliment/DefinitelyTyped,dsebastien/DefinitelyTyped,benliddicott/DefinitelyTyped,arusakov/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped | ---
+++
@@ -1,5 +1,5 @@
-import * as fs from 'fs';
-import * as gzipSize from 'gzip-size';
+import fs = require('fs');
+import gzipSize = require('gzip-size');
const string = 'Lorem ipsum dolor sit amet.';
|
77344c52bdf0e549ac0d11823ed4cf60e15f37ee | app/src/ui/lib/avatar.tsx | app/src/ui/lib/avatar.tsx | import * as React from 'react'
import { IGitHubUser } from '../../lib/dispatcher'
interface IAvatarProps {
readonly gitHubUser: IGitHubUser | null
readonly title: string | null
}
export class Avatar extends React.Component<IAvatarProps, void> {
public render() {
const DefaultAvatarURL = 'https://github.com/hubot.png'
const gitHubUser = this.props.gitHubUser
const avatarURL = (gitHubUser ? gitHubUser.avatarURL : null) || DefaultAvatarURL
const avatarTitle = this.props.title || undefined
return (
<div className='avatar' title={avatarTitle}>
<img src={avatarURL} alt={avatarTitle}/>
</div>
)
}
}
| import * as React from 'react'
import { IGitHubUser } from '../../lib/dispatcher'
interface IAvatarProps {
readonly gitHubUser: IGitHubUser | null
readonly title: string | null
}
const DefaultAvatarURL = 'https://github.com/hubot.png'
export class Avatar extends React.Component<IAvatarProps, void> {
private getTitle(user: IGitHubUser | null): string {
if (user === null) {
return this.props.title || 'Unkown User'
}
return this.props.title || user.email
}
public render() {
const gitHubUser = this.props.gitHubUser
const avatarURL = (gitHubUser ? gitHubUser.avatarURL : null) || DefaultAvatarURL
const avatarTitle = this.getTitle(gitHubUser)
return (
<div className='avatar' title={avatarTitle}>
<img src={avatarURL} alt={avatarTitle}/>
</div>
)
}
}
| Add function to ensure the component always has a valid title | Add function to ensure the component always has a valid title
| TypeScript | mit | artivilla/desktop,j-f1/forked-desktop,hjobrien/desktop,gengjiawen/desktop,j-f1/forked-desktop,kactus-io/kactus,artivilla/desktop,shiftkey/desktop,gengjiawen/desktop,gengjiawen/desktop,BugTesterTest/desktops,gengjiawen/desktop,j-f1/forked-desktop,artivilla/desktop,hjobrien/desktop,artivilla/desktop,say25/desktop,shiftkey/desktop,j-f1/forked-desktop,kactus-io/kactus,hjobrien/desktop,say25/desktop,BugTesterTest/desktops,desktop/desktop,desktop/desktop,desktop/desktop,hjobrien/desktop,shiftkey/desktop,shiftkey/desktop,BugTesterTest/desktops,say25/desktop,kactus-io/kactus,say25/desktop,kactus-io/kactus,desktop/desktop,BugTesterTest/desktops | ---
+++
@@ -6,12 +6,22 @@
readonly title: string | null
}
+const DefaultAvatarURL = 'https://github.com/hubot.png'
+
export class Avatar extends React.Component<IAvatarProps, void> {
+ private getTitle(user: IGitHubUser | null): string {
+ if (user === null) {
+ return this.props.title || 'Unkown User'
+ }
+
+ return this.props.title || user.email
+ }
+
public render() {
- const DefaultAvatarURL = 'https://github.com/hubot.png'
const gitHubUser = this.props.gitHubUser
const avatarURL = (gitHubUser ? gitHubUser.avatarURL : null) || DefaultAvatarURL
- const avatarTitle = this.props.title || undefined
+ const avatarTitle = this.getTitle(gitHubUser)
+
return (
<div className='avatar' title={avatarTitle}>
<img src={avatarURL} alt={avatarTitle}/> |
4e8588b59dc1d5a61fdf7076b3c9968f2826369f | site/main.ts | site/main.ts | declare function sscDingus(el: any);
document.addEventListener("DOMContentLoaded", function () {
var base = document.querySelector('.sscdingus');
sscDingus(base);
});
| declare function sscDingus(el: any, config: any);
document.addEventListener("DOMContentLoaded", function () {
var base = document.querySelector('.sscdingus');
sscDingus(base, {
history: false,
lineNumbers: false,
scrollbars: false,
});
});
| Use "stealth mode" options with dingus | Use "stealth mode" options with dingus
| TypeScript | mit | guoyiteng/braid,cucapra/braid,guoyiteng/braid,guoyiteng/braid,cucapra/braid,cucapra/braid,cucapra/braid,guoyiteng/braid,cucapra/braid,cucapra/braid,guoyiteng/braid,guoyiteng/braid | ---
+++
@@ -1,6 +1,10 @@
-declare function sscDingus(el: any);
+declare function sscDingus(el: any, config: any);
document.addEventListener("DOMContentLoaded", function () {
var base = document.querySelector('.sscdingus');
- sscDingus(base);
+ sscDingus(base, {
+ history: false,
+ lineNumbers: false,
+ scrollbars: false,
+ });
}); |
f98fd8d5858a05d88ff2c930d9a782feabb04f08 | kspRemoteTechPlanner/calculator/services/orbitalService.ts | kspRemoteTechPlanner/calculator/services/orbitalService.ts | /// <reference path="../calculatorreferences.ts" />
module Calculator {
export class OrbitalService {
'use strict';
period(sma: number, stdGravParam: number): number {
return 2 * Math.PI * Math.sqrt(Math.pow(sma, 3) / stdGravParam);
}
nightTime(radius: number, sma: number, stdGravParam: number): number {
return this.period(sma, stdGravParam) * Math.asin((radius / 2) / sma) / Math.PI;
}
hohmannStartDV(sma1: number, sma2: number, stdGravParam: number): number {
return Math.sqrt(stdGravParam / sma1) * (Math.sqrt((2 * sma2) / (sma1 + sma2)) - 1);
}
hohmannFinishDV(sma1: number, sma2: number, stdGravParam: number): number {
return Math.sqrt(stdGravParam / sma2) * (1 - Math.sqrt((2 * sma1) / (sma1 + sma2)));
}
slidePhaseAngle(slideDeg: number, periodLow: number, periodHigh: number): number {
return slideDeg / (1 - periodLow / periodHigh);
}
}
}
| /// <reference path="../calculatorreferences.ts" />
module Calculator {
export class OrbitalService {
'use strict';
period(sma: number, stdGravParam: number): number {
return 2 * Math.PI * Math.sqrt(Math.pow(sma, 3) / stdGravParam);
}
nightTime(radius: number, sma: number, stdGravParam: number): number {
return this.period(sma, stdGravParam) * Math.asin(radius / sma) / Math.PI;
}
hohmannStartDV(sma1: number, sma2: number, stdGravParam: number): number {
return Math.sqrt(stdGravParam / sma1) * (Math.sqrt((2 * sma2) / (sma1 + sma2)) - 1);
}
hohmannFinishDV(sma1: number, sma2: number, stdGravParam: number): number {
return Math.sqrt(stdGravParam / sma2) * (1 - Math.sqrt((2 * sma1) / (sma1 + sma2)));
}
slidePhaseAngle(slideDeg: number, periodLow: number, periodHigh: number): number {
return slideDeg / (1 - periodLow / periodHigh);
}
}
}
| Fix calculation of night time. | Fix calculation of night time.
| TypeScript | mit | ryohpops/kspRemoteTechPlanner,ryohpops/kspRemoteTechPlanner,ryohpops/kspRemoteTechPlanner | ---
+++
@@ -10,7 +10,7 @@
}
nightTime(radius: number, sma: number, stdGravParam: number): number {
- return this.period(sma, stdGravParam) * Math.asin((radius / 2) / sma) / Math.PI;
+ return this.period(sma, stdGravParam) * Math.asin(radius / sma) / Math.PI;
}
hohmannStartDV(sma1: number, sma2: number, stdGravParam: number): number { |
fd8b68457b51e7ad8fa0a3f2698e673c3de95bce | src/vs/workbench/electron-sandbox/loaderCyclicChecker.ts | src/vs/workbench/electron-sandbox/loaderCyclicChecker.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 nls from 'vs/nls';
import { IWorkbenchContribution } from 'vs/workbench/common/contributions';
import { Disposable } from 'vs/base/common/lifecycle';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { Severity } from 'vs/platform/notification/common/notification';
import { INativeHostService } from 'vs/platform/native/electron-sandbox/native';
export class LoaderCyclicChecker extends Disposable implements IWorkbenchContribution {
constructor(
@IDialogService dialogService: IDialogService,
@INativeHostService nativeHostService: INativeHostService,
) {
super();
if (require.hasDependencyCycle()) {
dialogService.show(Severity.Error, nls.localize('loaderCycle', "There is a dependency cycle in the AMD modules"), [nls.localize('ok', "OK")]);
nativeHostService.openDevTools();
}
}
}
| /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { IWorkbenchContribution } from 'vs/workbench/common/contributions';
import { Disposable } from 'vs/base/common/lifecycle';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { Severity } from 'vs/platform/notification/common/notification';
import { INativeHostService } from 'vs/platform/native/electron-sandbox/native';
export class LoaderCyclicChecker extends Disposable implements IWorkbenchContribution {
constructor(
@IDialogService dialogService: IDialogService,
@INativeHostService nativeHostService: INativeHostService,
) {
super();
if (require.hasDependencyCycle()) {
if (process.env.CI || process.env.BUILD_ARTIFACTSTAGINGDIRECTORY) {
// running on a build machine, just exit
console.log('There is a dependency cycle in the AMD modules');
nativeHostService.exit(37);
}
dialogService.show(Severity.Error, nls.localize('loaderCycle', "There is a dependency cycle in the AMD modules"), [nls.localize('ok', "OK")]);
nativeHostService.openDevTools();
}
}
}
| Exit immediately when a cycle is found and running on the build | Exit immediately when a cycle is found and running on the build
| TypeScript | mit | Krzysztof-Cieslak/vscode,microsoft/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,Microsoft/vscode,Microsoft/vscode,eamodio/vscode,Microsoft/vscode,eamodio/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,microsoft/vscode,Microsoft/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Microsoft/vscode,Microsoft/vscode,Microsoft/vscode,Microsoft/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,eamodio/vscode,Microsoft/vscode,eamodio/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,Microsoft/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,microsoft/vscode | ---
+++
@@ -19,6 +19,11 @@
super();
if (require.hasDependencyCycle()) {
+ if (process.env.CI || process.env.BUILD_ARTIFACTSTAGINGDIRECTORY) {
+ // running on a build machine, just exit
+ console.log('There is a dependency cycle in the AMD modules');
+ nativeHostService.exit(37);
+ }
dialogService.show(Severity.Error, nls.localize('loaderCycle', "There is a dependency cycle in the AMD modules"), [nls.localize('ok', "OK")]);
nativeHostService.openDevTools();
} |
e5013a5ef9b1a80f249a616ac77408fc39423381 | src/api/returnHit.ts | src/api/returnHit.ts | import axios from 'axios';
import { API_URL } from '../constants';
export type HitReturnStatus = 'repeat' | 'success' | 'error';
export const sendReturnHitRequest = async (hitId: string) => {
try {
const response = await axios.get(`${API_URL}/mturk/return`, {
params: {
hitId,
inPipeline: false
},
responseType: 'document'
});
const html: Document = response.data;
return validateHitReturn(html);
} catch (e) {
return 'error';
}
};
const validateHitReturn = (html: Document): HitReturnStatus => {
const noAssignedHitsContainer = html.querySelector('td.error_title');
if (!!noAssignedHitsContainer) {
return 'success';
}
const alertBox = html.querySelector('#alertboxHeader');
return !!alertBox ? validateAlertBoxText(alertBox) : 'error';
};
const validateAlertBoxText = (el: Element | undefined): HitReturnStatus => {
if (el === undefined) {
return 'error';
}
const text = (el as HTMLSpanElement).innerText.trim();
switch (text) {
case 'The HIT has been returned.':
return 'success';
case 'You have already returned this HIT.':
return 'repeat';
default:
return 'error';
}
};
| import axios from 'axios';
import { API_URL } from '../constants';
export type HitReturnStatus = 'repeat' | 'success' | 'error';
export const sendReturnHitRequest = async (hitId: string) => {
try {
const response = await axios.get(`${API_URL}/mturk/return`, {
params: {
hitId,
inPipeline: false
},
responseType: 'document'
});
const html: Document = response.data;
return validateHitReturn(html);
} catch (e) {
throw new Error('Unknown problem with returning Hit.')
}
};
const validateHitReturn = (html: Document): HitReturnStatus => {
const noAssignedHitsContainer = html.querySelector('td.error_title');
if (!!noAssignedHitsContainer) {
return 'success';
}
const alertBox = html.querySelector('#alertboxHeader');
return !!alertBox ? validateAlertBoxText(alertBox) : 'error';
};
const validateAlertBoxText = (el: Element | undefined): HitReturnStatus => {
if (el === undefined) {
return 'error';
}
const text = (el as HTMLSpanElement).innerText.trim();
switch (text) {
case 'The HIT has been returned.':
return 'success';
case 'You have already returned this HIT.':
return 'repeat';
default:
return 'error';
}
};
| Throw Error object instead of returning a string. | Throw Error object instead of returning a string.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -15,7 +15,7 @@
const html: Document = response.data;
return validateHitReturn(html);
} catch (e) {
- return 'error';
+ throw new Error('Unknown problem with returning Hit.')
}
};
|
45f867862871588f217d1fc856e2bd9949dbc255 | src/socket-io.module.ts | src/socket-io.module.ts | import { ModuleWithProviders } from '@angular/core';
import { SocketIoConfig } from './config/socket-io.config';
import { WrappedSocket } from './socket-io.service';
/** Socket factory */
export function SocketFactory(config: SocketIoConfig) {
return new WrappedSocket(config);
}
export const socketConfig: string = "__SOCKET_IO_CONFIG__";
export class SocketIoModule {
static forRoot(config: SocketIoConfig): ModuleWithProviders {
return {
ngModule: SocketIoModule,
providers: [
{ provide: socketConfig, useValue: config },
{
provide: WrappedSocket,
useFactory: SocketFactory,
deps : [socketConfig]
}
]
};
}
}
| import { NgModule, ModuleWithProviders } from '@angular/core';
import { SocketIoConfig } from './config/socket-io.config';
import { WrappedSocket } from './socket-io.service';
/** Socket factory */
export function SocketFactory(config: SocketIoConfig) {
return new WrappedSocket(config);
}
export const socketConfig: string = "__SOCKET_IO_CONFIG__";
@NgModule({})
export class SocketIoModule {
static forRoot(config: SocketIoConfig): ModuleWithProviders {
return {
ngModule: SocketIoModule,
providers: [
{ provide: socketConfig, useValue: config },
{
provide: WrappedSocket,
useFactory: SocketFactory,
deps : [socketConfig]
}
]
};
}
}
| Add missing import of ngModule | Add missing import of ngModule
| TypeScript | mit | rodgc/ngx-socket-io,rodgc/ngx-socket-io | ---
+++
@@ -1,4 +1,4 @@
-import { ModuleWithProviders } from '@angular/core';
+import { NgModule, ModuleWithProviders } from '@angular/core';
import { SocketIoConfig } from './config/socket-io.config';
import { WrappedSocket } from './socket-io.service';
@@ -9,6 +9,7 @@
export const socketConfig: string = "__SOCKET_IO_CONFIG__";
+@NgModule({})
export class SocketIoModule {
static forRoot(config: SocketIoConfig): ModuleWithProviders {
return { |
14390dfcaef558974cfd1b2fe717a9fd236db567 | src/Parsing/Outline/Patterns.ts | src/Parsing/Outline/Patterns.ts |
const group = (pattern: string) => `(?:${pattern})`
const optional = (pattern: string) => pattern + '?'
const all = (pattern: string) => pattern + '*'
const atLeast = (count: number, pattern: string) => pattern + `{${count},}`
const either = (...patterns: string[]) => group(patterns.join('|'))
const whitespace = '[^\\S\\n]'
const lineOf = (pattern: string) => `^` + pattern + all(whitespace) + '$'
const streakOf = (char: string) => lineOf(atLeast(3, char))
const dottedStreakOf = (char: string) => lineOf(optional(' ') + atLeast(2, group(char + ' ')) + char)
const BLANK_LINE = new RegExp(
lineOf('')
)
// We don't need to check for the start or end of the string, because if a line
// contains a non-whitespace character anywhere in it, it's not blank.
const NON_BLANK_LINE = /\S/
export {
NON_BLANK_LINE,
BLANK_LINE,
either,
lineOf,
streakOf,
dottedStreakOf
} |
const group = (pattern: string) => `(?:${pattern})`
const optional = (pattern: string) => group(pattern) + '?'
const all = (pattern: string) => group(pattern) + '*'
const atLeast = (count: number, pattern: string) => group(pattern) + `{${count},}`
const either = (...patterns: string[]) => group(patterns.join('|'))
const whitespace = '[^\\S\\n]'
const lineOf = (pattern: string) => `^` + pattern + all(whitespace) + '$'
const streakOf = (char: string) => lineOf(atLeast(3, char))
const dottedStreakOf = (char: string) => lineOf(optional(' ') + atLeast(2, char + ' ') + char)
const BLANK_LINE = new RegExp(
lineOf('')
)
// We don't need to check for the start or end of the string, because if a line
// contains a non-whitespace character anywhere in it, it's not blank.
const NON_BLANK_LINE = /\S/
export {
NON_BLANK_LINE,
BLANK_LINE,
either,
lineOf,
streakOf,
dottedStreakOf
} | Make public pattern helpers more robust | Make public pattern helpers more robust
| TypeScript | mit | start/up,start/up | ---
+++
@@ -1,11 +1,11 @@
const group = (pattern: string) => `(?:${pattern})`
-const optional = (pattern: string) => pattern + '?'
+const optional = (pattern: string) => group(pattern) + '?'
-const all = (pattern: string) => pattern + '*'
+const all = (pattern: string) => group(pattern) + '*'
-const atLeast = (count: number, pattern: string) => pattern + `{${count},}`
+const atLeast = (count: number, pattern: string) => group(pattern) + `{${count},}`
const either = (...patterns: string[]) => group(patterns.join('|'))
@@ -15,7 +15,7 @@
const streakOf = (char: string) => lineOf(atLeast(3, char))
-const dottedStreakOf = (char: string) => lineOf(optional(' ') + atLeast(2, group(char + ' ')) + char)
+const dottedStreakOf = (char: string) => lineOf(optional(' ') + atLeast(2, char + ' ') + char)
const BLANK_LINE = new RegExp(
lineOf('') |
ffc6edf6a6119b9a29ee9570b0fb22724c8a0ea7 | src/core/feature-flags.ts | src/core/feature-flags.ts | /* Copyright 2019 Google LLC. All Rights Reserved.
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.
==============================================================================*/
import queryString from 'query-string';
export class FeatureFlags {
readonly baseline: boolean = false;
constructor() {
const parsed = queryString.parse(window.location.search);
const { baseline } = parsed;
if (baseline === 'true') {
this.baseline = true;
}
}
}
export default new FeatureFlags();
| /* Copyright 2019 Google LLC. All Rights Reserved.
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.
==============================================================================*/
import queryString from 'query-string';
import { observable, computed } from 'mobx';
export type Variant = 'a' | 'b';
export class FeatureFlags {
@observable readonly variant: Variant = 'a';
@computed get baseline() {
return this.variant === 'b';
}
constructor() {
const parsed = queryString.parse(window.location.search);
const { variant } = parsed;
if (variant === 'b') {
this.variant = variant;
}
}
}
export default new FeatureFlags();
| Rename baseline query param to variant=b | Rename baseline query param to variant=b
| TypeScript | apache-2.0 | PAIR-code/cococo,PAIR-code/cococo,PAIR-code/cococo | ---
+++
@@ -14,15 +14,22 @@
==============================================================================*/
import queryString from 'query-string';
+import { observable, computed } from 'mobx';
+
+export type Variant = 'a' | 'b';
export class FeatureFlags {
- readonly baseline: boolean = false;
+ @observable readonly variant: Variant = 'a';
+
+ @computed get baseline() {
+ return this.variant === 'b';
+ }
constructor() {
const parsed = queryString.parse(window.location.search);
- const { baseline } = parsed;
- if (baseline === 'true') {
- this.baseline = true;
+ const { variant } = parsed;
+ if (variant === 'b') {
+ this.variant = variant;
}
}
} |
24589fc023eab759db4a8f6b4746482de1f04cf2 | src/environments/environment.ts | src/environments/environment.ts | // The file contents for the current environment will overwrite these during build.
// The build system defaults to the dev environment which uses `environment.ts`, but if you do
// `ng build --env=prod` then `environment.prod.ts` will be used instead.
// The list of which env maps to which file can be found in `.angular-cli.json`.
export const environment = {
production: false,
authCallbackURL: 'http://localhost:3000/auth/callback',
};
| // The file contents for the current environment will overwrite these during build.
// The build system defaults to the dev environment which uses `environment.ts`, but if you do
// `ng build --env=prod` then `environment.prod.ts` will be used instead.
// The list of which env maps to which file can be found in `.angular-cli.json`.
export const environment = {
production: false,
authCallbackURL: 'http://macbookpro:3000/auth/callback',
};
| Update Auth0 callback URL to support dev access from mobile | Update Auth0 callback URL to support dev access from mobile
| TypeScript | mit | lentz/buddyduel,lentz/buddyduel,lentz/buddyduel | ---
+++
@@ -5,5 +5,5 @@
export const environment = {
production: false,
- authCallbackURL: 'http://localhost:3000/auth/callback',
+ authCallbackURL: 'http://macbookpro:3000/auth/callback',
}; |
4540a63139e25a6694f5490fa95db5bb9a090857 | src/main/Apha/Projections/Projections.ts | src/main/Apha/Projections/Projections.ts |
import {TypedEventListener} from "../EventHandling/TypedEventListener";
import {ProjectionStorage} from "./Storage/ProjectionStorage";
import {Projection} from "./Projection";
export abstract class Projections<T extends Projection> extends TypedEventListener {
constructor(protected storage: ProjectionStorage<T>) {
super();
}
}
|
import {EventListener} from "../EventHandling/EventListener";
import {ProjectionStorage} from "./Storage/ProjectionStorage";
import {Projection} from "./Projection";
import {Event} from "../Message/Event";
export abstract class Projections<T extends Projection> implements EventListener {
constructor(protected storage: ProjectionStorage<T>) {}
public on: (event: Event) => void;
}
| Make projections just be an event listener. | Make projections just be an event listener.
| TypeScript | mit | martyn82/aphajs | ---
+++
@@ -1,10 +1,10 @@
-import {TypedEventListener} from "../EventHandling/TypedEventListener";
+import {EventListener} from "../EventHandling/EventListener";
import {ProjectionStorage} from "./Storage/ProjectionStorage";
import {Projection} from "./Projection";
+import {Event} from "../Message/Event";
-export abstract class Projections<T extends Projection> extends TypedEventListener {
- constructor(protected storage: ProjectionStorage<T>) {
- super();
- }
+export abstract class Projections<T extends Projection> implements EventListener {
+ constructor(protected storage: ProjectionStorage<T>) {}
+ public on: (event: Event) => void;
} |
1e96eafa0e129559e499316aa246a830d97caa00 | src/views/Game/touch_actions.ts | src/views/Game/touch_actions.ts | /*
* Copyright (C) 2012-2022 Online-Go.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
export function disableTouchAction() {
document.documentElement.classList.add("no-touch-action");
}
export function enableTouchAction() {
document.documentElement.classList.remove("no-touch-action");
}
| /*
* Copyright (C) 2012-2022 Online-Go.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
const gobanSelector = ".goban-container .Goban .Goban";
export function disableTouchAction(selector: string = gobanSelector) {
document.querySelector(selector).classList.add("no-touch-action");
}
export function enableTouchAction(selector: string = gobanSelector) {
document.querySelector(selector).classList.remove("no-touch-action");
}
| Disable touch-action only inside goban when pen is selected | Disable touch-action only inside goban when pen is selected
| TypeScript | agpl-3.0 | online-go/online-go.com,online-go/online-go.com,online-go/online-go.com,online-go/online-go.com,online-go/online-go.com | ---
+++
@@ -15,10 +15,12 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-export function disableTouchAction() {
- document.documentElement.classList.add("no-touch-action");
+const gobanSelector = ".goban-container .Goban .Goban";
+
+export function disableTouchAction(selector: string = gobanSelector) {
+ document.querySelector(selector).classList.add("no-touch-action");
}
-export function enableTouchAction() {
- document.documentElement.classList.remove("no-touch-action");
+export function enableTouchAction(selector: string = gobanSelector) {
+ document.querySelector(selector).classList.remove("no-touch-action");
} |
72cc0caca751097e8a975f5249d3d3b012e4f3f1 | packages/components/components/button/FileButton.tsx | packages/components/components/button/FileButton.tsx | import React, { ChangeEvent, ReactNode } from 'react';
import { classnames } from '../../helpers';
import Icon from '../icon/Icon';
import './FileButton.scss';
interface Props {
className?: string;
icon?: string;
disabled?: boolean;
onAddFiles: (files: File[]) => void;
children?: ReactNode;
}
const FileButton = ({ onAddFiles, icon = 'attach', disabled, className, children }: Props) => {
const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
const input = event.target;
if (input.files) {
onAddFiles([...input.files]);
input.value = '';
}
};
return (
<div className="file-button flex">
<label
role="button"
className={classnames([
'pm-button inline-flex flex-items-center',
icon && !children && 'pm-button--for-icon',
disabled && 'is-disabled',
className,
])}
>
<Icon name="attach" />
{children}
<input type="file" multiple onChange={handleChange} data-testid="composer-attachments-button" />
</label>
</div>
);
};
export default FileButton;
| import React, { ChangeEvent, KeyboardEvent, useRef, ReactNode } from 'react';
import { classnames } from '../../helpers';
import Icon from '../icon/Icon';
import './FileButton.scss';
interface Props {
className?: string;
icon?: string;
disabled?: boolean;
onAddFiles: (files: File[]) => void;
children?: ReactNode;
}
const FileButton = ({ onAddFiles, icon = 'attach', disabled, className, children }: Props) => {
const inputRef = useRef<HTMLInputElement>(null);
const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
const input = event.target;
if (input.files) {
onAddFiles([...input.files]);
input.value = '';
}
};
const handleKey = (event: KeyboardEvent) => {
if (event.key === 'Enter' || event.key === ' ') {
inputRef.current?.click();
}
};
return (
<div className="file-button flex">
<label
role="button"
tabIndex={0}
className={classnames([
'pm-button inline-flex relative flex-items-center',
icon && !children && 'pm-button--for-icon',
disabled && 'is-disabled',
className,
])}
onKeyDown={handleKey}
>
<Icon name="attach" />
{children}
<input
ref={inputRef}
type="file"
multiple
onChange={handleChange}
data-testid="composer-attachments-button"
/>
</label>
</div>
);
};
export default FileButton;
| Fix [MAILWEB-1210] add file focusable | Fix [MAILWEB-1210] add file focusable
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -1,4 +1,4 @@
-import React, { ChangeEvent, ReactNode } from 'react';
+import React, { ChangeEvent, KeyboardEvent, useRef, ReactNode } from 'react';
import { classnames } from '../../helpers';
import Icon from '../icon/Icon';
@@ -13,6 +13,7 @@
}
const FileButton = ({ onAddFiles, icon = 'attach', disabled, className, children }: Props) => {
+ const inputRef = useRef<HTMLInputElement>(null);
const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
const input = event.target;
if (input.files) {
@@ -20,21 +21,34 @@
input.value = '';
}
};
+ const handleKey = (event: KeyboardEvent) => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ inputRef.current?.click();
+ }
+ };
return (
<div className="file-button flex">
<label
role="button"
+ tabIndex={0}
className={classnames([
- 'pm-button inline-flex flex-items-center',
+ 'pm-button inline-flex relative flex-items-center',
icon && !children && 'pm-button--for-icon',
disabled && 'is-disabled',
className,
])}
+ onKeyDown={handleKey}
>
<Icon name="attach" />
{children}
- <input type="file" multiple onChange={handleChange} data-testid="composer-attachments-button" />
+ <input
+ ref={inputRef}
+ type="file"
+ multiple
+ onChange={handleChange}
+ data-testid="composer-attachments-button"
+ />
</label>
</div>
); |
f23f14d6fc4603a7329a99c8b3f5d22004dde110 | tsmonad.ts | tsmonad.ts | /// <reference path="either.ts" />
/// <reference path="maybe.ts" />
/// <reference path="writer.ts" />
// Node module declaration taken from node.d.ts
declare var module: {
exports: any;
require(id: string): any;
id: string;
filename: string;
loaded: boolean;
parent: any;
children: any[];
};
declare module 'tsmonad' {
export = TsMonad;
}
(function () {
'use strict';
if (typeof module !== undefined && module.exports) {
// it's node
module.exports = TsMonad;
} else {
// stick it on the global object
this.TsMonad = TsMonad;
}
}).call(this);
| /// <reference path="either.ts" />
/// <reference path="maybe.ts" />
/// <reference path="writer.ts" />
// Node module declaration taken from node.d.ts
declare var module: {
exports: any;
require(id: string): any;
id: string;
filename: string;
loaded: boolean;
parent: any;
children: any[];
};
declare module 'tsmonad' {
export = TsMonad;
}
(function () {
'use strict';
if (typeof module !== 'undefined' && module.exports) {
// it's node
module.exports = TsMonad;
} else {
// stick it on the global object
this.TsMonad = TsMonad;
}
}).call(this);
| Fix Uncaught ReferenceError: module is not defined | Fix Uncaught ReferenceError: module is not defined | TypeScript | mit | mwiencek/TsMonad,mwiencek/TsMonad,mwiencek/TsMonad,cbowdon/TsMonad,cbowdon/TsMonad | ---
+++
@@ -20,7 +20,7 @@
(function () {
'use strict';
- if (typeof module !== undefined && module.exports) {
+ if (typeof module !== 'undefined' && module.exports) {
// it's node
module.exports = TsMonad;
} else { |
7cc1b132f4ea20792edda965bbf00ca33bb88901 | frontend/src/stories/card/index.tsx | frontend/src/stories/card/index.tsx | import React from 'react';
import { storiesOf } from '@storybook/react';
import { Card } from '../../components/card';
storiesOf('Card', module).add('default', () => <Card>Hello world</Card>);
| import React from 'react';
import { storiesOf } from '@storybook/react';
import { Card } from '../../components/card';
import { Box } from 'components/box';
storiesOf('Card', module).add('default', () => (
<Box p={4}>
<Card>Hello world</Card>
</Box>
));
| Add some padding to card story | Add some padding to card story
| TypeScript | mit | patrick91/pycon,patrick91/pycon | ---
+++
@@ -2,5 +2,10 @@
import { storiesOf } from '@storybook/react';
import { Card } from '../../components/card';
+import { Box } from 'components/box';
-storiesOf('Card', module).add('default', () => <Card>Hello world</Card>);
+storiesOf('Card', module).add('default', () => (
+ <Box p={4}>
+ <Card>Hello world</Card>
+ </Box>
+)); |
a0f274a0d94172de81915892df127390fb344bbd | lib/resources/tasks/process-less.ts | lib/resources/tasks/process-less.ts | import * as gulp from 'gulp';
import * as changedInPlace from 'gulp-changed-in-place';
import * as sourcemaps from 'gulp-sourcemaps';
import * as less from 'gulp-less';
import * as plumber from 'gulp-plumber';
import * as notify from 'gulp-notify';
import * as project from '../aurelia.json';
import {build} from 'aurelia-cli';
export default function processCSS() {
return gulp.src(project.cssProcessor.source)
.pipe(changedInPlace({firstPass:true}))
.pipe(plumber({ errorHandler: notify.onError('Error: <%= error.message %>') }))
.pipe(sourcemaps.init())
.pipe(less())
.pipe(build.bundle());
};
| import * as gulp from 'gulp';
import * as changedInPlace from 'gulp-changed-in-place';
import * as sourcemaps from 'gulp-sourcemaps';
import * as less from 'gulp-less';
import * as plumber from 'gulp-plumber';
import * as notify from 'gulp-notify';
import * as project from '../aurelia.json';
import {build} from 'aurelia-cli';
export default function processCSS() {
return gulp.src(project.cssProcessor.source)
.pipe(changedInPlace({firstPass:true}))
.pipe(plumber({ errorHandler: notify.onError('Error: <%= error.message %>') }))
.pipe(sourcemaps.init())
.pipe(less())
.pipe(build.bundle());
}
| Remove unneeded semicolon after function. | Remove unneeded semicolon after function.
| TypeScript | mit | DrSammyD/cli,ghidello/cli,ghidello/cli,aurelia/cli,DrSammyD/cli,ghidello/cli,zewa666/cli,zewa666/cli,DrSammyD/cli,aurelia/cli,zewa666/cli,zewa666/cli | ---
+++
@@ -14,4 +14,4 @@
.pipe(sourcemaps.init())
.pipe(less())
.pipe(build.bundle());
-};
+} |
e7ab9e66ebdcd27625f2d2a3f6b236a85de8ecc0 | src/transformers/index.ts | src/transformers/index.ts | import { Transformer } from './types';
import { transform as transformInternal, SourceFile } from 'typescript';
export { TypeInjectorTransformer } from './TypeInjectorTransformer';
export { FunctionBlockTransformer } from './FunctionBlockTransformer';
export { MethodChainTransformer } from './MethodChainTransformer';
export { AnonymousFunctionTransformer } from './AnonymousFunctionTransformer';
export const transform = (sourceFile: SourceFile, transformers: Transformer[]) =>
transformInternal(sourceFile, transformers.map(t => t.getTransformer())).transformed.shift();
| import { Transformer } from './types';
import { transform as transformInternal, SourceFile } from 'typescript';
export { TypeInjectorTransformer } from './TypeInjectorTransformer';
export { FunctionBlockTransformer } from './FunctionBlockTransformer';
export { AnonymousFunctionTransformer } from './AnonymousFunctionTransformer';
export const transform = (sourceFile: SourceFile, transformers: Transformer[]) =>
transformInternal(sourceFile, transformers.map(t => t.getTransformer())).transformed.shift();
| Stop exporting method chain transformer | Stop exporting method chain transformer
| TypeScript | mit | AmnisIO/typewriter,AmnisIO/typewriter,AmnisIO/typewriter | ---
+++
@@ -2,7 +2,6 @@
import { transform as transformInternal, SourceFile } from 'typescript';
export { TypeInjectorTransformer } from './TypeInjectorTransformer';
export { FunctionBlockTransformer } from './FunctionBlockTransformer';
-export { MethodChainTransformer } from './MethodChainTransformer';
export { AnonymousFunctionTransformer } from './AnonymousFunctionTransformer';
export const transform = (sourceFile: SourceFile, transformers: Transformer[]) => |
040880e188067e29989985d9c113f9fe2c1ae10c | app/src/app/users/add-project-user/add-project-user.component.ts | app/src/app/users/add-project-user/add-project-user.component.ts | import { Component, OnInit, Input } from '@angular/core';
import { ProjectUser } from './../model';
import { ProjectUsersService } from './../services/project-users.service';
@Component({
selector: 'add-project-user',
templateUrl: 'add-project-user.component.html',
styleUrls: ['add-project-user.component.css']
})
export class AddProjectUserComponent implements OnInit {
@Input()
private projectId: string;
get roles(): string[] {
return ['owner', 'editor', 'viewer'];
}
private email: string;
private selectedRole: string = '';
private modalOpen: boolean;
private errors: string[];
private loading: boolean;
constructor(private service: ProjectUsersService) { }
ngOnInit() { }
openModal() {
this.modalOpen = true;
}
closeModal() {
this.modalOpen = false;
this.reset();
}
reset() {
this.email = '';
}
valid(): boolean {
return false;
}
submit() {
this.loading = true;
let user: ProjectUser = { email: this.email, project_id: this.projectId, role: this.selectedRole }
this.service.createProjectUser(user)
.subscribe(
res => console.log(res),
err => this.errors = err,
() => this.loading = false,
)
}
} | import { Component, OnInit, Input } from '@angular/core';
import { ProjectUser } from './../model';
import { ProjectUsersService } from './../services/project-users.service';
@Component({
selector: 'add-project-user',
templateUrl: 'add-project-user.component.html',
styleUrls: ['add-project-user.component.css']
})
export class AddProjectUserComponent implements OnInit {
@Input()
private projectId: string;
get roles(): string[] {
return ['owner', 'editor', 'viewer'];
}
private email: string = '';
private selectedRole: string = '';
private modalOpen: boolean = false;
private loading: boolean = false;
private errors: string[];
constructor(private service: ProjectUsersService) { }
ngOnInit() { }
openModal() {
this.modalOpen = true;
}
closeModal() {
this.modalOpen = false;
this.reset();
}
reset() {
this.email = '';
this.selectedRole = '';
}
valid(): boolean {
return false;
}
submit() {
this.loading = true;
let user: ProjectUser = { email: this.email, project_id: this.projectId, role: this.selectedRole }
this.service.createProjectUser(user)
.subscribe(
res => console.log(res),
err => this.errors = err,
() => this.loading = false,
)
}
} | Add selected role to reset method | Add selected role to reset method
| TypeScript | mit | anthonynsimon/parrot,anthonynsimon/parrot,todes1/parrot,anthonynsimon/parrot,todes1/parrot,anthonynsimon/parrot,anthonynsimon/parrot,todes1/parrot,anthonynsimon/parrot,todes1/parrot,todes1/parrot,todes1/parrot | ---
+++
@@ -16,11 +16,11 @@
return ['owner', 'editor', 'viewer'];
}
- private email: string;
+ private email: string = '';
private selectedRole: string = '';
- private modalOpen: boolean;
+ private modalOpen: boolean = false;
+ private loading: boolean = false;
private errors: string[];
- private loading: boolean;
constructor(private service: ProjectUsersService) { }
@@ -37,6 +37,7 @@
reset() {
this.email = '';
+ this.selectedRole = '';
}
valid(): boolean { |
18d81ee2d316c6d59f2d8d257debfd2f521c2025 | src/accumulate-command-stack.ts | src/accumulate-command-stack.ts | import { UsageError } from './usage-error';
import { Command } from './types';
import { LEAF, BRANCH } from './constants';
export function accumulateCommandStack(
commandStack: Command[],
maybeCommandNames: string[],
) {
for (const maybeCommandName of maybeCommandNames) {
if (maybeCommandName === 'help') {
throw new UsageError();
}
const command = commandStack.slice(-1)[0];
// ^^ Last item in the "commandStack" array
switch (command.commandType) {
case BRANCH:
const nextCommand = command.subcommands.find(
subcommand => subcommand.commandName === maybeCommandName,
);
if (!nextCommand) {
throw new UsageError(`Bad command "${maybeCommandName}"`);
}
commandStack.push(nextCommand);
break;
case LEAF:
// This means we're still processing "command name" args, but
// there's already a "leaf" command at the end of the stack.
throw new UsageError(
`Command "${command.commandName}" does not have subcommands`,
);
}
}
}
| import { UsageError } from './usage-error';
import { Command } from './types';
import { LEAF, BRANCH } from './constants';
export function accumulateCommandStack(
commandStack: Command[],
maybeCommandNames: string[],
) {
for (const maybeCommandName of maybeCommandNames) {
const command = commandStack.slice(-1)[0];
// ^^ Last item in the "commandStack" array
switch (command.commandType) {
case BRANCH:
const nextCommand = command.subcommands.find(
subcommand => subcommand.commandName === maybeCommandName,
);
if (!nextCommand) {
throw new UsageError(`Bad command "${maybeCommandName}"`);
}
commandStack.push(nextCommand);
break;
case LEAF:
// This means we're still processing "command name" args, but
// there's already a "leaf" command at the end of the stack.
throw new UsageError(
`Command "${command.commandName}" does not have subcommands`,
);
}
}
}
| Remove extraneous block from accumulateCommandStack | Remove extraneous block from accumulateCommandStack
| TypeScript | mit | carnesen/cli,carnesen/cli,carnesen/cli | ---
+++
@@ -7,9 +7,6 @@
maybeCommandNames: string[],
) {
for (const maybeCommandName of maybeCommandNames) {
- if (maybeCommandName === 'help') {
- throw new UsageError();
- }
const command = commandStack.slice(-1)[0];
// ^^ Last item in the "commandStack" array
switch (command.commandType) { |
5310bffd493cda4fb6d911c2ab05152f4a2f9f21 | src/components/Footer/index.tsx | src/components/Footer/index.tsx | import styled from "@emotion/styled"
import * as React from "react"
import { contentWidthColumn, headerWidth, mq } from "../../utils/styles"
import { Link } from "../Link"
interface FooterProps {
fullname: string | null
pronouns: string | null
}
const year = new Date().getFullYear()
const _Footer = styled.footer({
...contentWidthColumn,
alignSelf: "flex-end",
fontSize: "0.75rem",
margin: "1rem auto",
[mq.lg]: { marginLeft: headerWidth },
[mq.xl]: { marginLeft: 0 },
})
const Footer: React.FunctionComponent<FooterProps> = ({
fullname,
pronouns,
}) => (
<_Footer>
<div>
Copyright © {year} <Link href="/">{fullname}</Link> ({pronouns}).{" "}
<Link
href="https://creativecommons.org/licenses/by-sa/4.0/"
rel="license"
>
Some Rights Reserved
</Link>
.{" "}
<Link href="https://github.com/jbhannah/jbhannah.net">
Source on GitHub
</Link>
.
</div>
</_Footer>
)
export default Footer
| import styled from "@emotion/styled"
import * as React from "react"
import { contentWidthColumn, headerWidth, mq } from "../../utils/styles"
import { Link } from "../Link"
interface FooterProps {
fullname: string | null
pronouns: string | null
}
const year = new Date().getFullYear()
const _Footer = styled.footer({
...contentWidthColumn,
alignSelf: "flex-end",
fontSize: "0.75rem",
margin: "1rem auto",
[mq.lg]: { marginLeft: headerWidth },
[mq.xl]: { marginLeft: 0 },
})
const Footer: React.FunctionComponent<FooterProps> = ({
fullname,
pronouns,
}) => (
<_Footer>
<div>
Copyright © {year} <Link href="/">{fullname}</Link> ({pronouns}).{" "}
<Link
href="https://creativecommons.org/licenses/by-sa/4.0/"
rel="license"
>
Some Rights Reserved
</Link>
. Emoji by <Link href="https://twemoji.twitter.com/">Twemoji</Link>.
<Link href="https://github.com/jbhannah/jbhannah.net">
Source on GitHub
</Link>
.
</div>
</_Footer>
)
export default Footer
| Add Twemoji credit to footer | Add Twemoji credit to footer
| TypeScript | mit | jbhannah/jbhannah.net,jbhannah/jbhannah.net | ---
+++
@@ -32,7 +32,7 @@
>
Some Rights Reserved
</Link>
- .{" "}
+ . Emoji by <Link href="https://twemoji.twitter.com/">Twemoji</Link>.
<Link href="https://github.com/jbhannah/jbhannah.net">
Source on GitHub
</Link> |
d4fe745563ed84eaa7f1f0b1bcf02d7f0862fb3d | packages/web-client/app/components/card-pay/deposit-workflow/transaction-status/index.ts | packages/web-client/app/components/card-pay/deposit-workflow/transaction-status/index.ts | import Component from '@glimmer/component';
class CardPayDepositWorkflowTransactionStatusComponent extends Component {}
export default CardPayDepositWorkflowTransactionStatusComponent;
| /* eslint-disable ember/no-empty-glimmer-component-classes */
import Component from '@glimmer/component';
class CardPayDepositWorkflowTransactionStatusComponent extends Component {}
export default CardPayDepositWorkflowTransactionStatusComponent;
| Disable lint error - temporary | Disable lint error - temporary
| TypeScript | mit | cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack | ---
+++
@@ -1,3 +1,4 @@
+/* eslint-disable ember/no-empty-glimmer-component-classes */
import Component from '@glimmer/component';
class CardPayDepositWorkflowTransactionStatusComponent extends Component {} |
b91f3d9cf03156b6559a233b9795235f5cae1a73 | src/environments/environment.prod.ts | src/environments/environment.prod.ts | export const environment = {
production: true,
authCallbackURL: 'http://www.buddyduel.net/auth/callback',
authSilentUri: 'http://www.buddyduel.net/silent',
};
| export const environment = {
production: true,
authCallbackURL: 'https://www.buddyduel.net/auth/callback',
authSilentUri: 'https://www.buddyduel.net/silent',
};
| Switch auth callback URLs to HTTPS | Switch auth callback URLs to HTTPS
| TypeScript | mit | lentz/buddyduel,lentz/buddyduel,lentz/buddyduel | ---
+++
@@ -1,5 +1,5 @@
export const environment = {
production: true,
- authCallbackURL: 'http://www.buddyduel.net/auth/callback',
- authSilentUri: 'http://www.buddyduel.net/silent',
+ authCallbackURL: 'https://www.buddyduel.net/auth/callback',
+ authSilentUri: 'https://www.buddyduel.net/silent',
}; |
a483e6a2f5425033bd76cc648bd0132665e88ced | src/environments/environment.stag.ts | src/environments/environment.stag.ts | export const environment = {
production: false,
shibbolethSessionUrl: 'https://research-hub.cer.auckland.ac.nz:8443/Shibboleth.sso/Session.json',
apiUrl: 'https://research-hub.cer.auckland.ac.nz:8443/api/',
analyticsCode: 'UA-77710107-3'
};
| export const environment = {
production: true,
shibbolethSessionUrl: 'https://research-hub.cer.auckland.ac.nz:8443/Shibboleth.sso/Session.json',
apiUrl: 'https://research-hub.cer.auckland.ac.nz:8443/api/',
analyticsCode: 'UA-77710107-3'
};
| Set production variable to true | Set production variable to true
| TypeScript | bsd-3-clause | UoA-eResearch/research-hub,UoA-eResearch/research-hub,UoA-eResearch/research-hub | ---
+++
@@ -1,5 +1,5 @@
export const environment = {
- production: false,
+ production: true,
shibbolethSessionUrl: 'https://research-hub.cer.auckland.ac.nz:8443/Shibboleth.sso/Session.json',
apiUrl: 'https://research-hub.cer.auckland.ac.nz:8443/api/',
analyticsCode: 'UA-77710107-3' |
5748f762e93468ebebd84ede9e551eea8062179c | src/app/app.api-http.ts | src/app/app.api-http.ts | import { Injectable } from '@angular/core';
import {
HttpHeaderResponse,
HttpResponseBase,
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
} from '@angular/common/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { ApiResponse } from './shared/models';
@Injectable()
export class ApiInterceptor implements HttpInterceptor {
private JWT_KEY = 'taskboard.jwt';
constructor(private router: Router) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const headers = {
'Content-Type': 'application/json'
};
const token = sessionStorage.getItem(this.JWT_KEY);
if (token !== null) {
// tslint:disable-next-line
headers['Authorization'] = token;
}
request = request.clone({
setHeaders: headers
});
return next.handle(request).pipe(
tap(evt => {
if (evt instanceof HttpHeaderResponse ||
!(evt instanceof HttpResponseBase)) {
return;
}
const response: ApiResponse = evt.body;
if (response.data) {
sessionStorage.setItem(this.JWT_KEY, response.data[0]);
}
}, error => {
if ((error.status === 401 || error.status === 400)) {
sessionStorage.removeItem(this.JWT_KEY);
this.router.navigate(['/']);
}
})
);
}
}
| import { Injectable } from '@angular/core';
import {
HttpHeaderResponse,
HttpResponseBase,
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
} from '@angular/common/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { ApiResponse } from './shared/models';
@Injectable()
export class ApiInterceptor implements HttpInterceptor {
private JWT_KEY = 'taskboard.jwt';
constructor(private router: Router) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const headers = (request.body instanceof FormData)
? { }
: { 'Content-Type': 'application/json' };
const token = sessionStorage.getItem(this.JWT_KEY);
if (token !== null) {
// tslint:disable-next-line
headers['Authorization'] = token;
}
request = request.clone({
setHeaders: headers
});
return next.handle(request).pipe(
tap(evt => {
if (evt instanceof HttpHeaderResponse ||
!(evt instanceof HttpResponseBase)) {
return;
}
const response: ApiResponse = evt.body;
if (response.data) {
sessionStorage.setItem(this.JWT_KEY, response.data[0]);
}
}, error => {
if ((error.status === 401 || error.status === 400)) {
sessionStorage.removeItem(this.JWT_KEY);
this.router.navigate(['/']);
}
})
);
}
}
| Allow form data through without JSON header | Allow form data through without JSON header
| TypeScript | mit | kiswa/TaskBoard,kiswa/TaskBoard,kiswa/TaskBoard,kiswa/TaskBoard,kiswa/TaskBoard | ---
+++
@@ -21,9 +21,9 @@
constructor(private router: Router) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
- const headers = {
- 'Content-Type': 'application/json'
- };
+ const headers = (request.body instanceof FormData)
+ ? { }
+ : { 'Content-Type': 'application/json' };
const token = sessionStorage.getItem(this.JWT_KEY);
if (token !== null) { |
2f4738b78115452f5e141834add6078c883eb0f8 | src/app.component.ts | src/app.component.ts | import {Component} from 'angular2/core';
import {Http, Headers} from 'angular2/http';
@Component({
selector: 'playlistr',
template: `
<h1>Playlistr</h1>
<ul>
<li *ngFor="#release of releases" >
{{release.basic_information.title}}
-
<strong>{{release.basic_information.artists[0].name}}</strong>
</li>
</ul>
<p>© Playlistr</p>
`,
})
export class AppComponent {
result: Object;
releases: Array;
constructor(http: Http) {
this.result = {};
http
.get(
'https://api.discogs.com/users/imjacobclark/collection/folders/0/releases'
)
.subscribe(
data => this.result = JSON.parse(data.text()),
err => this.logError(err.text()),
() => this.filterSingles(this.result)
);
}
filterSingles(records){
this.releases = records.releases.filter(
record => record.basic_information.formats[0].descriptions.some(
description => description === 'Single' || description === '7"'
)
)
}
}
| import {Component} from 'angular2/core';
import {Http, Headers} from 'angular2/http';
@Component({
selector: 'playlistr',
template: `
<h1>Playlistr</h1>
<ul>
<li *ngFor="#release of releases" >
{{release.basic_information.title}}
-
<strong>{{release.basic_information.artists[0].name}}</strong>
</li>
</ul>
<p>© Playlistr</p>
`,
})
export class AppComponent {
result: Object;
releases: Array<Object>;
constructor(http: Http) {
this.result = {};
http
.get(
'https://api.discogs.com/users/imjacobclark/collection/folders/0/releases'
)
.subscribe(
data => this.result = JSON.parse(data.text()),
err => console.log(err),
() => this.filterSingles(this.result)
);
}
filterSingles(records){
this.releases = records.releases.filter(
record => record.basic_information.formats[0].descriptions.some(
description => description === 'Single' || description === '7"'
)
)
}
}
| Add type information to array | Add type information to array
| TypeScript | mit | imjacobclark/playlistr,imjacobclark/playlistr,imjacobclark/playlistr | ---
+++
@@ -17,7 +17,7 @@
})
export class AppComponent {
result: Object;
- releases: Array;
+ releases: Array<Object>;
constructor(http: Http) {
this.result = {};
@@ -27,7 +27,7 @@
)
.subscribe(
data => this.result = JSON.parse(data.text()),
- err => this.logError(err.text()),
+ err => console.log(err),
() => this.filterSingles(this.result)
);
} |
832fdaec3af4b3ce30c6bb1167be6ae7ff12586f | infoview/goal.tsx | infoview/goal.tsx | import * as React from 'react';
import { colorizeMessage, escapeHtml } from './util';
import { ConfigContext } from './index';
interface GoalProps {
goalState: string;
}
export function Goal(props: GoalProps): JSX.Element {
const config = React.useContext(ConfigContext);
if (!props.goalState) { return null; }
const reFilters = config.infoViewTacticStateFilters || [];
const filterIndex = config.filterIndex ?? -1;
let goalString = props.goalState.replace(/^(no goals)/mg, 'goals accomplished')
goalString = RegExp('^\\d+ goals|goals accomplished', 'mg').test(goalString) ? goalString : '1 goal\n'.concat(goalString);
if (!(reFilters.length === 0 || filterIndex === -1)) {
// this regex splits the goal state into (possibly multi-line) hypothesis and goal blocks
// by keeping indented lines with the most recent non-indented line
goalString = goalString.match(/(^(?! ).*\n?( .*\n?)*)/mg).map((line) => line.trim())
.filter((line) => {
const filt = reFilters[filterIndex];
const test = (new RegExp(filt.regex, filt.flags)).exec(line) !== null;
return filt.match ? test : !test;
}).join('\n');
}
goalString = colorizeMessage(escapeHtml(goalString));
return <pre className="font-code ml3" style={{whiteSpace: 'pre-wrap'}} dangerouslySetInnerHTML={{ __html: goalString }} />
}
| import * as React from 'react';
import { colorizeMessage, escapeHtml } from './util';
import { ConfigContext } from './index';
interface GoalProps {
goalState: string;
}
export function Goal(props: GoalProps): JSX.Element {
const config = React.useContext(ConfigContext);
if (!props.goalState) { return null; }
const reFilters = config.infoViewTacticStateFilters || [];
const filterIndex = config.filterIndex ?? -1;
let goalString = props.goalState.replace(/^(no goals)/mg, 'goals accomplished')
goalString = RegExp('^\\d+ goals|goals accomplished', 'mg').test(goalString) ? goalString : '1 goal\n'.concat(goalString);
if (!(reFilters.length === 0 || filterIndex === -1)) {
// this regex splits the goal state into (possibly multi-line) hypothesis and goal blocks
// by keeping indented lines with the most recent non-indented line
goalString = goalString.match(/(^(?! ).*\n?( .*\n?)*)/mg).map((line) => line.trim())
.filter((line) => {
const filt = reFilters[filterIndex];
const test = (new RegExp(filt.regex, filt.flags)).exec(line) !== null;
return filt.match ? test : !test;
}).join('\n');
}
goalString = colorizeMessage(escapeHtml(goalString));
return <pre className="font-code" style={{whiteSpace: 'pre-wrap'}} dangerouslySetInnerHTML={{ __html: goalString }} />
}
| Remove indentation from old-school tactic states. | Remove indentation from old-school tactic states.
| TypeScript | apache-2.0 | leanprover/vscode-lean,leanprover/vscode-lean,leanprover/vscode-lean | ---
+++
@@ -24,5 +24,5 @@
}).join('\n');
}
goalString = colorizeMessage(escapeHtml(goalString));
- return <pre className="font-code ml3" style={{whiteSpace: 'pre-wrap'}} dangerouslySetInnerHTML={{ __html: goalString }} />
+ return <pre className="font-code" style={{whiteSpace: 'pre-wrap'}} dangerouslySetInnerHTML={{ __html: goalString }} />
} |
a19b05f8139754069fdd2bf0387b6111f92905ac | src/utils/RenderDebouncer.ts | src/utils/RenderDebouncer.ts | import { ITerminal, IDisposable } from '../Interfaces';
/**
* Debounces calls to render terminal rows using animation frames.
*/
export class RenderDebouncer implements IDisposable {
private _rowStart: number;
private _rowEnd: number;
private _animationFrame: number = null;
constructor(
private _terminal: ITerminal,
private _callback: (start: number, end: number) => void
) {
}
public dispose(): void {
if (this._animationFrame) {
window.cancelAnimationFrame(this._animationFrame);
this._animationFrame = null;
}
}
public refresh(rowStart?: number, rowEnd?: number): void {
rowStart = rowStart || 0;
rowEnd = rowEnd || this._terminal.rows - 1;
this._rowStart = this._rowStart ? Math.min(this._rowStart, rowStart) : rowStart;
this._rowEnd = this._rowEnd ? Math.max(this._rowEnd, rowEnd) : rowEnd;
if (this._animationFrame) {
return;
}
this._animationFrame = window.requestAnimationFrame(() => this._innerRefresh());
}
private _innerRefresh(): void {
// Clamp values
this._rowStart = Math.max(this._rowStart, 0);
this._rowEnd = Math.min(this._rowEnd, this._terminal.rows - 1);
// Run render callback
this._callback(this._rowStart, this._rowEnd);
// Reset debouncer
this._rowStart = null;
this._rowEnd = null;
this._animationFrame = null;
}
}
| import { ITerminal, IDisposable } from '../Interfaces';
/**
* Debounces calls to render terminal rows using animation frames.
*/
export class RenderDebouncer implements IDisposable {
private _rowStart: number;
private _rowEnd: number;
private _animationFrame: number = null;
constructor(
private _terminal: ITerminal,
private _callback: (start: number, end: number) => void
) {
}
public dispose(): void {
if (this._animationFrame) {
window.cancelAnimationFrame(this._animationFrame);
this._animationFrame = null;
}
}
public refresh(rowStart?: number, rowEnd?: number): void {
rowStart = rowStart || 0;
rowEnd = rowEnd || this._terminal.rows - 1;
this._rowStart = this._rowStart !== null ? Math.min(this._rowStart, rowStart) : rowStart;
this._rowEnd = this._rowEnd !== null ? Math.max(this._rowEnd, rowEnd) : rowEnd;
if (this._animationFrame) {
return;
}
this._animationFrame = window.requestAnimationFrame(() => this._innerRefresh());
}
private _innerRefresh(): void {
// Clamp values
this._rowStart = Math.max(this._rowStart, 0);
this._rowEnd = Math.min(this._rowEnd, this._terminal.rows - 1);
// Run render callback
this._callback(this._rowStart, this._rowEnd);
// Reset debouncer
this._rowStart = null;
this._rowEnd = null;
this._animationFrame = null;
}
}
| Fix bad type check that caused rows to not refresh | Fix bad type check that caused rows to not refresh
| TypeScript | mit | xtermjs/xterm.js,akalipetis/xterm.js,sourcelair/xterm.js,Tyriar/xterm.js,akalipetis/xterm.js,sourcelair/xterm.js,sourcelair/xterm.js,xtermjs/xterm.js,xtermjs/xterm.js,sourcelair/xterm.js,xtermjs/xterm.js,akalipetis/xterm.js,Tyriar/xterm.js,Tyriar/xterm.js,Tyriar/xterm.js,Tyriar/xterm.js,akalipetis/xterm.js,xtermjs/xterm.js | ---
+++
@@ -24,8 +24,8 @@
public refresh(rowStart?: number, rowEnd?: number): void {
rowStart = rowStart || 0;
rowEnd = rowEnd || this._terminal.rows - 1;
- this._rowStart = this._rowStart ? Math.min(this._rowStart, rowStart) : rowStart;
- this._rowEnd = this._rowEnd ? Math.max(this._rowEnd, rowEnd) : rowEnd;
+ this._rowStart = this._rowStart !== null ? Math.min(this._rowStart, rowStart) : rowStart;
+ this._rowEnd = this._rowEnd !== null ? Math.max(this._rowEnd, rowEnd) : rowEnd;
if (this._animationFrame) {
return; |
1d19cc638caae9b22f3c19c419984e9dd6125a8f | src/client/app/components/TooltipHelpComponentAlternative.tsx | src/client/app/components/TooltipHelpComponentAlternative.tsx | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import * as React from 'react';
import { FormattedMessage } from 'react-intl';
import ReactTooltip from 'react-tooltip';
import helpLinks from '../translations/helpLinks';
interface TooltipHelpProps {
tipId: string;
}
/**
* Component that renders a help icon that shows a tooltip on hover
*/
export default function TooltipHelpComponentAlternative(props: TooltipHelpProps) {
const divStyle = {
display: 'inline-block'
};
// Create links
const values = helpLinks[props.tipId];
const links: Record<string, JSX.Element> = {};
Object.keys(values).forEach(key => {
const link = values[key];
links[key] = (<a target='_blank' href={link}>
{link}
</a>);
});
return (
<div style={divStyle}>
<i data-for={`${props.tipId}`} data-tip className='fa fa-question-circle' />
<ReactTooltip id={`${props.tipId}`} event='click' clickable effect='solid'>
<div style={{ width: '300px' }}>
<FormattedMessage
id={props.tipId}
values={links}
/>
</div>
</ReactTooltip>
</div>
);
}
| /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import * as React from 'react';
import { FormattedMessage } from 'react-intl';
import ReactTooltip from 'react-tooltip';
import helpLinks from '../translations/helpLinks';
interface TooltipHelpProps {
tipId: string;
}
/**
* Component that renders a help icon that shows a tooltip on hover
*/
export default function TooltipHelpComponentAlternative(props: TooltipHelpProps) {
const divStyle = {
display: 'inline-block'
};
// Create links
const values = helpLinks[props.tipId];
const links: Record<string, JSX.Element> = {};
Object.keys(values).forEach(key => {
const link = values[key];
links[key] = (<a target='_blank' rel="noopener noreferrer" href={link}>
{link}
</a>);
});
return (
<div style={divStyle}>
<i data-for={`${props.tipId}`} data-tip className='fa fa-question-circle' />
<ReactTooltip id={`${props.tipId}`} event='click' clickable effect='solid'>
<div style={{ width: '300px' }}>
<FormattedMessage
id={props.tipId}
values={links}
/>
</div>
</ReactTooltip>
</div>
);
}
| Add rel attribute to resolve security warning | Add rel attribute to resolve security warning
| TypeScript | mpl-2.0 | OpenEnergyDashboard/OED,OpenEnergyDashboard/OED,OpenEnergyDashboard/OED,OpenEnergyDashboard/OED | ---
+++
@@ -24,7 +24,7 @@
const links: Record<string, JSX.Element> = {};
Object.keys(values).forEach(key => {
const link = values[key];
- links[key] = (<a target='_blank' href={link}>
+ links[key] = (<a target='_blank' rel="noopener noreferrer" href={link}>
{link}
</a>);
}); |
22012c16382b56956c081a31933a4f22db9784f7 | packages/ejs/src/index.ts | packages/ejs/src/index.ts | import { HttpResponseOK } from '@foal/core';
import { render as renderEjs } from 'ejs';
// Use types.
export function renderToString(template: string, locals?: object): string {
return renderEjs(template, locals);
}
export function render(template: string, locals?: object): HttpResponseOK {
return new HttpResponseOK(renderToString(template, locals));
}
| import { Controller, HttpResponseOK } from '@foal/core';
import { render as renderEjs } from 'ejs';
// Use types.
export function renderToString(template: string, locals?: object): string {
return renderEjs(template, locals);
}
export function render(template: string, locals?: object): HttpResponseOK {
return new HttpResponseOK(renderToString(template, locals));
}
export function view(path: string, template: string, locals?: object): Controller<'main'> {
const controller = new Controller<'main'>();
controller.addRoute('main', 'GET', path, ctx => render(template, locals));
return controller;
}
| Add view controller factory to @foal/ejs. | Add view controller factory to @foal/ejs.
| TypeScript | mit | FoalTS/foal,FoalTS/foal,FoalTS/foal,FoalTS/foal | ---
+++
@@ -1,4 +1,4 @@
-import { HttpResponseOK } from '@foal/core';
+import { Controller, HttpResponseOK } from '@foal/core';
import { render as renderEjs } from 'ejs';
// Use types.
@@ -9,3 +9,9 @@
export function render(template: string, locals?: object): HttpResponseOK {
return new HttpResponseOK(renderToString(template, locals));
}
+
+export function view(path: string, template: string, locals?: object): Controller<'main'> {
+ const controller = new Controller<'main'>();
+ controller.addRoute('main', 'GET', path, ctx => render(template, locals));
+ return controller;
+} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.