repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
react-epic/deviation
src/createStoreExtractor.ts
<reponame>react-epic/deviation import { AnyConstructorType } from './ConstructorType' import { IProviderToStoreMap } from './Injectable' import { PureDeviation } from './PureDeviation' import { Store } from './Store' import { StoreInjector } from './StoreInjector' export interface IExtractorConstructor extends AnyConstructorType<StoreInjector<{}>> { providers: IProviderToStoreMap getStore?<T extends AnyConstructorType<Store<any, any>>>( provider: T ): InstanceType<T> getProviders?(): IProviderToStoreMap } export function createStoreExtractor(): IExtractorConstructor { class Extractor extends StoreInjector<{}> { public static providers: IProviderToStoreMap = new Map() constructor(deviation: PureDeviation) { super(deviation) } public static getStore< T extends AnyConstructorType<Store<any, any>> >(provider: T): InstanceType<T> { return (this.providers.get( provider ) as unknown) as InstanceType<T> } public static getProviders(): IProviderToStoreMap { return this.providers } public storeDidMount(): void { Extractor.providers = this.props.providers } } return Extractor }
react-epic/deviation
src/PureDeviation.tsx
import { isFunction } from 'lodash' import * as React from 'react' import { noop } from 'rxjs' import { AnyConstructorType } from './ConstructorType' import { Deviation } from './Deviation' import { IProviderToStoreMap } from './Injectable' import { Store } from './Store' import { StoreInjector } from './StoreInjector' import { isVariantOf } from './isVariantOf' export interface IPureDeviationProps { providers?: AnyConstructorType<Store<any, any>>[] defaultProviders: IProviderToStoreMap children?: JSX.Element handleError?(e: Error): void } export interface IPureDeviationState { providers: IProviderToStoreMap handleError(e: Error): void } export interface IStoreProps { providers: Map< AnyConstructorType<Store<any, any>>, Store<any, any> > } export const DeviationContext = React.createContext({ providers: new Map(), handleError: noop }) export const Provider: React.Provider<IPureDeviationState> = DeviationContext.Provider export const Consumer: React.Consumer<IPureDeviationState> = DeviationContext.Consumer export class PureDeviation extends React.Component< IPureDeviationProps, IPureDeviationState > { public static defaultProps: IPureDeviationProps = { defaultProviders: new Map(), providers: [], handleError: noop } public state: IPureDeviationState = { providers: new Map(this.props.defaultProviders), handleError: this.props.handleError } constructor(props: IPureDeviationProps) { super(props) for (const provider of Array.from(this.props.providers)) { const store = this.instantiate( provider, this.state.providers ) this.state.providers.set(provider, store) } } public instantiate( provider: AnyConstructorType<Store<any, any>>, providers: IProviderToStoreMap ): Store<Deviation | IStoreProps, any> { if (isVariantOf(provider, StoreInjector)) { return new provider(this) } return new provider({ providers }) } public componentDidMount(): void { const providers = this.state.providers this.updateProviders(providers) for (const [provider, store] of Array.from(providers)) { if (isFunction(store.storeDidMount)) { store.storeDidMount() } } } public render(): React.ReactNode { return ( <Provider value={this.state}> {this.props.children} </Provider> ) } public updateProviders(providers: IProviderToStoreMap): void { /** * `setState` only notifies changes to components. This method * notifies changes to the stores. */ for (const [provider, store] of Array.from(providers)) { if ( store && store.constructor && (store.constructor as typeof Store).updateProviders ) { ;(store.constructor as typeof Store).updateProviders( store, this.state.providers ) } } } public componentDidUpdate( prevProps: IPureDeviationProps, prevState: IPureDeviationState ): void { for (const [provider, store] of Array.from( prevState.providers )) { if (!this.state.providers.has(provider)) { store.storeWillUnmount() } } for (const [provider, store] of Array.from( this.state.providers )) { if (!prevState.providers.has(provider)) { store.storeDidMount() } } this.updateProviders(this.state.providers) } public componentWillUnmount(): void { for (const [provider, store] of Array.from( this.state.providers )) { if (isFunction(store.storeWillUnmount)) { store.storeWillUnmount() } } } }
react-epic/deviation
test/Deviation/TodoApp.tsx
<gh_stars>1-10 import { ReactWrapper, mount } from 'enzyme' import * as React from 'react' import { Deviation, Inject, Store } from '../../src' import { enter } from '../shared/enter' export interface IStoreState { todos: string[] } export class TodoStore extends Store<{}, IStoreState> { public state: IStoreState = { todos: [] } public addTodo = (todo: string): void => { this.setState(state => ({ todos: state.todos.concat([todo]) })) } } export interface ITodoAppProps { todoStore?: TodoStore } @Inject({ todoStore: TodoStore }) export class TodoApp extends React.Component<ITodoAppProps> { public handleSubmit = ( event: React.KeyboardEvent<HTMLInputElement> ) => { this.props.todoStore.addTodo( (event.target as HTMLInputElement).value ) } public render(): React.ReactNode { const { todoStore } = this.props return ( <div> <ul id="todo-list"> {todoStore.state.todos.map((todo, key) => ( <li key={key}>{todo}</li> ))} </ul> <div> <label htmlFor="new-todo">New Todo:</label> <input name="new-todo" id="todo-input" onKeyDown={enter(this.handleSubmit)} /> </div> </div> ) } } export function createMountPoint(): ReactWrapper< any, Readonly<{}>, React.Component<{}, {}, any> > { return mount( <Deviation providers={[TodoStore]}> <TodoApp /> </Deviation> ) }
react-epic/deviation
src/isVariantOf.ts
import { AnyConstructorType } from './ConstructorType' import { IProviderToStoreMap } from './Injectable' import { Store } from './Store' export function isVariantOf<T extends AnyConstructorType<any>>( typeA: Function, typeB: T ): typeA is AnyConstructorType<InstanceType<T>> { return typeA.prototype instanceof typeB } export function findVariantOf( typeA: AnyConstructorType<Store<any, any>> ): (( providers: IProviderToStoreMap ) => AnyConstructorType<Store<any, any>>) { return providers => { for (const [provider] of Array.from(providers)) { if (isVariantOf(provider, typeA)) { return provider } } return null } }
react-epic/deviation
test/LazyDI/LazyDI.test.tsx
<filename>test/LazyDI/LazyDI.test.tsx import { expect } from 'chai' import { mount } from 'enzyme' import { describe, it } from 'mocha' import * as React from 'react' import * as sinon from 'sinon' import { Deviation } from '../../src' import { AppComponent, HttpMockupProvider } from './HttpProvider' describe('Lazy DI', () => { describe('HttpApp', () => { it('should fallback to the provider subclass', () => { const stub = sinon.stub( HttpMockupProvider.prototype, 'getApi' ) const wrapper = mount( <Deviation providers={[HttpMockupProvider]}> <AppComponent /> </Deviation> ) expect(stub.calledOnce).to.equal( true, 'expect getApi to be called once' ) stub.restore() }) }) })
react-epic/deviation
src/index.ts
export * from './Deviation' export * from './PureDeviation' export * from './Inject' export * from './Store' export * from './StoreInjector' export * from './Injectable' export * from './Connector' export * from './createStoreExtractor' export * from './isVariantOf' export * from './ConstructorType' export * from './deviateComponent' export * from './deviateStore'
react-epic/deviation
test/Deviation/Deviation.test.ts
<filename>test/Deviation/Deviation.test.ts import { expect } from 'chai' import { ReactWrapper } from 'enzyme' import * as React from 'react' import { createMountPoint as createMultipleCounterMountPoint } from './MultipleCounter' import { createMountPoint as createTodoMountPoint } from './TodoApp' describe('Deviation', () => { describe('TodoApp', () => { it('should add new todos', () => { const wrapper = createTodoMountPoint() const todoInput = wrapper.find('#todo-input') const newTodos = [ 'Make this test works', 'Fix the bugs', 'Deploy the library', 'Close issues' ] for (const todo of newTodos) { todoInput.prop('onKeyDown')(({ target: { value: todo }, keyCode: 13 } as unknown) as React.KeyboardEvent<any>) } wrapper.update() expect( wrapper.find('#todo-list').find('li') ).to.have.lengthOf(newTodos.length) }) }) describe('MultipleCounter', () => { it('should create local stores', () => { const wrapper = createMultipleCounterMountPoint() const totalCounter = wrapper.find('#total-counter') const addCounterInput = wrapper.find('#add-counter') const numberOfCounters = 4 Array.from({ length: numberOfCounters }).forEach(() => { ;(addCounterInput.prop('onClick') as Function)() }) wrapper.update() const counters = Array.from({ length: numberOfCounters }).map((value, id) => wrapper.find(`#counter-${id}`)) function increaseCounter( counter: ReactWrapper, count: number ): void { const incrementButton = counter.find('button') Array.from({ length: count }).forEach(() => { ;(incrementButton.prop('onClick') as Function)() }) } increaseCounter(counters[1], 5) increaseCounter(counters[3], 8) expect(totalCounter.text()).to.equal('13') expect(counters[1].find('p').text()).to.equal('5') expect(counters[3].find('p').text()).to.equal('8') }) }) })
react-epic/deviation
test/Testing/Testing.test.tsx
<reponame>react-epic/deviation import { expect } from 'chai' import { mount } from 'enzyme' import * as React from 'react' import * as sinon from 'sinon' import { Deviation, createStoreExtractor } from '../../src' import { CallApp, CallService, createMountPoint } from './CallApp' describe('Testing', () => { describe('CallApp', () => { it('should be called once', () => { const callCount = 3 const stub = sinon.stub(CallService.prototype, 'getPhone') const wrapper = createMountPoint() const button = wrapper.find('button') for (const i of Array.from({ length: callCount })) { button.prop('onClick')( ({} as unknown) as React.MouseEvent<{}> ) } expect(stub.callCount).to.be.equal(callCount) stub.restore() }) it('should extract CallService from providers', () => { const callCount = 3 const Extractor = createStoreExtractor() const wrapper = mount( <Deviation providers={[CallService, Extractor]}> <CallApp /> </Deviation> ) const callService = Extractor.getStore(CallService) const stub = sinon.stub(callService, 'getPhone') const button = wrapper.find('button') for (const i of Array.from({ length: callCount })) { button.prop('onClick')( ({} as unknown) as React.MouseEvent<{}> ) } expect(stub.callCount).to.be.equal(callCount) }) }) })
react-epic/deviation
src/Injectable.ts
<reponame>react-epic/deviation<filename>src/Injectable.ts import { isFunction, transform } from 'lodash' import { AnyConstructorType } from './ConstructorType' import { Store } from './Store' import { isVariantOf } from './isVariantOf' export type IProviderToStoreMap = Map< AnyConstructorType<Store<any, any>>, Store<any, any> > export type IStoreRecord = Record<string, Store<any, any>> export type Injectable = AnyConstructorType<Store<any, any>> export type LazyInjectable = (( providers: IProviderToStoreMap ) => Injectable | void) export type HybridInjectable = Injectable | LazyInjectable export type InjectableRecord = Record<string, HybridInjectable> export function loadInjectables( injectables: InjectableRecord = {}, providers: IProviderToStoreMap = new Map() ): IStoreRecord { return transform( injectables, (injectableProviers, injectable, key) => { const provider = loadInjectable(injectable, providers) if (provider) { injectableProviers[key] = provider } }, {} ) } export function getInjectable( injectable: HybridInjectable, providers: IProviderToStoreMap ): void | Injectable { if (isFunction(injectable)) { if (isVariantOf(injectable, Store)) { return injectable } /** * Lazy load dependency. */ return injectable(providers) } } export function loadInjectable( injectable: HybridInjectable, providers: IProviderToStoreMap ): Store<any, any> { const provider = getInjectable(injectable, providers) if (provider) { return providers.get(provider) } }
react-epic/deviation
test/shared/enter.ts
<filename>test/shared/enter.ts import { isFunction } from 'lodash' import * as React from 'react' export function enter(event: React.KeyboardEvent<{}>): boolean export function enter( func: (event: React.KeyboardEvent<{}>) => void ): ((event: React.KeyboardEvent<{}>) => void) export function enter( func: | React.KeyboardEvent<{}> | ((event: React.KeyboardEvent<{}>) => void) ): boolean | ((event: React.KeyboardEvent<{}>) => void) { if (!isFunction(func)) { return func.keyCode === 13 } return (event: React.KeyboardEvent<{}>): void => { if (enter(event)) { func(event) } } }
react-epic/deviation
src/Deviation.tsx
import * as React from 'react' import { noop } from 'rxjs' import { AnyConstructorType } from './ConstructorType' import { Consumer, IPureDeviationState, PureDeviation } from './PureDeviation' import { Store } from './Store' export interface IDeviationProps { providers?: AnyConstructorType<Store<any, any>>[] children?: JSX.Element handleError?(e: Error): void } export class Deviation extends React.Component< IDeviationProps > { public static defaultProps: IDeviationProps = { providers: [], handleError: noop } public render(): React.ReactNode { return <Consumer>{this.renderContext}</Consumer> } public renderContext = ( context: IPureDeviationState ): React.ReactNode => { return ( <PureDeviation providers={this.props.providers} defaultProviders={context.providers} handleError={this.props.handleError} > {this.props.children} </PureDeviation> ) } }
react-epic/deviation
src/Connector.tsx
<filename>src/Connector.tsx import * as React from 'react' import { Subscription, noop } from 'rxjs' import { IProviderToStoreMap, IStoreRecord, InjectableRecord, loadInjectables } from './Injectable' import { notifier } from './Store' interface IConnectorProps { providers?: IProviderToStoreMap injectables?: InjectableRecord children?: ((props: any) => React.ReactNode) handleError(e: Error): void } interface IConnectorState { stores: IStoreRecord } export class Connector extends React.Component< IConnectorProps, IConnectorState > { public static defaultProps: Partial<IConnectorProps> = { providers: new Map(), injectables: {}, handleError: noop } public state: IConnectorState = { stores: loadInjectables( this.props.injectables, this.props.providers ) } public subscription: Subscription = new Subscription() public componentDidMount(): void { for (const [provider, store] of Array.from( this.props.providers )) { const subscription = store[notifier].subscribe( () => { this.setState(({ stores }) => ({ stores: { ...stores } })) }, err => { this.props.handleError(err) } ) this.subscription.add(subscription) } } public render(): React.ReactNode { const { children } = this.props return children(this.state.stores) } public onReInject(stores: IStoreRecord): void { this.setState({ stores }) } public componentDidUpdate(prevProps: IConnectorProps): void { const { providers, injectables } = this.props if ( providers !== prevProps.providers || injectables !== prevProps.injectables ) { /** * Perform a side-effect. Replace previous registered store with * the current store. */ this.onReInject(loadInjectables(injectables, providers)) } } public componentWillUnmount(): void { if (this.subscription) { this.subscription.unsubscribe() } } }
react-epic/deviation
src/Inject.ts
<reponame>react-epic/deviation import * as React from 'react' import { deviateComponent } from './deviateComponent' import { deviateStore } from './deviateStore' import { isVariantOf } from './isVariantOf' import { AnyConstructorType } from './ConstructorType' import { IStoreRecord, InjectableRecord } from './Injectable' import { Store } from './Store' export function defaultMergeProps( stores: IStoreRecord, props: any ): any { return { ...stores, ...props } } export type InjectedComponentType = AnyConstructorType< React.Component<any, any> | Store<any, any> > export function Inject( injectables: InjectableRecord, mergeProps: ( stores: IStoreRecord, props: any ) => any = defaultMergeProps ): (<T extends InjectedComponentType>( WrappedConstructor: T ) => T) { return WrappedConstructor => { return isVariantOf(WrappedConstructor, React.Component) ? deviateComponent( WrappedConstructor, injectables, mergeProps ) : isVariantOf(WrappedConstructor, Store) ? deviateStore( WrappedConstructor, injectables, mergeProps ) : WrappedConstructor } }
react-epic/deviation
test/StoreDI/StoreDI.test.ts
import { expect } from 'chai' import * as React from 'react' import { createMountPoint } from './CountTodos' describe('StoreDI', () => { describe('CountTodos', () => { it('should update store dependency state', () => { const wrapper = createMountPoint() const todoInput = wrapper.find('#todo-input') const newTodos = [ 'Make this test works', 'Fix the bugs', 'Deploy the library', 'Close issues' ] for (const todo of newTodos) { todoInput.prop('onKeyDown')(({ target: { value: todo }, keyCode: 13 } as unknown) as React.KeyboardEvent<{}>) } const todoCounter = wrapper.find('#todo-counter') expect( Number.parseInt(todoCounter.text(), 10) ).to.be.equal(newTodos.length) }) }) })
react-epic/deviation
test/CyclicDI/CyclicDI.test.ts
<filename>test/CyclicDI/CyclicDI.test.ts import { expect } from 'chai' import { createMountPoint } from './CommunicateApp' describe('Cyclic DI', () => { describe('CommunicateApp', () => { it('should resolve cyclic dependency injection', () => { const wrapper = createMountPoint() const a = wrapper.find('#a') const b = wrapper.find('#b') expect(a.text()).to.be.equal( 'true', 'expect #a text to be true' ) expect(b.text()).to.be.equal( 'true', 'expect #b text to be true' ) }) }) })
react-epic/deviation
test/shared/ErrorBoundary.ts
import * as React from 'react' export class ErrorBoundary extends React.Component { public componentDidCatch( error: Error, info: React.ErrorInfo ): void { // tslint:disable-next-line:no-console console.log(error, info) } public render(): React.ReactNode { return this.props.children } }
react-epic/deviation
test/Testing/CallApp.tsx
<filename>test/Testing/CallApp.tsx<gh_stars>1-10 import { ReactWrapper, mount } from 'enzyme' import * as React from 'react' import { Observable } from 'rxjs' import { AjaxResponse, ajax } from 'rxjs/ajax' import { Deviation, Inject, Store } from '../../src' export class CallService extends Store { public getPhone(): Observable<AjaxResponse> { return ajax.get('/phone' as string) } } export interface ICallAppProps { callService?: CallService } @Inject({ callService: CallService }) export class CallApp extends React.Component<ICallAppProps> { public triggerPhoneCall = () => { this.props.callService.getPhone() } public render(): React.ReactNode { return ( <button onClick={this.triggerPhoneCall}>Trigger</button> ) } } export function createMountPoint(): ReactWrapper< any, Readonly<{}>, React.Component<{}, {}, any> > { return mount( <Deviation providers={[CallService]}> <CallApp /> </Deviation> ) }
react-epic/deviation
test/StoreDI/CountTodos.tsx
<reponame>react-epic/deviation import { ReactWrapper, mount } from 'enzyme' import * as React from 'react' import { Deviation, Inject, Store } from '../../src' import { enter } from '../shared/enter' export interface ICounterStore { counter: number } export class CounterStore extends Store<{}, ICounterStore> { public state: ICounterStore = { counter: 0 } public increment = () => { this.setState(({ counter }) => ({ counter: counter + 1 })) } } export interface ITodoStoreProps { counterStore: CounterStore } export interface ITodoStoreState { todos: string[] } @Inject({ counterStore: CounterStore }) export class TodoStore extends Store< ITodoStoreProps, ITodoStoreState > { public state: ITodoStoreState = { todos: [] } public addTodo = (newTodo: string): void => { this.props.counterStore.increment() this.setState(({ todos }) => ({ todos: [...todos, newTodo] })) } } export interface ICounterTodosProps { todoStore?: TodoStore counterStore?: CounterStore } @Inject({ counterStore: CounterStore, todoStore: TodoStore }) export class CountTodos extends React.Component< ICounterTodosProps > { public handleSubmit = ( event: React.KeyboardEvent<{}> ): void => { this.props.todoStore.addTodo( (event.target as HTMLInputElement).value ) } public render(): React.ReactNode { const { counterStore } = this.props return ( <div> <p id="todo-counter">{counterStore.state.counter}</p> <div> <label htmlFor="new-todo">New Todo:</label> <input name="new-todo" id="todo-input" onKeyDown={enter(this.handleSubmit)} /> </div> </div> ) } } export function createMountPoint(): ReactWrapper< any, Readonly<{}>, React.Component<{}, {}, any> > { return mount( <Deviation providers={[CounterStore, TodoStore]}> <CountTodos /> </Deviation> ) }
react-epic/deviation
test/LazyDI/HttpProvider.tsx
import * as React from 'react' import { Observable } from 'rxjs' import { AjaxResponse, ajax } from 'rxjs/ajax' import { Inject, Store, findVariantOf } from '../../src' export class HttpProvider extends Store { public getApi(api: string): void public getApi(api: string): Observable<AjaxResponse> { return ajax.get(api) } } export class HttpMockupProvider extends HttpProvider { public getApi(api: string): void { // Nothing Here! } } export interface IAppComponentProps { httpProvider?: HttpMockupProvider } @Inject({ httpProvider: findVariantOf(HttpProvider) }) export class AppComponent extends React.Component< IAppComponentProps > { public componentDidMount(): void { this.props.httpProvider.getApi('/api') } public render(): React.ReactNode { return <div>Hello World!</div> } }
react-epic/deviation
src/deviateStore.ts
import { AnyConstructorType } from './ConstructorType' import { IProviderToStoreMap, IStoreRecord, InjectableRecord, loadInjectables } from './Injectable' import { Store } from './Store' export interface IStoreWrapperProps { providers?: IProviderToStoreMap injectables?: InjectableRecord } export function deviateStore( WrappedStore: AnyConstructorType<Store<any, any>>, injectables: InjectableRecord, mergeProps: ( stores: IStoreRecord, props: IStoreWrapperProps ) => IStoreWrapperProps ): AnyConstructorType<Store<any, any>> { class StoreWrapper extends WrappedStore { constructor(props: IStoreWrapperProps) { const { providers } = props const stores = loadInjectables(injectables, providers) super(mergeProps(stores, props)) } public static updateProviders( store: Store<any, any>, providers: IProviderToStoreMap ): void { store.props = { ...store.props, ...mergeProps(loadInjectables(injectables, providers), { providers }) } } } return StoreWrapper }
react-epic/deviation
gulpfile.ts
import * as del from 'del' import * as gulp from 'gulp' import * as ts from 'gulp-typescript' function tsProject(settings?: ts.Settings): ts.CompileStream { return ts.createProject('tsconfig.json', settings)( ts.reporter.defaultReporter() ) } const test = { src: gulp.src('{test,src}/**/*.{ts,tsx}'), dest: gulp.dest('out') } gulp.task('clean:test', () => del('out')) gulp.task('clean:build', () => del('lib')) gulp.task('build:test', ['clean:test'], () => test.src.pipe(tsProject()).js.pipe(test.dest) )
react-epic/deviation
test/Deviation/MultipleCounter.tsx
import { ReactWrapper, mount } from 'enzyme' import * as React from 'react' import { Deviation, Inject, Store } from '../../src' export interface ITotalCounterState { counter: number } export class TotalCounterStore extends Store< {}, ITotalCounterState > { public state: ITotalCounterState = { counter: 0 } public increment = (): void => { this.setState(({ counter }) => ({ counter: counter + 1 })) } } export interface ICounterStoreProps { totalCounterStore?: TotalCounterStore } export interface ICounterStoreState { counter: number } @Inject({ totalCounterStore: TotalCounterStore }) export class CounterStore extends Store< ICounterStoreProps, ICounterStoreState > { public state: ICounterStoreState = { counter: 0 } public increment = (): void => { this.setState(({ counter }) => ({ counter: counter + 1 })) this.props.totalCounterStore.increment() } } export interface ICounterStoreProps { id: string counterStore?: CounterStore } @Inject({ counterStore: CounterStore }) export class Counter extends React.Component< ICounterStoreProps > { public render(): React.ReactNode { const { id, counterStore } = this.props return ( <div id={id}> <p>{counterStore.state.counter}</p> <button onClick={counterStore.increment}> Increment </button> </div> ) } } export interface IMultipleCounterProps { totalCounterStore?: TotalCounterStore } export interface IMultipleCounterState { numberOfCounters: number } // tslint:disable-next-line: max-classes-per-file @Inject({ totalCounterStore: TotalCounterStore }) export class MulitpleCounter extends React.Component< IMultipleCounterProps, IMultipleCounterState > { public state: IMultipleCounterState = { numberOfCounters: 0 } public addCounter = (): void => { this.setState(({ numberOfCounters }) => ({ numberOfCounters: numberOfCounters + 1 })) } public render(): React.ReactNode { const { totalCounterStore } = this.props return ( <div> <p id="total-counter"> {totalCounterStore.state.counter} </p> {Array.from({ length: this.state.numberOfCounters }).map((value, id) => ( <Deviation providers={[CounterStore]} key={id}> <Counter id={`counter-${id}`} /> </Deviation> ))} <button id="add-counter" onClick={this.addCounter}> Add Counter </button> </div> ) } } export function createMountPoint(): ReactWrapper< any, Readonly<{}>, React.Component<{}, {}, any> > { return mount( <Deviation providers={[TotalCounterStore]}> <MulitpleCounter /> </Deviation> ) }
react-epic/deviation
test/CyclicDI/CommunicateApp.tsx
import { ReactWrapper, mount } from 'enzyme' import * as React from 'react' import { Deviation, Inject, Store } from '../../src' export interface IATalkProps { bTalk: BTalk } export interface IATalkState { received: boolean } @Inject({ bTalk: () => BTalk }) export class ATalk extends Store<IATalkProps, IATalkState> { public state: IATalkState = { received: false } public storeDidMount(): void { this.send() } public receive(): void { this.setState({ received: true }) } public send(): void { this.props.bTalk.receive() } } export interface IBTalkProps { aTalk: ATalk } export interface IBTalkState { received: boolean } @Inject({ aTalk: () => ATalk }) export class BTalk extends Store<IBTalkProps, IBTalkState> { public state: IBTalkState = { received: false } public storeDidMount(): void { this.send() } public receive(): void { this.setState({ received: true }) } public send(): void { this.props.aTalk.receive() } } export interface ICommunicateAppProps { aTalk?: ATalk bTalk?: BTalk } @Inject({ aTalk: ATalk, bTalk: BTalk }) export class CommunicateApp extends React.Component< ICommunicateAppProps > { public render(): React.ReactNode { const { aTalk, bTalk } = this.props return ( <div> <p id="a">{JSON.stringify(aTalk.state.received)}</p> <p id="b">{JSON.stringify(bTalk.state.received)}</p> </div> ) } } export function createMountPoint(): ReactWrapper< any, Readonly<{}>, React.Component<{}, {}, any> > { return mount( <Deviation providers={[ATalk, BTalk]}> <CommunicateApp /> </Deviation> ) }
react-epic/deviation
src/deviateComponent.tsx
import * as React from 'react' import { Connector } from './Connector' import { IStoreRecord, InjectableRecord } from './Injectable' import { Consumer, IPureDeviationState } from './PureDeviation' export function deviateComponent<P, S>( WrappedComponent: any, injectables: InjectableRecord, mergeProps: (stores: IStoreRecord, props: any) => any ): any { class WrapperComponent extends React.Component<P, S> { public render(): React.ReactNode { return <Consumer>{this.renderContext}</Consumer> } public renderContext = ( context: IPureDeviationState ): React.ReactNode => { return ( <Connector providers={context.providers} injectables={injectables} handleError={context.handleError} > {this.renderProps} </Connector> ) } public renderProps = ( props: IStoreRecord ): React.ReactNode => { return ( <WrappedComponent {...mergeProps(props, this.props)} /> ) } } return WrapperComponent }
LinbuduLab/json-to-type-graphql
tests/checker.test.ts
<filename>tests/checker.test.ts import path from "path"; import fs from "fs-extra"; import tmp from "tmp"; import * as execa from "execa"; import { Project, SourceFile } from "ts-morph"; import { checker } from "../src/checker"; import { CHECKER_MODULE_SPECIFIER } from "../src/utils"; const outputPath = path.resolve(__dirname, "./fixtures/generated-fixture.ts"); const emptyOutputPath = path.resolve(__dirname, "./fixtures/empty-fixtures.ts"); const tmpFilePath = path.resolve( path.dirname(outputPath), "generated_checker.ts" ); let source: SourceFile; beforeEach(() => { fs.ensureFileSync(tmpFilePath); source = new Project().addSourceFileAtPath(tmpFilePath); }); afterEach(() => { // fs.rmSync(tmpFilePath); new Project().removeSourceFile(source); }); describe("should check generated code", () => { it("should skip when disabled", async () => { const ensureFileSync = jest.spyOn(fs, "ensureFileSync"); const writeFileSync = jest.spyOn(fs, "writeFileSync"); await checker(outputPath, { disable: true, keep: true, execaOptions: {}, executeOptions: {}, buildSchemaOptions: {}, }); expect(ensureFileSync).not.toHaveBeenCalled(); expect(writeFileSync).not.toHaveBeenCalled(); }); it("should generate check file", async () => { await checker(outputPath, { disable: false, keep: true, execaOptions: {}, executeOptions: {}, buildSchemaOptions: {}, }); const checkerImport = source.getImportDeclaration( (imp) => imp.getModuleSpecifierValue() === CHECKER_MODULE_SPECIFIER ); expect(checkerImport).toBeDefined(); expect(checkerImport?.getDefaultImport()?.getText()).toBeUndefined(); const resolverClass = source.getClass("TmpResolver"); expect(resolverClass).toBeDefined(); expect(resolverClass?.getDecorator("Resolver")).toBeDefined(); expect( resolverClass ?.getDecorator("Resolver") ?.getArguments() .map((x) => x.getText()) ).toEqual(["(type)=>Root"]); expect(resolverClass?.getMethod("TmpResolver")?.isAsync()).toBeTruthy(); expect( resolverClass?.getMethod("TmpResolver")?.getDecorator("Query") ).toBeDefined(); expect( resolverClass ?.getMethod("TmpResolver") ?.getDecorator("Query") ?.getArguments() .map((x) => x.getText()) ).toEqual(["(type)=>[Root]"]); expect( resolverClass ?.getMethod("TmpResolver") ?.getStatements() .map((x) => x.getText()) ).toEqual(["return [];"]); expect(fs.readFileSync(tmpFilePath, "utf-8")).toContain("buildSchemaSync"); }); it("should keep generated checker by keep option", async () => { await checker(outputPath, { disable: false, keep: false, execaOptions: {}, executeOptions: {}, buildSchemaOptions: {}, }); expect(fs.existsSync(tmpFilePath)).toBeFalsy(); await checker(outputPath, { disable: false, keep: true, execaOptions: {}, executeOptions: {}, buildSchemaOptions: {}, }); expect(fs.existsSync(tmpFilePath)).toBeTruthy(); }); it.skip("should throw when erorr encountered", async () => { const outputSource = new Project().addSourceFileAtPath(outputPath); outputSource.getClasses().map((cls) => cls.remove()); outputSource.saveSync(); await expect( checker(outputPath, { disable: true, keep: true, execaOptions: {}, executeOptions: {}, buildSchemaOptions: {}, }) ).rejects.toThrow(); }); });
LinbuduLab/json-to-type-graphql
src/generator.ts
<reponame>LinbuduLab/json-to-type-graphql import { Scope } from "ts-morph"; import type { SourceFile, DecoratorStructure, PropertyDeclarationStructure, OptionalKind, } from "ts-morph"; import { capitalCase, normalizeClassFix, normalizeTypeFix, reverseObjectKeys, DEFAULT_SUFFIX, DEFAULT_ENTRY_CLASS_NAME, BASE_IMPORTS, BASE_MODULE_SPECIFIER, } from "./utils"; import type { ProcessedFieldInfoObject, ClassGeneratorRecord, GeneratorOptions, RecordValue, } from "./utils"; import { addImportDeclaration, ImportType, invokeClassDeclarationGenerator, } from "./ast"; /** * Generate AST from parsed info * @param source source file * @param parsed parsed info * @param options generator options */ export function generator( source: SourceFile, parsed: ProcessedFieldInfoObject, options: GeneratorOptions ) { const classGeneratorRecord: ClassGeneratorRecord = {}; addImportDeclaration( source, BASE_IMPORTS, BASE_MODULE_SPECIFIER, ImportType.NAMED_IMPORTS, false ); collectClassStruInfo( source, parsed, classGeneratorRecord, undefined, options ); reverseRelation(classGeneratorRecord); const record = options.sort ? reverseObjectKeys(classGeneratorRecord) : classGeneratorRecord; invokeClassDeclarationGenerator(source, record, true); } /** * Collect class info record to generate from parsed info * @param source source file * @param parsed parsed info * @param record class info record * @param parent info parent (if exist) * @param options generator options */ export function collectClassStruInfo( source: SourceFile, parsed: ProcessedFieldInfoObject, record: ClassGeneratorRecord, parent: string | undefined, options: GeneratorOptions ): void { const { entryClassName, publicProps, readonlyProps, suffix, prefix } = options; const classDecorator: OptionalKind<DecoratorStructure>[] = [ { name: "ObjectType", arguments: [], }, ]; const properties: OptionalKind<PropertyDeclarationStructure>[] = []; const classPrefix = normalizeClassFix(prefix, entryClassName); const classSuffix = normalizeClassFix(suffix, DEFAULT_SUFFIX); for (const [k, v] of Object.entries(parsed)) { const typePrefix = normalizeTypeFix(classPrefix, v.type); const typeSuffix = normalizeTypeFix(classSuffix, v.type); const propType = `${typePrefix}${v.propType}${typeSuffix}${ v.list ? "[]" : "" }`; const returnType = `${typePrefix}${v.decoratorReturnType}${typeSuffix}`; if (v.nested) { collectClassStruInfo(source, v.fields!, record, entryClassName, { ...options, entryClassName: `${classPrefix}${v.propType}${typeSuffix}`, }); } const fieldReturnType: string[] = v.decoratorReturnType ? v.list ? [ `(type) => [${returnType}${v.nullableListItem ? "" : "!"}]${ v.nullable ? "" : "!" }`, ] : [`(type) => ${returnType}${v.nullable ? "" : "!"}`] : []; if (v.nullable) fieldReturnType.push(`{ nullable: true }`); properties.push({ name: v.prop, type: propType, decorators: [ { name: "Field", arguments: fieldReturnType, }, ], scope: publicProps.includes(v.prop) ? Scope.Public : undefined, trailingTrivia: (writer) => writer.newLine(), hasExclamationToken: !v.nullable, hasQuestionToken: v.nullable, isReadonly: readonlyProps.includes(v.prop), }); } const currentRecord: RecordValue<ClassGeneratorRecord> = { info: { name: entryClassName === DEFAULT_ENTRY_CLASS_NAME ? DEFAULT_ENTRY_CLASS_NAME : capitalCase(`${entryClassName}`), decorators: classDecorator, properties, isExported: true, }, parent: parent ?? null, children: [], generated: false, }; record[entryClassName] = currentRecord; } /** * Fill children info to parent item * @param raw */ export function reverseRelation(raw: ClassGeneratorRecord) { for (const [k, v] of Object.entries(raw)) { if (v.parent) { raw[v.parent]["children"].push(k); } } }
LinbuduLab/json-to-type-graphql
src/writter.ts
<gh_stars>1-10 import prettier from "prettier"; import fs from "fs-extra"; import type { WriterOptions } from "./utils"; /** * Format generated file and write * @param param */ export function writter({ outputPath, override, format, formatOptions, }: WriterOptions) { if (!outputPath) throw new Error("writer.outputPath is required!"); const raw = fs.readFileSync(outputPath, "utf-8"); const formatted = format ? prettier.format(raw, { parser: "typescript", tabWidth: 2, ...formatOptions, }) : raw; fs.writeFileSync(outputPath, formatted); }
LinbuduLab/json-to-type-graphql
src/index.ts
import fs from "fs-extra"; import { Project } from "ts-morph"; import { reader } from "./reader"; import { preprocessor } from "./preprocessor"; import { parser } from "./parser"; import { generator } from "./generator"; import { postprocessor } from "./postprocessor"; import { checker } from "./checker"; import { writter } from "./writter"; import { normalizeOptions } from "./utils"; import type { Options } from "./utils"; /** * Generate TypeGraphQL class declaration from JSON object * @param content Input raw content * @param outputPath Output file path * @param options */ export default async function handler(options: Options): Promise<void> { const content = await reader(options.reader); const { normalizedPreprocessorOptions, normalizedParserOptions, normalizedGeneratorOptions, normalizedPostprocessorOptions, normalizedCheckerOptions, normalizedWritterOptions, } = normalizeOptions(options); const originInput = content; const preprocessed = preprocessor(originInput, normalizedPreprocessorOptions); const parsedInfo = parser(preprocessed, normalizedParserOptions); fs.ensureFileSync(normalizedWritterOptions.outputPath); const source = new Project().addSourceFileAtPath( normalizedWritterOptions.outputPath ); generator(source, parsedInfo, normalizedGeneratorOptions); postprocessor(source, normalizedPostprocessorOptions); await checker(normalizedWritterOptions.outputPath, normalizedCheckerOptions); writter(normalizedWritterOptions); } export * from "./reader"; export * from "./preprocessor"; export * from "./parser"; export * from "./generator"; export * from "./postprocessor"; export * from "./checker"; export * from "./writter";
LinbuduLab/json-to-type-graphql
tests/postprocesser.test.ts
import { Project } from "ts-morph"; import tmp from "tmp"; import fs from "fs-extra"; import { postprocessor } from "../src/postprocessor"; describe("should apply postprocess", () => { it("should use custom postprocessor", () => { const fn = jest.fn().mockImplementation((r) => {}); const tmpFile = tmp.fileSync().name; fs.writeFileSync(tmpFile, "const foo = 'bar'"); const source = new Project().addSourceFileAtPath(tmpFile); postprocessor(source, { customPostprocessor: fn, }); expect(fn).toHaveBeenCalledTimes(1); expect(fn).toHaveBeenCalledWith(source, {}); }); it("should skip when no custom postprocessor specified", () => { const tmpFile = tmp.fileSync().name; const source = new Project().addSourceFileAtPath(tmpFile); fs.writeFileSync(tmpFile, "const foo = 'bar'"); postprocessor(source, {}); // TODO: how do we know it's skipped? }); });
LinbuduLab/json-to-type-graphql
src/checker.ts
import path from "path"; import fs from "fs-extra"; import { Project } from "ts-morph"; import execa from "execa"; import { createTmpResolverContent } from "./ast"; import type { CheckerOptions } from "./utils"; /** * Check can generated schema be used by buildSchemaSync * @param outputPath generated path * @param options checker options * @returns */ export async function checker(outputPath: string, options: CheckerOptions) { if (options.disable) return; const outputDir = path.dirname(outputPath); const tmpFilePath = path.resolve(outputDir, "generated_checker.ts"); fs.ensureFileSync(tmpFilePath); fs.writeFileSync(tmpFilePath, fs.readFileSync(outputPath, "utf-8")); const project = new Project(); const checkerOnlySource = project.addSourceFileAtPath(tmpFilePath); try { createTmpResolverContent(checkerOnlySource, options, "Root"); await execa( `ts-node ${tmpFilePath}`, [ "--compiler-options", JSON.stringify({ experimentalDecorators: true, emitDecoratorMetadata: true, declaration: false, ...options.executeOptions, }), ], { shell: true, stdio: "inherit", ...options.execaOptions, } ); } catch (error) { throw error; } finally { !options.keep && fs.existsSync(tmpFilePath) && fs.rmSync(tmpFilePath); } }
LinbuduLab/json-to-type-graphql
src/parser.ts
<reponame>LinbuduLab/json-to-type-graphql import intersection from "lodash/intersection"; import uniqBy from "lodash/uniqBy"; import { strictTypeChecker, capitalCase, ValidFieldType } from "./utils"; import type { MaybeArray, SourceObject, SourceArray, ProcessedFieldInfoObject, ParsedFieldInfo, ParserOptions, } from "./utils"; /** * Parse raw content to specific structure which can be consumed by generator * @param content Input content * @param options Parser options * @returns */ export function parser( content: MaybeArray<SourceObject> | SourceArray, options: Required<ParserOptions> ): ProcessedFieldInfoObject { return Array.isArray(content) ? arrayEntryParser(content, options) : objectEntryParser(content, options); } /** * Handle array entry json structure parsing * @param content Input content * @param options Parser options * @returns */ export function arrayEntryParser( content: SourceObject[] | SourceArray, options: ParserOptions ): ProcessedFieldInfoObject { const { forceNonNullable, forceReturnType, arrayEntryProp, forceNonNullableListItem, } = options; const parsedFieldInfo: ProcessedFieldInfoObject = {}; if (!content.length) return {}; const randomItem = content[0]; const type = strictTypeChecker(randomItem); switch (type) { case ValidFieldType.String: case ValidFieldType.Boolean: case ValidFieldType.Number: parsedFieldInfo["TMP"] = { type: ValidFieldType.Primitive_Array, propType: typeof randomItem, nested: false, list: true, prop: arrayEntryProp, nullable: !forceNonNullable, nullableListItem: !forceNonNullableListItem, fields: null, decoratorReturnType: typeof randomItem === "number" ? "Int" : forceReturnType ? strictTypeChecker(randomItem) : null, }; break; case ValidFieldType.Object: parsedFieldInfo["TMP"] = { type: ValidFieldType.Object_Array, propType: capitalCase(arrayEntryProp), nested: true, list: true, prop: arrayEntryProp, nullable: !forceNonNullable, nullableListItem: !forceNonNullableListItem, fields: objectArrayParser(content as SourceObject[], options), decoratorReturnType: capitalCase(arrayEntryProp), }; break; case ValidFieldType.Empty_Array: parsedFieldInfo["TMP"] = { type, list: true, propType: capitalCase(arrayEntryProp), decoratorReturnType: capitalCase(arrayEntryProp), nested: true, nullable: !forceNonNullable, nullableListItem: !forceNonNullableListItem, prop: arrayEntryProp, fields: {}, }; break; case ValidFieldType.Primitive_Array: case ValidFieldType.Object_Array: case ValidFieldType.Null: case ValidFieldType.Undefined: case ValidFieldType.Ignore: break; } return parsedFieldInfo; } /** * Handle common object entry json structure parsing * @param content Input content * @param options Parser options * @returns */ export function objectEntryParser( content: SourceObject, options: ParserOptions ): ProcessedFieldInfoObject { const { forceNonNullable, forceReturnType, forceNonNullableListItem } = options; const parsedFieldInfo: ProcessedFieldInfoObject = {}; for (const [k, v] of Object.entries(content)) { const type = strictTypeChecker(v); const capitalCasedKey = capitalCase(k); switch (type) { case ValidFieldType.String: case ValidFieldType.Boolean: parsedFieldInfo[k] = { type, propType: typeof v, nested: false, prop: k, nullable: !forceNonNullable, list: false, fields: null, decoratorReturnType: forceReturnType ? type : null, }; break; case ValidFieldType.Number: parsedFieldInfo[k] = { type, propType: "number", nested: false, prop: k, nullable: !forceNonNullable, list: false, fields: null, decoratorReturnType: "Int", }; break; case ValidFieldType.Object: parsedFieldInfo[k] = { type, propType: capitalCasedKey, nested: true, list: false, prop: k, nullable: !forceNonNullable, decoratorReturnType: capitalCasedKey, fields: parser(v, options), }; break; case ValidFieldType.Empty_Array: parsedFieldInfo[k] = { type, list: true, propType: capitalCasedKey, decoratorReturnType: capitalCasedKey, nested: true, nullable: !forceNonNullable, nullableListItem: !forceNonNullableListItem, prop: k, fields: {}, }; break; case ValidFieldType.Primitive_Array: parsedFieldInfo[k] = { type, propType: typeof v[0], nested: false, list: true, prop: k, fields: null, nullable: !forceNonNullable, nullableListItem: !forceNonNullableListItem, decoratorReturnType: typeof v[0] === "number" ? "Int" : strictTypeChecker(v[0]), }; break; case ValidFieldType.Object_Array: parsedFieldInfo[k] = { type, list: true, propType: capitalCasedKey, decoratorReturnType: capitalCasedKey, nested: true, nullable: !forceNonNullable, nullableListItem: !forceNonNullableListItem, prop: k, fields: objectArrayParser(v, options), }; break; case ValidFieldType.Null: case ValidFieldType.Undefined: case ValidFieldType.Ignore: break; } } return parsedFieldInfo; } /** * Handle object member array parsing * @param arr * @param options * @returns */ export function objectArrayParser( arr: SourceObject[], options: ParserOptions ): ProcessedFieldInfoObject { const keys: string[][] = []; const parsedKeys: ParsedFieldInfo[] = []; const { forceNonNullable } = options ?? {}; const processedResult: ProcessedFieldInfoObject = {}; for (const item of arr) { keys.push(Object.keys(item)); } const intersectionKeys = intersection(...keys); intersectionKeys.forEach((key) => { const nonNullSharedItem = arr.filter( (item) => item[key] === 0 || item[key] === "" || !![item[key]] ); parsedKeys.push({ ...parser(nonNullSharedItem[0], options)[key], shared: true, // NOTE: shared keys are regarded as non-nullable value // even in common array entry situation nullable: false, }); }); for (const item of arr) { intersectionKeys.forEach((key) => { key in item && delete item[key]; }); } for (const item of arr) { for (const [k, v] of Object.entries(item)) { parsedKeys.push({ ...parser({ [k]: v }, options)[k], shared: false, nullable: !forceNonNullable, }); } } const result = uniqBy(parsedKeys, (key) => key.prop); result.forEach((item) => { processedResult[item.prop] = item; }); return processedResult; }
LinbuduLab/json-to-type-graphql
tests/utils.test.ts
import { capitalCase, ensureArray, reverseObjectKeys, strictTypeChecker, normalizeClassFix, normalizeTypeFix, ValidFieldType, } from "../src/utils"; describe("should ensure utils!", () => { it("should transform to capitalCase", () => { expect(capitalCase("nested")).toBe("Nested"); expect(capitalCase("nestedType")).toBe("NestedType"); }); it("should ensure array type", () => { expect(ensureArray(1)).toEqual([1]); expect(ensureArray([1])).toEqual([1]); }); it("should reverse object keys", () => { expect( reverseObjectKeys({ a: { info: {}, parent: null, children: [], generated: true, }, b: { info: {}, parent: null, children: [], generated: true, }, c: { info: {}, parent: null, children: [], generated: true, }, }) ).toStrictEqual({ c: { info: {}, parent: null, children: [], generated: true, }, b: { info: {}, parent: null, children: [], generated: true, }, a: { info: {}, parent: null, children: [], generated: true, }, }); }); it("should check type", () => { expect(strictTypeChecker("linbudu")).toBe(ValidFieldType.String); expect(strictTypeChecker(null)).toBe(ValidFieldType.Null); expect(strictTypeChecker(undefined)).toBe(ValidFieldType.Undefined); expect(strictTypeChecker(599)).toBe(ValidFieldType.Number); expect(strictTypeChecker(true)).toBe(ValidFieldType.Boolean); expect(strictTypeChecker([])).toBe(ValidFieldType.Empty_Array); expect(strictTypeChecker([1, 2, 3])).toBe(ValidFieldType.Primitive_Array); expect(strictTypeChecker([1, "2", true])).toBe( ValidFieldType.Primitive_Array ); expect(strictTypeChecker({ foo: "bar" })).toBe(ValidFieldType.Object); expect(strictTypeChecker([{ foo: "bar" }, { foo: "bar" }])).toBe( ValidFieldType.Object_Array ); expect(strictTypeChecker(Symbol("linbudu"))).toBe(ValidFieldType.Ignore); }); it("should normalize class fix", () => { expect(normalizeClassFix(true, "foo")).toBe("foo"); expect(normalizeClassFix("bar", "")).toBe("bar"); expect(normalizeClassFix("bar", "foo")).toBe("bar"); expect(normalizeClassFix(false, "foo")).toBe(""); expect(normalizeClassFix(false, "")).toBe(""); }); it("should normalize type fix", () => { expect(normalizeTypeFix("foo", ValidFieldType.Boolean)).toBe(""); expect(normalizeTypeFix("foo", ValidFieldType.String)).toBe(""); expect(normalizeTypeFix("foo", ValidFieldType.Number)).toBe(""); expect(normalizeTypeFix("foo", ValidFieldType.Primitive_Array)).toBe(""); expect(normalizeTypeFix("foo", ValidFieldType.Empty_Array)).toBe("Foo"); expect(normalizeTypeFix("foo", ValidFieldType.Object)).toBe("Foo"); expect(normalizeTypeFix("foo", ValidFieldType.Object_Array)).toBe("Foo"); }); });
LinbuduLab/json-to-type-graphql
src/utils.ts
import { Options as PrettierOptions } from "prettier"; import { capitalCase as originalCapitalCase } from "capital-case"; import { OptionalKind, ClassDeclarationStructure, SourceFile } from "ts-morph"; import { Options as GotOptions } from "got"; import { Options as ExecaOptions } from "execa"; import { CompilerOptions } from "typescript"; import { BuildSchemaOptions } from "type-graphql"; /** * Capitalize string, avoid incorrect behaviour like: "nestedType" -> "Nested Type" * @param str * @returns */ export const capitalCase: typeof originalCapitalCase = (str) => originalCapitalCase(str, { delimiter: "" }); export type ClassGeneratorRecord = Record< string, { info: OptionalKind<ClassDeclarationStructure>; parent: string | null; children: string[]; generated: boolean; } >; export type ClassInfo = OptionalKind<ClassDeclarationStructure>; export const ARRAY_ENTRY_STRUCTURE_PROP = "data"; export const DEFAULT_ENTRY_CLASS_NAME = "Root"; export const DEFAULT_ENTRY_CLASS_NAME_SUFFIX = "__TMP_CLASS_NAME_TYPE__"; export const DEFAULT_SUFFIX = "Type"; export const BASE_IMPORTS = ["ObjectType", "Field", "Int", "ID"]; export const BASE_MODULE_SPECIFIER = "type-graphql"; export const CHECKER_IMPORTS = ["Resolver", "Query", "buildSchemaSync"]; export const CHECKER_MODULE_SPECIFIER = "reflect-metadata"; export type SourceObject = Record<string, any>; export type SourceArray = Array<string | boolean | number | SourceObject>; export type ValidPrimitiveType = "string" | "number" | "boolean"; export type RecordValue<T> = T extends Record<string, infer R> ? R : never; export type MaybeArray<T> = T | Array<T>; export type ParsedFieldInfo = { type: ValidFieldType; nested: boolean; prop: string; propType: "string" | "number" | "boolean" | string; list: boolean; nullable: boolean; decoratorReturnType: string | null; fields: ProcessedFieldInfoObject | null; shared?: boolean; nullableListItem?: boolean; }; export type ReaderOptions = { path?: string; url?: string; options?: GotOptions; raw?: SourceObject | SourceObject[] | SourceArray; }; /** * Custom preprocess function */ export type PreprocessorFunc = ( raw: SourceObject | SourceObject[] | SourceArray, options: Omit<PreprocessorOptions, "customPreprocessor"> ) => MaybeArray<SourceObject> | SourceArray; export type PreprocessorOptions = { preserveObjectOnlyInArray: boolean; customPreprocessor?: PreprocessorFunc; }; export type ParserOptions = { forceNonNullable: boolean; forceNonNullableListItem: boolean; forceReturnType: boolean; arrayEntryProp: string; }; export type GeneratorOptions = { entryClassName: string; prefix: boolean | string; suffix: boolean | string; publicProps: string[]; readonlyProps: string[]; sort: boolean; }; export type PostprocessorFunc = ( source: SourceFile, options: Omit<PostprocessorOptions, "customPostprocessor"> ) => void; export type PostprocessorOptions = { // removeUnusedDecorators: boolean; customPostprocessor?: PostprocessorFunc; }; export type CheckerOptions = { disable: boolean; keep: boolean; execaOptions: ExecaOptions; executeOptions: CompilerOptions; buildSchemaOptions: Omit<BuildSchemaOptions, "resolvers">; }; export type WriterOptions = { outputPath: string; override?: boolean; format?: boolean; formatOptions?: PrettierOptions; }; export type Options = { /** * Options pass to reader */ reader: Partial<ReaderOptions>; /** * Options pass to pre-processor */ preprocessor?: Partial<PreprocessorOptions>; /** * Options pass to parser */ parser?: Partial<ParserOptions>; /** * Options pass to generator */ generator?: Partial<GeneratorOptions>; /** * Options pass to post-processor */ postprocessor?: Partial<PostprocessorOptions>; /** * Options pass to checker */ checker?: Partial<CheckerOptions>; /** * Options pass to writer */ writter: WriterOptions; }; export type InferPartialTypeParam<T> = T extends Partial<infer R> ? R : T; export type NormalizedOptions = { [K in keyof Omit< Options, "reader" > as `normalized${Capitalize<K>}Options`]-?: InferPartialTypeParam< Options[K] >; }; export function normalizeOptions(options: Options): NormalizedOptions { const { preserveObjectOnlyInArray = true, customPreprocessor = undefined } = options?.preprocessor ?? {}; const { forceNonNullable = true, forceReturnType = false, arrayEntryProp = ARRAY_ENTRY_STRUCTURE_PROP, forceNonNullableListItem = false, } = options.parser ?? {}; const { prefix = false, publicProps = [], readonlyProps = [], suffix = false, entryClassName = DEFAULT_ENTRY_CLASS_NAME, sort = true, } = options.generator ?? {}; const { customPostprocessor = undefined } = options.postprocessor ?? {}; const { disable: disableChecker = true, keep = false, execaOptions = {}, executeOptions = {}, buildSchemaOptions = {}, } = options.checker ?? {}; const { format = true, override = false, formatOptions = {}, outputPath, } = options.writter ?? {}; return { normalizedPreprocessorOptions: { preserveObjectOnlyInArray, customPreprocessor, }, normalizedParserOptions: { forceNonNullable, forceReturnType, arrayEntryProp, forceNonNullableListItem, }, normalizedGeneratorOptions: { prefix, publicProps, readonlyProps, suffix, entryClassName, sort, }, normalizedPostprocessorOptions: { customPostprocessor, }, normalizedCheckerOptions: { disable: sort || disableChecker, keep, execaOptions, executeOptions, buildSchemaOptions, }, normalizedWritterOptions: { format, override, formatOptions, outputPath, }, }; } export type ProcessedFieldInfoObject = Record<string, ParsedFieldInfo>; /** * Valid field type * which can be used by parser and generator to perform different operations on. */ export const enum ValidFieldType { Null = "Null", Undefined = "Undefined", String = "String", Number = "Number", Boolean = "Boolean", Object = "Object", Primitive_Array = "Primitive_Array", Object_Array = "Object_Array", Empty_Array = "Empty_Array", Ignore = "Ignore", } /** * Ensure args to be array * @param maybeArray * @returns */ export function ensureArray<T>(maybeArray: T | T[]): T[] { return Array.isArray(maybeArray) ? maybeArray : [maybeArray]; } // FIXME: Use Map to ensure k-v are placed as insert order /** * Simply reverse object by reversing its keys. * @param object * @returns */ export function reverseObjectKeys( object: ClassGeneratorRecord ): ClassGeneratorRecord { const result: ClassGeneratorRecord = {}; for (const key of Object.keys(object).reverse()) { result[key] = object[key]; } return result; } /** * Classify field type to stricter kinds * @param val * @returns `ValidFieldType` */ export function strictTypeChecker(val: unknown): ValidFieldType { if (val === null) return ValidFieldType.Null; if (typeof val === "undefined") return ValidFieldType.Undefined; if (typeof val === "string") return ValidFieldType.String; if (typeof val === "number") return ValidFieldType.Number; if (typeof val === "boolean") return ValidFieldType.Boolean; if (Array.isArray(val)) { if (!val.length) return ValidFieldType.Empty_Array; return ["string", "number", "boolean"].includes(typeof val[0]) ? ValidFieldType.Primitive_Array : ValidFieldType.Object_Array; } if (typeof val === "object") return ValidFieldType.Object; return ValidFieldType.Ignore; } export function normalizeClassFix( fix: string | boolean, fallback: string ): string { return fix ? (typeof fix === "string" ? fix : fallback) : ""; } /** * Nornalize type fix, skip on specific field type * @param fix * @param type * @returns */ export function normalizeTypeFix(fix: string, type: ValidFieldType): string { return [ ValidFieldType.Boolean, ValidFieldType.String, ValidFieldType.Number, ValidFieldType.Primitive_Array, ].includes(type) ? "" : capitalCase(fix); }
LinbuduLab/json-to-type-graphql
tests/preprocesser.test.ts
<gh_stars>1-10 import { preprocessor, preserveObjectTypeInArrayOnly, preservePrimitiveTypeInArrayOnly, } from "../src/preprocessor"; const objectOnlyArray = [{ foo: "bar" }]; const primitiveOnlyArray = [1, 2, 3, 4]; const mixedPrimitiveOnlyArray = [1, "linbudu", true]; const mixedArray = [...objectOnlyArray, ...primitiveOnlyArray]; describe("should process raw content", () => { it("should preserve object only", () => { expect(preserveObjectTypeInArrayOnly(objectOnlyArray)).toStrictEqual( objectOnlyArray ); expect(preserveObjectTypeInArrayOnly(primitiveOnlyArray)).toStrictEqual([]); expect( preserveObjectTypeInArrayOnly(mixedPrimitiveOnlyArray) ).toStrictEqual([]); expect(preserveObjectTypeInArrayOnly(mixedArray)).toStrictEqual( objectOnlyArray ); }); it("should primitive member only", () => { expect(preservePrimitiveTypeInArrayOnly(objectOnlyArray)).toStrictEqual([]); expect(preservePrimitiveTypeInArrayOnly(primitiveOnlyArray)).toStrictEqual( primitiveOnlyArray ); expect( preservePrimitiveTypeInArrayOnly(mixedPrimitiveOnlyArray) ).toStrictEqual(mixedPrimitiveOnlyArray); expect(preservePrimitiveTypeInArrayOnly(mixedArray)).toStrictEqual( primitiveOnlyArray ); }); it("should use cutom preprocessor if specified", () => { const fn = jest.fn().mockImplementation((r) => r); const raw = { foo: "bar" }; preprocessor(raw, { preserveObjectOnlyInArray: true, customPreprocessor: fn, }); expect(fn).toHaveBeenCalledTimes(1); expect(fn).toHaveBeenCalledWith(raw, { preserveObjectOnlyInArray: true }); }); it("should process array source", () => { expect( preprocessor(mixedArray, { preserveObjectOnlyInArray: true }) ).toStrictEqual(objectOnlyArray); expect( preprocessor(mixedArray, { preserveObjectOnlyInArray: false }) ).toStrictEqual(primitiveOnlyArray); }); it("should process object", () => { expect( preprocessor( { foo: { foo1: [["foo"]], foo2: "bar", foo3: [], }, }, { preserveObjectOnlyInArray: true } ) ).toStrictEqual({ foo: { foo2: "bar", foo3: [], }, }); expect( preprocessor( { foo: { foo1: "foo", foo2: "bar", foo3: [], }, }, { preserveObjectOnlyInArray: true } ) ).toStrictEqual({ foo: { foo1: "foo", foo2: "bar", foo3: [], }, }); expect( preprocessor( { foo: { foo1: "foo", foo2: "bar", foo3: { foo3arr: [], foo3nestedarr: [[]], }, }, }, { preserveObjectOnlyInArray: true } ) ).toStrictEqual({ foo: { foo1: "foo", foo2: "bar", foo3: { foo3arr: [], }, }, }); expect(preprocessor([], { preserveObjectOnlyInArray: true })).toStrictEqual( [] ); expect( preprocessor( { foo: { foo1: "foo", foo2: "bar", foo3: { foo3arr: ["foo", "bar"], foo3nestedarr: [[]], foo3mixedarr: [{ a: 1 }, "foo", "bar"], }, }, }, { preserveObjectOnlyInArray: true } ) ).toStrictEqual({ foo: { foo1: "foo", foo2: "bar", foo3: { foo3arr: ["foo", "bar"], foo3mixedarr: [{ a: 1 }], }, }, }); expect( preprocessor( { foo: { foo1: "foo", foo2: "bar", foo3: { foo3arr: ["foo", "bar"], foo3nestedarr: [[]], foo3mixedarr: [{ a: 1 }, "foo", "bar"], }, }, }, { preserveObjectOnlyInArray: false } ) ).toStrictEqual({ foo: { foo1: "foo", foo2: "bar", foo3: { foo3arr: ["foo", "bar"], foo3mixedarr: ["foo", "bar"], }, }, }); }); });
LinbuduLab/json-to-type-graphql
src/preprocessor.ts
import { MaybeArray, strictTypeChecker, ValidFieldType } from "./utils"; import omit from "lodash/omit"; import type { SourceObject, SourceArray, PreprocessorOptions } from "./utils"; /** * Pre-process raw content before it's passed to parser. * Nested array will be removed for now(not support yet). * @param raw * @param options * @returns */ export function preprocessor( raw: MaybeArray<SourceObject> | SourceArray, options: PreprocessorOptions ): MaybeArray<SourceObject> | SourceArray { if ( options.customPreprocessor && typeof options.customPreprocessor === "function" ) { return options.customPreprocessor( raw, omit(options, ["customPreprocessor"]) ); } if (Array.isArray(raw)) { return arrayPreprocessor(raw, options); } for (const [k, v] of Object.entries(raw)) { // extract as `nestedArray` if (Array.isArray(v)) { v.length && Array.isArray(v[0]) ? // delete nested array directly at first delete raw[k] : (raw[k] = preprocessor(v, options)); } if (strictTypeChecker(v) === ValidFieldType.Object) { preprocessor(v, options); } } return raw; } /** * Ensure only object or primitive type exist in an array. * @param raw * @param param1 * @returns */ export function arrayPreprocessor( raw: SourceArray, { preserveObjectOnlyInArray }: PreprocessorOptions ) { if (!raw.length) return raw; const { primitives, objects, shouldApplyProcess } = shouldProcess(raw); return shouldApplyProcess ? preserveObjectOnlyInArray ? objects : primitives : raw; } type ShouldProcessResult = { primitives: SourceArray; objects: SourceObject[]; shouldApplyProcess: boolean; }; /** * Determine should process array and split primitive & object members * @param arr * @returns */ export function shouldProcess( arr: SourceArray | SourceObject[] ): ShouldProcessResult { const primitives = preservePrimitiveTypeInArrayOnly(arr); const objects = preserveObjectTypeInArrayOnly(arr); return { primitives, objects, shouldApplyProcess: primitives.length !== 0 && objects.length !== 0, }; } /** * Preserve only object type in an array, primitive type will be removed. * @param arr * @returns */ export function preserveObjectTypeInArrayOnly( arr: SourceArray ): SourceObject[] { return arr.filter( (val) => strictTypeChecker(val) === ValidFieldType.Object ) as SourceObject[]; } /** * Preserve only primitive type in an array, object type will be removed. * @param arr * @returns */ export function preservePrimitiveTypeInArrayOnly( arr: SourceArray ): SourceArray { return arr.filter((val) => [ ValidFieldType.Number, ValidFieldType.Boolean, ValidFieldType.String, ].includes(strictTypeChecker(val)) ); }
LinbuduLab/json-to-type-graphql
tests/ast.test.ts
<gh_stars>1-10 import prettier from "prettier"; import tmp from "tmp"; import fs from "fs-extra"; import path from "path"; import { Project, SourceFile } from "ts-morph"; import { checkExistClassDeclarations, removeNamedImportsMember, setNamedImportsMember, removeImportDeclarations, appendNamedImportsMember, addImportDeclaration, ImportType, removeClassDeclarations, classDeclarationGeneratorFromList, createTmpResolverContent, classDeclarationGenerator, invokeClassDeclarationGenerator, } from "../src/ast"; import { BASE_MODULE_SPECIFIER, CHECKER_IMPORTS, CHECKER_MODULE_SPECIFIER, } from "../src/utils"; let tmpFile: string; let source: SourceFile; beforeEach(() => { tmpFile = tmp.fileSync().name; fs.writeFileSync( tmpFile, fs.readFileSync( path.resolve(__dirname, "./fixtures/ast-fixture.ts"), "utf-8" ) ); source = new Project().addSourceFileAtPath(tmpFile); }); afterEach(() => { fs.rmSync(tmpFile); new Project().removeSourceFile(source); }); describe("should perform AST operations", () => { it("should generate simple class declaration", () => { invokeClassDeclarationGenerator( source, { FooBar: { info: { name: "FooBar", }, parent: null, children: [], generated: false, }, Wuhu: { info: { name: "Wuhu", }, parent: null, children: [], generated: false, }, }, true ); expect(source.getClasses().map((x) => x.getName())).toContain("Wuhu"); expect(source.getClasses().map((x) => x.getName())).toContain("FooBar"); }); it("should skip generated class info", () => { invokeClassDeclarationGenerator( source, { FooBar: { info: { name: "FooBar", }, parent: null, children: [], generated: true, }, Wuhu: { info: { name: "Wuhu", }, parent: null, children: [], generated: true, }, }, true ); expect(source.getClasses().map((x) => x.getName())).not.toContain("Wuhu"); expect(source.getClasses().map((x) => x.getName())).not.toContain("FooBar"); }); it("should generate with child info", () => { invokeClassDeclarationGenerator( source, { FooBar: { info: { name: "FooBar", }, parent: null, children: ["Wuhu"], generated: false, }, Wuhu: { info: { name: "Wuhu", }, parent: "FooBar", children: ["WuhuChild"], generated: false, }, WuhuChild: { info: { name: "WuhuChild", }, parent: "Wuhu", children: [], generated: false, }, }, true ); expect(source.getClasses().map((x) => x.getName())).toContain("FooBar"); expect(source.getClasses().map((x) => x.getName())).toContain("Wuhu"); expect(source.getClasses().map((x) => x.getName())).toContain("WuhuChild"); }); it("should check exist class", () => { expect(checkExistClassDeclarations(source)).toEqual(["Foo", "Bar"]); }); it("should remove named imports member", () => { removeNamedImportsMember(source, ["Scope"], "ts-morph"); expect( source .getImportDeclaration( (imp) => imp.getModuleSpecifierValue() === "ts-morph" )! .getNamedImports() .map((x) => x.getName()) ).not.toContain("Scope"); expect( source .getImportDeclaration( (imp) => imp.getModuleSpecifierValue() === "ts-morph" )! .getNamedImports() .map((x) => x.getName()) ).toContain("SyntaxKind"); }); it("should set named imports member", () => { setNamedImportsMember(source, ["Decorator"], "ts-morph", true); expect( source .getImportDeclaration( (imp) => imp.getModuleSpecifierValue() === "ts-morph" )! .getNamedImports() .map((x) => x.getName()) ).toEqual(["Decorator"]); }); it("should remove import declaration", () => { removeImportDeclarations(source, "ts-morph", true); expect( source.getImportDeclarations().map((imp) => imp.getModuleSpecifierValue()) ).not.toContain("ts-morph"); }); it("should add named imports", () => { // exist appendNamedImportsMember(source, ["SyntaxKind"], "ts-morph", true); // new appendNamedImportsMember(source, ["Decorator"], "ts-morph", true); expect( source .getImportDeclaration( (imp) => imp.getModuleSpecifierValue() === "ts-morph" )! .getNamedImports() .map((x) => x.getName()) ).toEqual(["Scope", "SyntaxKind", "Decorator"]); }); it("should add import declaration", () => { addImportDeclaration( source, "prettier", "prettier", ImportType.NAMESPACE_IMPORT, true ); addImportDeclaration( source, undefined, "reflect-metadata", ImportType.DEFAULT_IMPORT, true ); addImportDeclaration( source, ["green"], "chalk", ImportType.NAMED_IMPORTS, true ); const allImps = source .getImportDeclarations() .map((imp) => imp.getModuleSpecifierValue()); expect(allImps).toContain("prettier"); expect(allImps).toContain("reflect-metadata"); expect(allImps).toContain("chalk"); expect( source .getImportDeclaration( (imp) => imp.getModuleSpecifierValue() === "prettier" )! .getNamespaceImport() ?.getText() ).toEqual("prettier"); expect( source .getImportDeclaration( (imp) => imp.getModuleSpecifierValue() === "reflect-metadata" )! .getDefaultImport() ?.getText() ).toBeUndefined; expect( source .getImportDeclaration( (imp) => imp.getModuleSpecifierValue() === "chalk" )! .getNamedImports() .map((x) => x.getText()) ).toEqual(["green"]); }); it("should remove class declaration", () => { removeClassDeclarations(source, ["Foo"], true); expect(source.getClasses().map((cls) => cls.getName()!)).not.toContain( "Foo" ); expect(source.getClasses().map((cls) => cls.getName()!)).toContain("Bar"); }); it("should create class declarations", () => { classDeclarationGeneratorFromList( source, [{ name: "FooBar" }, { name: "Wuhu" }], true ); expect(source.getClasses().map((cls) => cls.getName()!)).toContain( "FooBar" ); expect(source.getClasses().map((cls) => cls.getName()!)).toContain("Wuhu"); }); it("should create tmp resolver content", () => { createTmpResolverContent( source, { buildSchemaOptions: { emitSchemaFile: true, nullableByDefault: true, dateScalarMode: "timestamp", }, disable: false, keep: true, execaOptions: {}, executeOptions: {}, }, "Root" ); expect( source.getImportDeclaration( (x) => x.getModuleSpecifierValue() === CHECKER_MODULE_SPECIFIER ) ).toBeDefined(); expect( source .getImportDeclaration( (x) => x.getModuleSpecifierValue() === CHECKER_MODULE_SPECIFIER ) ?.getDefaultImport() ?.getText() ).toBeUndefined(); // expect( // source // .getImportDeclaration( // (x) => x.getModuleSpecifierValue() === BASE_MODULE_SPECIFIER // ) // ?.getNamedImports() // .map((x) => x.getText()) // ).toEqual(CHECKER_IMPORTS); const tmpClass = source.getClass((cls) => cls.getName() === "TmpResolver"); expect(tmpClass).toBeDefined(); expect(tmpClass?.getDecorator("Resolver")).toBeDefined(); expect( tmpClass ?.getDecorator("Resolver") ?.getArguments() .map((x) => x.getText())[0] ).toBe(`(type)=>Root`); expect(tmpClass?.getMethod("TmpResolver")).toBeDefined(); expect(tmpClass?.getMethod("TmpResolver")?.isAsync()).toBeTruthy(); expect( tmpClass?.getMethod("TmpResolver")?.getDecorator("Query") ).toBeDefined(); expect( tmpClass ?.getMethod("TmpResolver") ?.getDecorator("Query") ?.getArguments() .map((x) => x.getText())[0] ).toBe(`(type)=>[Root]`); expect(tmpClass?.getMethods().map((x) => x.getName())[0]).toBe( "TmpResolver" ); }); });
LinbuduLab/json-to-type-graphql
tests/reader.test.ts
import path from "path"; import fs from "fs-extra"; import { reader } from "../src/reader"; describe("should read content from various sources", () => { it("should throw when no options provided", async () => { await expect(reader()).rejects.toThrow("You must provide reader options!"); }); it("should throw when incorrect options provided", async () => { // @ts-ignore await expect(reader({ x: "xxx" })).rejects.toThrow( "You must provide oneof path/url/raw to get origin JSON content!" ); }); it("should read from JSON file", async () => { const raw = await reader({ path: path.resolve(__dirname, "./fixtures/simple.json"), }); expect(raw).not.toBeNull(); expect(typeof raw).toBe("object"); expect(Object.keys(raw).length).toBeGreaterThan(0); }); it("should read from JSON file(array-entry)", async () => { const raw = await reader({ path: path.resolve(__dirname, "./fixtures/array-entry.json"), }); expect(raw).not.toBeNull(); expect(Array.isArray(raw)).toBe(true); expect(raw.length).toBeGreaterThan(0); }); it("should read from raw object", async () => { const data = { stringField: "linbudu", numberField: 599, booleanField: true, }; expect(await reader({ raw: data })).toMatchObject(data); }); it("should read from request", async () => { const fetched = await reader({ url: "https://dog.ceo/api/breeds/image/random", }); expect(fetched).toBeDefined(); expect(typeof fetched).toBe("object"); expect(typeof fetched.message).toBe("string"); expect(typeof fetched.status).toBe("string"); }); });
LinbuduLab/json-to-type-graphql
src/ast.ts
import type { ClassDeclaration, SourceFile, Statement, ts } from "ts-morph"; import { ensureArray, BASE_MODULE_SPECIFIER, CHECKER_IMPORTS, CHECKER_MODULE_SPECIFIER, CheckerOptions, } from "./utils"; import type { ClassGeneratorRecord, ClassInfo } from "./utils"; /** Global record for class declaration generation */ let collectedInfoRecord: ClassGeneratorRecord = {}; /** * Start class declaration generation from reversed record * @param source Source * @param record Generation record * @param apply Should apply change directly to the source file * @description Current generation order: `P - C1 - C1-1 - C2 - C2-1 - C3`, * will support `P - C1 - C2 - C3 - C1-1 - C1-2 in the future` */ export function invokeClassDeclarationGenerator( source: SourceFile, record: ClassGeneratorRecord, apply?: boolean ) { collectedInfoRecord = record; classDeclarationGenerator(source, record, apply); } /** * Traverse the global record to generate class declarations * Will execute recursively if record item containes non-empty children prop * @param source Source * @param record Generation record * @param apply Should apply change directly to the source file */ export function classDeclarationGenerator( source: SourceFile, record: ClassGeneratorRecord, apply?: boolean ): void { for (const [k, v] of Object.entries(record)) { !v?.generated && source.addClass(v.info); v.generated = true; if (v.children.length) { for (const child of v.children) { classDeclarationGenerator( source, { [child]: collectedInfoRecord[child], }, apply ); } } } apply && source.saveSync(); } /** * Check exist class declaration in current source file * @param source Source * @return List of exist class declaration specifier. */ export function checkExistClassDeclarations(source: SourceFile): string[] { return source.getClasses().map((x) => x.getName()!); } /** * Remove named imports from specific import * @param source * @param namedImportsToRemove * @param moduleSpecifier * @param apply */ export function removeNamedImportsMember( source: SourceFile, namedImportsToRemove: string[], moduleSpecifier: string, apply?: boolean ) { const target = source.getImportDeclaration( (dec) => dec.getModuleSpecifierValue() === moduleSpecifier ); const existNamedImports = target?.getNamedImports(); const remainedNamedImports = existNamedImports ?.filter((imp) => !namedImportsToRemove.includes(imp.getText())) .map((i) => i.getText()) ?? []; setNamedImportsMember(source, remainedNamedImports, moduleSpecifier, false); apply && source.saveSync(); } /** * Directly set named imports member, exist named imports will be removed. * @param source Source * @param namedImports New named imports to set * @param moduleSpecifier The import declaration to operate * @param apply Should apply change directly to the source file */ export function setNamedImportsMember( source: SourceFile, namedImports: string[], moduleSpecifier: string, apply?: boolean ) { const target = source.getImportDeclaration( (dec) => dec.getModuleSpecifierValue() === moduleSpecifier ); target?.removeNamedImports(); target?.addNamedImports(namedImports); apply && source.saveSync(); } /** * Remove specific import declarations * @param source * @param specifier * @param apply */ export function removeImportDeclarations( source: SourceFile, specifier: string | string[], apply?: boolean ) { const specifierList = ensureArray(specifier); source .getImportDeclarations() .filter((imp) => specifierList.includes(imp.getModuleSpecifierValue())) .forEach((imp) => imp.remove()); apply && source.saveSync(); } /** * Append new named imports member * @param source Source * @param namedImports New named imports to append * @param moduleSpecifier The import declaration to operate * @param apply Should apply change directly to the source file */ export function appendNamedImportsMember( source: SourceFile, namedImports: string[], moduleSpecifier: string, apply?: boolean ) { const target = source.getImportDeclaration( (dec) => dec.getModuleSpecifierValue() === moduleSpecifier ); const existNamedImports = target ?.getNamedImports() .map((imp) => imp.getText()); const namedImportsToAppend = namedImports.filter( (imp) => !existNamedImports?.includes(imp) ); target?.addNamedImports(namedImportsToAppend); apply && source.saveSync(); } export enum ImportType { NAMESPACE_IMPORT = "NAMESPACE_IMPORT", NAMED_IMPORTS = "NAMED_IMPORTS", DEFAULT_IMPORT = "DEFAULT_IMPORT", } /** * Add a namespace import declaration in source file * @param source Source * @param namespace Namespace import * @param moduleSpecifier The import declaration to operate */ export function addImportDeclaration( source: SourceFile, namespace: string, moduleSpecifier: string, importType: ImportType.NAMESPACE_IMPORT, apply?: boolean ): void; /** * Add a named import declaration in source file * @param source Source * @param namedImports Named imports * @param moduleSpecifier The import declaration to operate */ export function addImportDeclaration( source: SourceFile, namedImports: string[], moduleSpecifier: string, importType: ImportType.NAMED_IMPORTS, apply?: boolean ): void; /** * Add a default import declaration in source file * @param source Source * @param defaultImport Default import * @param moduleSpecifier The import declaration to operate */ export function addImportDeclaration( source: SourceFile, defaultImport: string | undefined, moduleSpecifier: string, importType: ImportType.DEFAULT_IMPORT, apply?: boolean ): void; export function addImportDeclaration( source: SourceFile, importClause: string | undefined | string[], moduleSpecifier: string, importType: ImportType, apply?: boolean ) { switch (importType) { case ImportType.DEFAULT_IMPORT: source.addImportDeclaration({ defaultImport: importClause as string, moduleSpecifier, }); break; case ImportType.NAMED_IMPORTS: source.addImportDeclaration({ namedImports: ensureArray(importClause as string), moduleSpecifier, }); break; case ImportType.NAMESPACE_IMPORT: source.addImportDeclaration({ namespaceImport: importClause as string, moduleSpecifier: moduleSpecifier, }); break; } apply && source.saveSync(); } /** * Generate class declarations from list * @param source * @param list * @param apply */ export function classDeclarationGeneratorFromList( source: SourceFile, list: ClassInfo[], apply?: boolean ): void { list.forEach((classInfo) => source.addClass(classInfo)); apply && source.saveSync(); } /** * Remove class declarations by name list * @param source * @param names * @param apply */ export function removeClassDeclarations( source: SourceFile, names: string[], apply?: boolean ): void { source .getClasses() .filter((classDec) => names.includes(classDec.getName()!)) .forEach((classDec) => { classDec.remove(); }); apply && source.saveSync(); } /** * Add resolver related import, create resolver class, add buildSchemaSync * @param source * @param rootType * @returns */ export function createTmpResolverContent( source: SourceFile, checkerOptions: CheckerOptions, rootType: string ): { resolverClass: ClassDeclaration; buildSchemaStatements: Statement<ts.Statement>[]; } { addImportDeclaration( source, undefined, CHECKER_MODULE_SPECIFIER, ImportType.DEFAULT_IMPORT ); appendNamedImportsMember(source, CHECKER_IMPORTS, BASE_MODULE_SPECIFIER); const resolverClass = source.addClass({ name: "TmpResolver", isExported: true, decorators: [ { name: "Resolver", arguments: [`(type)=>${rootType}`], }, ], methods: [ { name: "TmpResolver", isAsync: true, statements: ["return [];"], decorators: [ { name: "Query", arguments: [`(type)=>[${rootType}]`], }, ], returnType: `Promise<${rootType}[]>`, }, ], }); // TODO: enhancement const buildSchemaStatements = source.addStatements([ ` buildSchemaSync({ resolvers: [TmpResolver], emitSchemaFile: ${checkerOptions.buildSchemaOptions.emitSchemaFile}, skipCheck: false, nullableByDefault: ${checkerOptions.buildSchemaOptions.nullableByDefault}, dateScalarMode: ${checkerOptions.buildSchemaOptions.dateScalarMode} });`, ]); source.saveSync(); return { resolverClass, buildSchemaStatements, }; }
LinbuduLab/json-to-type-graphql
tests/fixtures/ast-fixture.ts
import consola from "consola"; import { Scope, SyntaxKind } from "ts-morph"; class Foo {} class Bar {}
LinbuduLab/json-to-type-graphql
src/postprocessor.ts
<gh_stars>1-10 import { SourceFile } from "ts-morph"; import omit from "lodash/omit"; import type { PostprocessorOptions } from "./utils"; /** * Post-process source file after it's processed by generator. * @param source * @param options * @returns */ export function postprocessor( source: SourceFile, options: PostprocessorOptions ): void { if ( options.customPostprocessor && typeof options.customPostprocessor === "function" ) { options.customPostprocessor(source, omit(options, ["customPostprocessor"])); } // TODO: remove unused decorators // TODO: more... }
LinbuduLab/json-to-type-graphql
tests/writter.test.ts
import { writter } from "../src/writter"; import fs from "fs-extra"; import prettier from "prettier"; import tmp from "tmp"; let tmpFile: string; beforeEach(() => { tmpFile = tmp.fileSync().name; fs.writeFileSync(tmpFile, "const a:string = 'linbudu'"); }); describe("should handle write and format", () => { it("should throw on no output path specified", () => { // @ts-ignore expect(() => writter({})).toThrow("writer.outputPath is required!"); // @ts-ignore expect(() => writter({ outputPath: null })).toThrow( "writer.outputPath is required!" ); }); it("should write", () => { const rfs = jest .spyOn(fs, "readFileSync") .mockReturnValue("const a:string = 'linbudu'"); const wfs = jest.spyOn(fs, "writeFileSync").mockReturnValue(); writter({ outputPath: tmpFile, formatOptions: { singleQuote: true } }); expect(rfs).toBeCalledTimes(1); expect(rfs).toBeCalledWith(tmpFile, "utf-8"); expect(wfs).toBeCalledTimes(1); expect(wfs).toBeCalledWith(tmpFile, "const a:string = 'linbudu'"); }); it("should disable format", () => { const formatter = jest.spyOn(prettier, "format"); writter({ outputPath: tmpFile, format: false }); expect(formatter).not.toBeCalled(); writter({ outputPath: tmpFile, format: true }); expect(formatter).toBeCalledTimes(1); expect(formatter).toBeCalledWith("const a:string = 'linbudu'", { parser: "typescript", tabWidth: 2, }); }); });
LinbuduLab/json-to-type-graphql
tests/fixtures/generated-fixture.ts
<gh_stars>1-10 import { ObjectType, Field, Int, ID } from "type-graphql"; @ObjectType() export class MixedField { @Field() a!: string; } @ObjectType() export class EmptyArrayField {} @ObjectType() export class MixedField1 { @Field({ nullable: true }) a111?: string; } @ObjectType() export class C { @Field((type) => MixedField1, { nullable: true }) mixedField1?: MixedField1; } @ObjectType() export class MixedFieldrs { @Field() b!: string; @Field((type) => C!) c!: C; } @ObjectType() export class NestedField { @Field({ nullable: true }) booleanField?: boolean; @Field((type) => Int, { nullable: true }) numberField?: number; @Field({ nullable: true }) stringField?: string; @Field((type) => [Int], { nullable: true }) primitiveArrayField?: number[]; @Field((type) => [MixedFieldrs], { nullable: true }) mixedFieldrs?: MixedFieldrs[]; } @ObjectType() export class Ff {} @ObjectType() export class Fec { @Field((type) => Int!) feca!: number; @Field() fecb!: boolean; @Field((type) => [String]!) fecc!: string[]; } @ObjectType() export class Fe { @Field((type) => Int, { nullable: true }) fea?: number; @Field((type) => [Int], { nullable: true }) feb?: number[]; @Field((type) => [Fec], { nullable: true }) fec?: Fec[]; } @ObjectType() export class F { @Field((type) => Int!) fa!: number; @Field((type) => Int, { nullable: true }) fb?: number; @Field((type) => Int, { nullable: true }) fc?: number; @Field((type) => [Int], { nullable: true }) fd?: number[]; @Field((type) => [Ff], { nullable: true }) ff?: Ff[]; @Field((type) => Fe, { nullable: true }) fe?: Fe; } @ObjectType() export class Root { @Field({ nullable: true }) booleanField?: boolean; @Field((type) => Int, { nullable: true }) numberField?: number; @Field({ nullable: true }) stringField?: string; @Field((type) => [Int], { nullable: true }) primitiveArrayField?: number[]; @Field((type) => [MixedField], { nullable: true }) mixedField?: MixedField[]; @Field((type) => [EmptyArrayField], { nullable: true }) emptyArrayField?: EmptyArrayField[]; @Field((type) => NestedField, { nullable: true }) nestedField?: NestedField; @Field((type) => [F], { nullable: true }) f?: F[]; }
LinbuduLab/json-to-type-graphql
src/sample/demo.ts
<gh_stars>1-10 import path from "path"; import fs from "fs-extra"; import transformer from ".."; import { reader, parser, generator, checker, writter } from ".."; const outputPath = path.join(__dirname, "./generated.ts"); fs.existsSync(outputPath) && fs.rmSync(outputPath); (async () => { await transformer({ reader: { path: path.join(__dirname, "./demo.json") }, // reader: { path: path.join(__dirname, "./sample.json") }, // reader: { url: "https://dog.ceo/api/breeds/image/random" }, parser: { forceNonNullable: false, forceReturnType: false, forceNonNullableListItem: false, }, generator: { entryClassName: "Root", sort: false }, checker: { disable: false, keep: true, }, writter: { outputPath, }, }); })();
LinbuduLab/json-to-type-graphql
src/reader.ts
import jsonfile from "jsonfile"; import path from "path"; import got, { Options } from "got"; import type { MaybeArray, ReaderOptions, SourceArray, SourceObject, } from "./utils"; /** * Read content from certain resources * @param options * @returns */ export async function reader(options?: ReaderOptions) { // Use Invariant if (!options) { throw new Error("You must provide reader options!"); } if (options.path) return readFromFile(options.path); if (options.url) return await readFromRequest(options.url, options.options); if (options.raw) return options.raw; throw new Error( "You must provide oneof path/url/raw to get origin JSON content!" ); } export function readFromFile(filePath: string) { return jsonfile.readFileSync(filePath, { throws: true }); } export async function readFromRequest(url: string, options?: Options) { const res = await got(url, { responseType: "json", method: "GET", ...options, }); return (res as { body: MaybeArray<SourceObject> | SourceArray }).body; }
igorosabel/Coffee-Frontend
src/app/model/calendar-day.class.ts
<gh_stars>0 import { CalendarDayInterface } from '../interfaces/interfaces'; export class CalendarDay { constructor( public day: number = null, public month: number = null, public year: number = null ) {} toInterface(): CalendarDayInterface { return { day: this.day, month: this.month, year: this.year }; } }
igorosabel/Coffee-Frontend
src/app/pipes/format-num.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'formatNum' }) export class FormatNumPipe implements PipeTransform { transform(num: string): string { const check = parseInt(num); return (check<10) ? '0' + check : check.toString(); } }
igorosabel/Coffee-Frontend
src/app/pages/people/people.component.ts
import { Component, ViewChild, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { ColorsComponent } from '../../components/colors/colors.component'; import { ApiService } from '../../services/api.service'; import { DataShareService } from '../../services/data-share.service'; import { PeopleResult } from '../../model/people-result.class'; @Component({ selector: 'app-people', templateUrl: './people.component.html', styleUrls: [] }) export class PeopleComponent implements OnInit { @ViewChild('colors', { static: true }) colors : ColorsComponent; people = {}; peopleList: PeopleResult[] = []; constructor(private as: ApiService, private dss: DataShareService, private router: Router) {} ngOnInit() { if (this.dss.getGlobal('people') === null) { this.as.getPeople().subscribe(result => { this.people = result.people; this.dss.setGlobal('people', this.people); this.loadPeopleList(); }); } else { this.people = this.dss.getGlobal('people'); this.loadPeopleList(); } } loadPeopleList() { for (let person in this.people) { this.peopleList.push( this.people[person] ); } this.colors.loadColors(this.peopleList); } editPerson(id) { this.router.navigate(['/edit-person', id]); } }
igorosabel/Coffee-Frontend
src/app/components/calendar/calendar.component.ts
import { Component, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'calendar', templateUrl: './calendar.component.html', styleUrls: ['./calendar.component.scss'] }) export class CalendarComponent { @Output() select = new EventEmitter(); @Output() change = new EventEmitter(); months: string[] = ['Urtarrila','Otsaila','Martxoa','Apirila','Maiatza','Ekaina','Uztaila','Abuztua','Iraila','Urria','Azaroa','Abendua']; days: string[] = ['Astelehena','Asteartea','Asteazkena','Osteguna','Ostirala','Larunbata','Igandea']; daysShort: string[] = ['Asl','Ast','Asz','Ost','Osi','Lar','Iga']; day: number = null; month: number = null; year: number = null; events = []; marked = {}; currentMonth: string = null; currentYear: number = null; headerDays: string[] = []; headerDaysShort: string[] = []; rows = []; constructor() {} selectDay(d) { this.select.emit({day: d.day, month: this.month+1, year: this.year}); } setDate(d) { this.day = d.day; this.month = d.month; this.year = d.year; } getDate() { return {day: this.day, month: this.month, year: this.year}; } setEvents(events) { this.rows = []; this.events = events; this.marked = {}; this.events.forEach(element => this.marked[element.d] = element); } previousMonth(ev) { ev.preventDefault(); this.month--; if (this.month==-1) { this.month = 11; this.year--; } this.setEvents([]); this.change.emit(this.getDate()); } nextMonth(ev) { ev.preventDefault(); this.month++; if (this.month==12) { this.month = 0; this.year++; } this.setEvents([]); this.change.emit(this.getDate()); } header() { this.currentMonth = this.months[this.month]; this.currentYear = this.year; this.headerDays = this.days; this.headerDaysShort = this.daysShort; } otherMonthDay(day) { return {class:'calendar-day-other', day: day}; } currentMonthDay(day) { const now = new Date(); let today = (this.year===now.getFullYear() && this.month===now.getMonth() && this.day===day) ? ' calendar-today' : ''; let marked = ''; if (this.marked[day] && this.marked[day].list && this.marked[day].list.length==1) { marked = ' person_' + this.marked[day].list[0].id_person; } return { class: 'calendar-day calendar-clickable' + today + marked, day: day, events: this.marked[day] }; } draw() { // Obtengo el primer día del mes y el primer día de la semana const firstDay = new Date(this.year, this.month, 1); const firstDayWeekday = firstDay.getDay() === 0 ? 7 : firstDay.getDay(); // Obtengo número de días en el mes const monthLength = new Date(this.year, this.month+1, 0).getDate(); const previousMonthLength = new Date(this.year, this.month, 0).getDate(); // Cabecera del calendario this.header(); // Contenido del calendario // Variables con valores por defecto para los días let day = 1; // Día actual del mes let prev = 1; // Días del mes anterior let next = 1; // Días del mes siguiente let nextMonth = false; // Bucle de semanas (filas) for (let i = 0; i < 9; i++) { if (nextMonth) { continue; } let days = []; // Bucle días de la semana (celdas) for (let j = 1; j <= 7; j++) { if (day <= monthLength && (i > 0 || j >= firstDayWeekday)) { // Mes actual days.push( this.currentMonthDay(day) ); day++; } else { if (day <= monthLength) { // Mes anterior days.push( this.otherMonthDay( previousMonthLength - firstDayWeekday + prev + 1 ) ); prev++; } else { // Mes siguiente days.push( this.otherMonthDay(next) ); next++; nextMonth = true; } } } this.rows.push(days); } console.log(this.rows); } }
igorosabel/Coffee-Frontend
src/app/services/class-mapper.service.ts
<reponame>igorosabel/Coffee-Frontend import { Injectable } from '@angular/core'; import { CalendarDay } from '../model/calendar-day.class'; import { MonthResult } from '../model/month-result.class'; import { MonthDayResult } from '../model/month-day-result.class'; import { DayResult } from '../model/day-result.class'; import { PeopleResult } from '../model/people-result.class'; import { CalendarDayInterface, MonthResultInterface, MonthDayResultInterface, DayResultInterface, PeopleResultInterface } from '../interfaces/interfaces'; @Injectable({ providedIn: 'root' }) export class ClassMapperService { constructor() {} getCalendarDay(cd: CalendarDayInterface): CalendarDay { return new CalendarDay( cd.day, cd.month, cd.year ); } getMonth(m: MonthResultInterface): MonthResult { const dayList: MonthDayResult[] = []; for (let d of m.list) { dayList.push( this.getMonthDay(d) ); } return new MonthResult( m.status, m.m, m.y, dayList ); } getMonthDay(d: MonthDayResultInterface): MonthDayResult { const dayList: DayResult[] = []; for (let i of d.list) { dayList.push( this.getDay(i) ); } return new MonthDayResult( d.d, dayList ); } getDay(i: DayResultInterface): DayResult { return new DayResult( i.id, i.id_person, i.people ); } getPeople(list: any): PeopleResult[] { const people: PeopleResult[] = []; console.log(list); for (let p of list) { people.push( this.getPeopleResult(p) ); } return people; } getPeopleResult(p: PeopleResultInterface): PeopleResult { return new PeopleResult( p.id, p.name, p.num_coffee, p.num_pay, p.num_special, p.num_special_pay, p.color, p.did_go ); } }
igorosabel/Coffee-Frontend
src/app/pages/day/day.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { CalendarDay } from '../../model/calendar-day.class'; import { PeopleResult } from '../../model/people-result.class'; import { ApiService } from '../../services/api.service'; import { DataShareService } from '../../services/data-share.service'; import { DialogService } from '../../services/dialog.service'; import { DialogOptions } from '../../interfaces/interfaces'; @Component({ selector: 'detail', templateUrl: './day.component.html', styleUrls: [] }) export class DayComponent implements OnInit { day: CalendarDay = new CalendarDay(); idCoffee: number = 0; special: boolean = false; people = {}; peopleList: PeopleResult[] = []; payed: number = null; sending: boolean = false; constructor(private as: ApiService, private dss: DataShareService, private dialog: DialogService, private router: Router) {} ngOnInit() { this.idCoffee = this.dss.getGlobal('idDay'); this.day = this.dss.getGlobal('day'); const date = new Date(this.day.year, this.day.month-1, this.day.day); this.special = (date.getDay()===5); if (this.idCoffee===null) { this.as.getDay(this.day.toInterface()).subscribe(result => { this.idCoffee = result.id_coffee; this.payed = result.id_pay; this.people = result.list; this.loadPeopleList(); }); } else { this.as.getCoffee(this.idCoffee).subscribe(result => { this.idCoffee = result.id_coffee; this.payed = result.id_pay; this.people = result.list; this.loadPeopleList(); }); } } loadPeopleList() { for (let person in this.people) { this.peopleList.push( this.people[person] ); } } back() { this.dss.removeGlobal('day'); this.router.navigate(['/']); } save() { let ok = false; for (let i in this.peopleList) { if (this.peopleList[i].did_go) { ok = true; break; } } if (!ok) { this.dialog.alert({title: 'Errorea', content: 'Ez da inor joan kafera?', ok: 'Ados'}); return false; } if (this.payed===null) { this.dialog.alert({title: 'Errorea', content: 'Ez du inor ordaindu?', ok: 'Ados'}); return false; } this.sending = true; const saveObj = { id: this.idCoffee, d: this.day.day, m: this.day.month, y: this.day.year, special: this.special, id_pay: this.payed, list: [] }; for (let i in this.peopleList) { if (this.peopleList[i].did_go) { saveObj.list.push(this.peopleList[i].id); } } this.as.saveCoffee(saveObj).subscribe(result => { if (result.status==='ok') { this.dss.removeGlobal('events'); this.router.navigate(['/']); } else { this.dialog.alert({title: 'Errorea', content: 'Akats bat gertatu da datuak gordetzerakoan.', ok: 'Ados'}); } }); } deleteDay() { this.dialog.confirm({title: 'Kafea ezabatu', content: 'Ziur zaude kafe hau ezabatu nahi duzula?', ok: 'Ados', cancel: 'Utzi'}) .subscribe(result => { if (result===true) { this.as.deleteCoffee(this.idCoffee).subscribe(result => { this.dss.removeGlobal('events'); this.back(); }); } }); } addNew() { this.idCoffee = 0; for (let i in this.peopleList) { this.peopleList[i].did_go = false; } this.payed = null; } }
igorosabel/Coffee-Frontend
src/app/model/month-result.class.ts
import { MonthDayResult } from './month-day-result.class'; import { MonthResultInterface, MonthDayResultInterface } from '../interfaces/interfaces'; export class MonthResult { constructor( public status: string = null, public m: number = null, public y: number = null, public list: MonthDayResult[] = [] ) {} toInterface(): MonthResultInterface { const list: MonthDayResultInterface[] = []; for (let md of this.list) { list.push(md.toInterface()); } return { status: this.status, m: this.m, y: this.y, list: list } } }
igorosabel/Coffee-Frontend
src/app/components/colors/colors.component.ts
<reponame>igorosabel/Coffee-Frontend<filename>src/app/components/colors/colors.component.ts import { Component, Inject } from '@angular/core'; import { DOCUMENT } from "@angular/common"; import { CommonService } from '../../services/common.service'; @Component({ selector: 'colors', template: '', styleUrls: [] }) export class ColorsComponent { css: string = ''; constructor(@Inject(DOCUMENT) private document, private common: CommonService) { } loadColors(peopleList){ for (let i in peopleList){ this.css += ` .person_${peopleList[i].id}{ color: ${this.common.invertColor(peopleList[i].color,true)} !important; background-color: ${peopleList[i].color} !important; width: 100%; height: 42px; margin-top: 3px; padding-left: 10px; display: flex; align-items: center; } `; } const st = this.document.createElement('style'); st.type = 'text/css'; st.innerHTML = this.css; this.document.querySelector('head').appendChild(st); } }
igorosabel/Coffee-Frontend
src/app/model/day.class.ts
<filename>src/app/model/day.class.ts export class Day { constructor( public css: string = null, public day: number = null, public events: ) { } }
igorosabel/Coffee-Frontend
src/app/pages/edit-person/edit-person.component.ts
<filename>src/app/pages/edit-person/edit-person.component.ts import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { ApiService } from '../../services/api.service'; import { DataShareService } from '../../services/data-share.service'; import { DialogService } from '../../services/dialog.service'; import { Person } from '../../interfaces/interfaces'; @Component({ selector: 'app-edit-person', templateUrl: './edit-person.component.html', styleUrls: [] }) export class EditPersonComponent implements OnInit { id: number; private sub: any; name: string = ''; color: string = '#ffffff'; sending: boolean = false; people = {}; constructor(private as: ApiService, private dss: DataShareService, private dialog: DialogService, private route: ActivatedRoute, private router: Router) { } ngOnInit() { this.sub = this.route.params.subscribe(params => { this.id = params['id']; this.loadPerson(); }); } loadPerson() { if (this.dss.getGlobal('people') === null) { this.as.getPeople().subscribe(result => { this.people = result.people; this.dss.setGlobal('people', this.people); this.loadPerson(); }); } else { if (!this.people['person_'+this.id]) { this.dss.removeGlobal('people'); this.loadPerson(); } else { this.name = this.people['person_'+this.id].name; this.color = this.people['person_'+this.id].color; } } } save() { if (this.name==='') { this.dialog.alert({title: 'Errorea', content: 'Izena ezinbestekoa da!', ok: 'Ados'}); return false; } if (this.color==='') { this.dialog.alert({title: 'Errorea', content: 'Kolore bat aukeratu behar duzu!', ok: 'Ados'}); return false; } this.sending = true; const person: Person = { id: this.id, name: this.name, color: this.color } this.as.savePerson(person).subscribe(result => { this.sending = false; if (result.status==='ok') { this.dss.removeGlobal('people') this.router.navigate(['/people']); } else { this.dialog.alert({title: 'Errorea', content: 'Errore bat gertatu da kafezalea editatzerakoan!', ok: 'Ados'}); } }); } deletePerson() { this.dialog.confirm({title: 'Kafezalea ezabatu', content: 'Ziur zaude pertsona hau ezabatu nahi duzula?', ok: 'Ados', cancel: 'Utzi'}) .subscribe(result => { if (result===true) { this.as.deletePerson(this.id).subscribe(result => { this.dss.removeGlobal('people'); this.router.navigate(['/people']); }); } }); } }
igorosabel/Coffee-Frontend
src/app/model/month-day-result.class.ts
<gh_stars>0 import { DayResult } from './day-result.class'; import { DayResultInterface, MonthDayResultInterface } from '../interfaces/interfaces'; export class MonthDayResult { constructor( public d: number = null, public list: DayResult[] = [] ) {} toInterface(): MonthDayResultInterface { const list: DayResultInterface[] = []; for (let d of this.list) { list.push(d.toInterface()); } return { d: this.d, list: list }; } }
igorosabel/Coffee-Frontend
src/app/model/people-result.class.ts
<filename>src/app/model/people-result.class.ts<gh_stars>0 import { PeopleResultInterface } from '../interfaces/interfaces'; export class PeopleResult { constructor( public id: number = null, public name: string = null, public num_coffee: number = null, public num_pay: number = null, public num_special: number = null, public num_special_pay: number = null, public color: string = null, public did_go: boolean = false ) {} toInterface(): PeopleResultInterface { return { id: this.id, name: this.name, num_coffee: this.num_coffee, num_pay: this.num_pay, num_special: this.num_special, num_special_pay: this.num_special_pay, color: this.color, did_go: this.did_go }; } }
igorosabel/Coffee-Frontend
src/app/services/common.service.ts
import { Injectable } from '@angular/core'; @Injectable() export class CommonService { constructor() {} urldecode(str) { if (!str){ return ''; } return decodeURIComponent( str.replace( /\+/g, '%20' ).replace( /\%21/g, '!' ).replace( /\%27/g, "'" ).replace( /\%28/g, '(' ).replace( /\%29/g, ')' ).replace( /\%2A/g, '*' ).replace( /\%7E/g, '~' ) ); } invertColor(hex, bw) { if (hex.indexOf('#') === 0) { hex = hex.slice(1); } // convert 3-digit hex to 6-digits. if (hex.length === 3) { hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; } if (hex.length !== 6) { throw new Error('Invalid HEX color.'); } let r = parseInt(hex.slice(0, 2), 16), g = parseInt(hex.slice(2, 4), 16), b = parseInt(hex.slice(4, 6), 16); if (bw) { return (r * 0.299 + g * 0.587 + b * 0.114) > 186 ? '#000000' : '#FFFFFF'; } // invert color components const newR = (255 - r).toString(16); const newG = (255 - g).toString(16); const newB = (255 - b).toString(16); // pad each with zeros and return return "#" + this.padZero(newR) + this.padZero(newG) + this.padZero(newB); } padZero(str) { const len = 2; let zeros = new Array(len).join('0'); return (zeros + str).slice(-len); } }
igorosabel/Coffee-Frontend
src/app/pages/add-person/add-person.component.ts
import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { ApiService } from '../../services/api.service'; import { DataShareService } from '../../services/data-share.service'; import { DialogService } from '../../services/dialog.service'; import { Person } from '../../interfaces/interfaces'; @Component({ selector: 'app-add-person', templateUrl: './add-person.component.html', styleUrls: [] }) export class AddPersonComponent { name: string = ''; color: string = '#ffffff'; sending: boolean = false; constructor(private as: ApiService, private dss: DataShareService, private dialog: DialogService, private router: Router) {} save() { if (this.name==='') { this.dialog.alert({title: 'Errorea', content: 'Izena ezinbestekoa da!', ok: 'Ados'}); return false; } if (this.color==='') { this.dialog.alert({title: 'Errorea', content: 'Kolore bat aukeratu behar duzu!', ok: 'Ados'}); return false; } this.sending = true; const person: Person = { id: 0, name: this.name, color: this.color } this.as.savePerson(person).subscribe(result => { this.sending = false; if (result.status==='ok') { this.dss.removeGlobal('people') this.router.navigate(['/']); } else { this.dialog.alert({title: 'Errorea', content: 'Errore bat gertatu da kafezale berria gehitzean!', ok: 'Ados'}); } }); } }
igorosabel/Coffee-Frontend
src/app/services/api.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { environment } from '../../environments/environment'; import { MonthResultInterface, PeopleListResult, CoffeeData, StatusResult, CalendarDayInterface, DayData, Person, PersonResult, PersonDetailResult } from '../interfaces/interfaces'; @Injectable() export class ApiService { apiUrl = environment.apiUrl; constructor(private http : HttpClient) {} getMonth(month: number, year: number): Observable<MonthResultInterface> { return this.http.post<MonthResultInterface>(this.apiUrl + 'coffee/get-month-list', {month, year}); } getPeople(): Observable<PeopleListResult> { return this.http.post<PeopleListResult>(this.apiUrl + 'person/get-people', {}); } saveCoffee(coffeData: CoffeeData): Observable<StatusResult> { return this.http.post<StatusResult>(this.apiUrl + 'coffee/save', coffeData); } getDay(day: CalendarDayInterface): Observable<DayData> { return this.http.post<DayData>(this.apiUrl + 'get-day', day); } getCoffee(id: number): Observable<DayData> { return this.http.post<DayData>(this.apiUrl + 'coffee/get', {id}); } deleteCoffee(id: number): Observable<StatusResult> { return this.http.post<StatusResult>(this.apiUrl + 'coffee/delete', {id}); } savePerson(person: Person): Observable<PersonResult> { return this.http.post<PersonResult>(this.apiUrl + 'person/save', person); } deletePerson(id: number): Observable<StatusResult> { return this.http.post<StatusResult>(this.apiUrl + 'person/delete', {id}); } getPerson(id: number): Observable<PersonDetailResult> { return this.http.post<PersonDetailResult>(this.apiUrl + 'person/get', {id}); } }
igorosabel/Coffee-Frontend
src/app/pages/coffee/coffee.component.ts
import { Component, ViewChild, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { CalendarDay } from '../../model/calendar-day.class'; import { MonthDayResult } from '../../model/month-day-result.class'; import { PeopleResult } from '../../model/people-result.class'; import { ColorsComponent } from '../../components/colors/colors.component'; import { CalendarComponent } from '../../components/calendar/calendar.component'; import { ApiService } from '../../services/api.service'; import { DataShareService } from '../../services/data-share.service'; import { ClassMapperService } from '../../services/class-mapper.service'; import { MonthDayResultInterface } from '../../interfaces/interfaces'; @Component({ selector: 'coffee', templateUrl: './coffee.component.html', styleUrls: ['./coffee.component.scss'] }) export class CoffeeComponent implements OnInit { @ViewChild('colors', { static: true }) colors : ColorsComponent; @ViewChild('calendar', { static: true }) calendar : CalendarComponent; data: CalendarDay = new CalendarDay(); events: MonthDayResult[] = []; people = {}; peopleList: PeopleResult[] = []; sortField: string = 'percentage'; sortOrder: string = 'down'; constructor( private as: ApiService, private dss: DataShareService, private cms: ClassMapperService, private router: Router ) {} ngOnInit() { const d = new Date(); this.data = new CalendarDay(d.getDate(), d.getMonth(), d.getFullYear()); if (this.dss.getGlobal('data') === null) { this.dss.setGlobal('data', this.data); } else { const checkData = this.dss.getGlobal('data'); if (this.data.day!==checkData.day || this.data.month!==checkData.month || this.data.year!==checkData.year) { this.dss.resetGlobals(); this.dss.setGlobal('data', this.data); } } if (this.dss.getGlobal('events') === null) { this.as.getMonth(this.data.month + 1, this.data.year).subscribe(result => { const resultData = this.cms.getMonth(result); this.events = resultData.list; this.dss.setGlobal('events', this.events); this.startCalendar(); }); } else { this.events = this.dss.getGlobal('events'); this.startCalendar(); } if (this.dss.getGlobal('people') === null) { this.as.getPeople().subscribe(result => { console.log(result); this.people = this.cms.getPeople(result.people); console.log(this.people); this.dss.setGlobal('people', this.people); this.loadPeopleList(); }); } else { this.people = this.dss.getGlobal('people'); this.loadPeopleList(); } } startCalendar() { this.calendar.setDate(this.data); this.calendar.setEvents(this.events); this.calendar.draw(); } loadPeopleList() { for(let person in this.people) { this.peopleList.push( this.people[person] ); } this.colors.loadColors(this.peopleList); } newDay() { const d = new Date(); const day = <CalendarDay>{ day: d.getDate(), month: d.getMonth()+1, year: d.getFullYear() }; this.dss.setGlobal('day', day); this.router.navigate(['/day']); } selectDay(ev) { const day = this.events.find(function (obj) { return obj.d === ev.day; }); this.dss.setGlobal('day', ev); if (day && day.list.length>1) { this.router.navigate(['/day-list']); } else { if (day) { this.dss.setGlobal('idDay', day.list[0].id); } else { this.dss.setGlobal('idDay', null); } this.router.navigate(['/day']); } } changeMonth(ev) { this.dss.removeGlobal('data'); this.dss.removeGlobal('events'); this.data = ev; this.dss.setGlobal('data', this.data); this.as.getMonth(this.data.month+1, this.data.year).subscribe(result => { const resultData = this.cms.getMonth(result); this.events = resultData.list; this.dss.setGlobal('events', this.events); this.startCalendar(); }); } listOrder() { if (this.sortField=='percentage') { if (this.sortOrder=='down') { this.peopleList.sort((a, b) => { return (b.num_pay / b.num_coffee) - (a.num_pay / a.num_coffee); }); } if (this.sortOrder=='up') { this.peopleList.sort((a, b) => { return (a.num_pay / a.num_coffee) - (b.num_pay / b.num_coffee); }); } } if (this.sortField=='special') { if (this.sortOrder=='down') { this.peopleList.sort((a, b) => { return (b.num_special_pay / b.num_special) - (a.num_special_pay / a.num_special); }); } if (this.sortOrder=='up') { this.peopleList.sort((a, b) => { return (a.num_special_pay / a.num_special) - (b.num_special_pay / b.num_special); }); } } } changeOrder(mode, ev) { ev.preventDefault(); this.sortField = mode; this.sortOrder = (this.sortOrder=='up') ? 'down' : 'up'; this.listOrder(); } goToPerson(id) { this.router.navigate(['/person', id]); } }
igorosabel/Coffee-Frontend
src/app/pages/person/person.component.ts
<gh_stars>0 import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { ApiService } from '../../services/api.service'; import { DataShareService } from '../../services/data-share.service'; import { CommonService } from '../../services/common.service'; @Component({ selector: 'app-person', templateUrl: './person.component.html', styleUrls: [] }) export class PersonComponent implements OnInit { id: number; private sub: any; name: string = ''; color: string = '#000'; headerColor: string = '#fff'; coffees = []; constructor(private common: CommonService, private as: ApiService, private dss: DataShareService, private route: ActivatedRoute) {} ngOnInit() { this.sub = this.route.params.subscribe(params => { this.id = params['id']; this.as.getPerson(this.id).subscribe(result => { this.name = this.common.urldecode(result.name); this.color = this.common.urldecode(result.color); this.headerColor = this.common.invertColor(this.color,true); let list = []; for (let i in result.list){ list.push({ id: result.list[i].id, d: result.list[i].d, m: result.list[i].m, y: result.list[i].y, special: result.list[i].special, pay: (result.list[i].id_person===this.id) }); } this.coffees = list; }); }); } }
igorosabel/Coffee-Frontend
src/app/interfaces/interfaces.ts
export interface MonthResultInterface { status: string; m: number; y: number; list: MonthDayResultInterface[]; } export interface MonthDayResultInterface { d: number; list: DayResultInterface[]; } export interface DayResultInterface { id: number; id_person: number; people: number[]; } export interface PeopleListResult { [key: string]: PeopleResultInterface; } export interface PeopleResultInterface { id: number; name: string; num_coffee: number; num_pay: number; num_special: number; num_special_pay: number; color: string; did_go: boolean; } export interface CalendarDayInterface { day: number; month: number; year: number; } export interface DialogOptions { title: string; content: string; ok: string; cancel?: string; } export interface CoffeeData { id: number; d: number; m: number; y: number; special: boolean; id_pay: number; list: number[]; } export interface StatusResult { status: string; } export interface DayData { status: string; d: number; m: number; y: number; id_coffee: number; special: boolean; id_pay: number; list: PeopleResultInterface[]; } export interface Person { id: number; name: string; color: string; } export interface PersonResult { status: string; id: number; } export interface PersonDetailResult { status: string; id: number; name: string; color: string; list: PersonCoffee[]; } export interface PersonCoffee { id: number; d: number; m: number; y: number; special: boolean; id_person: number; }
igorosabel/Coffee-Frontend
src/app/pages/day-list/day-list.component.ts
<filename>src/app/pages/day-list/day-list.component.ts import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { CalendarDay } from '../../model/calendar-day.class'; import { ApiService } from '../../services/api.service'; import { DataShareService } from '../../services/data-share.service'; import { MonthDayResultInterface } from '../../interfaces/interfaces'; @Component({ selector: 'app-day-list', templateUrl: './day-list.component.html', styleUrls: [] }) export class DayListComponent implements OnInit { day: CalendarDay = new CalendarDay(0, 0, 0); events: MonthDayResultInterface[] = []; people = {}; selectedDay: MonthDayResultInterface; constructor(private as: ApiService, private dss: DataShareService, private router: Router) {} ngOnInit() { this.day = <CalendarDay> this.dss.getGlobal('day'); if (this.dss.getGlobal('events') === null) { this.as.getMonth(this.day.month+1, this.day.year).subscribe(result => { this.events = result.list; this.dss.setGlobal('events', this.events); this.loadPeopleList(); }); } else { this.events = this.dss.getGlobal('events'); this.loadPeopleList(); } } back() { this.dss.removeGlobal('day'); this.router.navigate(['/']); } loadPeopleList() { if (this.dss.getGlobal('people') === null) { this.as.getPeople().subscribe(result => { this.people = result.people; this.dss.setGlobal('people', this.people); this.loadDayList(); }); } else { this.people = this.dss.getGlobal('people'); this.loadDayList(); } } loadDayList() { const check = this.day.day; this.selectedDay = this.events.find(function (obj) { return obj.d === check; }); } goToEvent(id) { this.dss.setGlobal('idDay', id); this.router.navigate(['/day']); } }
igorosabel/Coffee-Frontend
src/app/app.common.ts
<gh_stars>0 /* * Páginas */ import { CoffeeComponent } from './pages/coffee/coffee.component'; import { DayComponent } from './pages/day/day.component'; import { PeopleComponent } from './pages/people/people.component'; import { AddPersonComponent } from './pages/add-person/add-person.component'; import { EditPersonComponent } from './pages/edit-person/edit-person.component'; import { PersonComponent } from './pages/person/person.component'; import { DayListComponent } from './pages/day-list/day-list.component'; export const PAGES: any[] = [ CoffeeComponent, DayComponent, PeopleComponent, AddPersonComponent, EditPersonComponent, PersonComponent, DayListComponent ]; /* * Componentes */ import { CalendarComponent } from './components/calendar/calendar.component'; import { ColorsComponent } from './components/colors/colors.component'; import { ConfirmDialogComponent } from './components/dialogs/confirm-dialog/confirm-dialog.component'; import { AlertDialogComponent } from './components/dialogs/alert-dialog/alert-dialog.component'; export const COMPONENTS: any[] = [ CalendarComponent, ColorsComponent, ConfirmDialogComponent, AlertDialogComponent ]; /* * Pipes */ import { UrldecodePipe } from './pipes/urldecode.pipe'; import { PercentageTotalPipe } from './pipes/percentage-total.pipe'; import { PercentageFridaysPipe } from './pipes/percentage-fridays.pipe'; import { FormatNumPipe } from './pipes/format-num.pipe'; import { PeopleListPipe } from './pipes/people-list.pipe'; import { PeoplePayPipe } from './pipes/people-pay.pipe'; export const PIPES: any[] = [ UrldecodePipe, PercentageTotalPipe, PercentageFridaysPipe, FormatNumPipe, PeopleListPipe, PeopleListPipe, PeoplePayPipe ]; /* * Servicios */ import { CommonService } from './services/common.service'; import { ApiService } from './services/api.service'; import { DataShareService } from './services/data-share.service'; import { DialogService } from './services/dialog.service'; import { ClassMapperService } from './services/class-mapper.service'; export const SERVICES: any[] = [ CommonService, ApiService, DataShareService, DialogService, ClassMapperService ]; /* * Componentes Angular Material */ import { MatToolbarModule } from '@angular/material/toolbar'; import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; import { MatCardModule } from '@angular/material/card'; import { MatListModule } from '@angular/material/list'; import { MatSidenavModule } from '@angular/material/sidenav'; import { MatCheckboxModule } from '@angular/material/checkbox'; import { MatRadioModule } from '@angular/material/radio'; import { MatDialogModule } from '@angular/material/dialog'; import { MatInputModule } from '@angular/material/input'; export const MATERIAL: any[] = [ MatToolbarModule, MatButtonModule, MatIconModule, MatCardModule, MatListModule, MatSidenavModule, MatCheckboxModule, MatRadioModule, MatDialogModule, MatInputModule ];
igorosabel/Coffee-Frontend
src/app/pipes/people-pay.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import { PeopleListResult } from '../interfaces/interfaces'; import { CommonService } from '../services/common.service'; @Pipe({ name: 'peoplePay' }) export class PeoplePayPipe implements PipeTransform { constructor(private common: CommonService) {} transform(id_person: number, people: PeopleListResult): string { return this.common.urldecode( people['person_'+id_person].name ); } }
igorosabel/Coffee-Frontend
src/app/services/data-share.service.ts
<filename>src/app/services/data-share.service.ts<gh_stars>0 import { Injectable } from '@angular/core'; @Injectable() export class DataShareService { globals = {}; constructor() {} setGlobal(key: string, value: any) { this.globals[key] = value; } getGlobal(key:string) { if (this.globals[key]) { return this.globals[key]; } return null; } removeGlobal(key:string) { if (this.globals[key]) { delete this.globals[key]; } } resetGlobals() { this.globals = {}; } }
igorosabel/Coffee-Frontend
src/app/app-routing.module.ts
<reponame>igorosabel/Coffee-Frontend import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { CoffeeComponent } from './pages/coffee/coffee.component'; import { DayComponent } from './pages/day/day.component'; import { PeopleComponent } from './pages/people/people.component'; import { AddPersonComponent } from './pages/add-person/add-person.component'; import { EditPersonComponent } from './pages/edit-person/edit-person.component'; import { PersonComponent } from './pages/person/person.component'; import { DayListComponent } from './pages/day-list/day-list.component'; const routes: Routes = [ { path: '', component: CoffeeComponent }, { path: 'day', component: DayComponent }, { path: 'people', component: PeopleComponent }, { path: 'add-person', component: AddPersonComponent }, { path: 'edit-person/:id', component: EditPersonComponent }, { path: 'person/:id', component: PersonComponent }, { path: 'day-list', component: DayListComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes, { relativeLinkResolution: 'legacy' })], exports: [RouterModule] }) export class AppRoutingModule {}
igorosabel/Coffee-Frontend
src/app/pipes/percentage-fridays.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import { PeopleResult } from '../model/people-result.class'; @Pipe({ name: 'percentageFridays' }) export class PercentageFridaysPipe implements PipeTransform { transform(person: PeopleResult): string { let num = 0; if (person.num_coffee!==0) { num = Math.floor((person.num_pay / person.num_coffee) * 100); } return `${num}% (${person.num_pay}/${person.num_coffee})`; } }
igorosabel/Coffee-Frontend
src/app/model/day-result.class.ts
import { DayResultInterface } from '../interfaces/interfaces'; export class DayResult { constructor( public id: number = null, public id_person: number = null, public people: number[] = [] ) {} toInterface(): DayResultInterface { return { id: this.id, id_person: this.id_person, people: this.people }; } }
igorosabel/Coffee-Frontend
src/app/pipes/people-list.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import { PeopleListResult } from '../interfaces/interfaces'; import { CommonService } from '../services/common.service'; @Pipe({ name: 'peopleList' }) export class PeopleListPipe implements PipeTransform { constructor(private common: CommonService) {} transform(list: number[], people: PeopleListResult): string { const aux = []; list.forEach(num => aux.push( this.common.urldecode(people['person_'+num].name) )); return aux.join(', '); } }
christophd/atlasmap
ui/packages/atlasmap/src/Atlasmap/utils/toolbar.ts
import { ConfigModel, ErrorInfo, ErrorLevel, ErrorScope, ErrorType, InspectionType, } from "@atlasmap/core"; import { getDocDef, getDocDefByName, importInstanceSchema, removeDocumentRef, } from "./document"; /** * Return true if the specified file object exists as a source or target * document, false otherwise. * * @param file - file object * @param isSource - source or target panel */ export function documentExists(file: File, isSource: boolean): boolean { const docDef = getDocDefByName(file.name, ConfigModel.getConfig(), isSource); return docDef ? true : false; } /** * Delete the specified source or target document. * * @param fileId - document ID to delete * @param isSource - source or target panel */ export async function deleteAtlasFile(fileId: string, isSource: boolean) { const cfg = ConfigModel.getConfig(); const docDef = getDocDef(fileId, cfg, isSource); await removeDocumentRef(docDef, cfg); cfg.initializationService.updateInitComplete(); } /** * The user has requested their current mappings be exported. Use the mapping management * service to establish the file content and to push it down to the server. * * @param fileName - user-specified catalog file name */ export function exportAtlasFile(fileName: string) { const cfg = ConfigModel.getConfig(); // Tack on a .adm suffix if one wasn't already specified. if (fileName.split(".").pop() !== "adm") { fileName = fileName.concat(".adm"); } return cfg.fileService.exportMappingsCatalog(fileName); } /** * A user has selected a compressed mappings catalog file to be imported into the canvas. * * @param selectedFile - user-specified ADM catalog file. * @param cfg */ async function processMappingsCatalog(selectedFile: any, cfg: ConfigModel) { cfg.initializationService.updateLoadingStatus("Importing AtlasMap Catalog"); await cfg.fileService.importADMCatalog(selectedFile); } /** * Import an ADM catalog file or a user JAR file. * * @param selectedFile * @param userFileSuffix * @param cfg */ function importAtlasGlobalFile( selectedFile: File, userFileSuffix: string, cfg: ConfigModel, ) { if (userFileSuffix === "ADM") { cfg.errorService.resetAll(); // Clear out current user documents from the backend service before processing the // imported ADM. cfg.fileService .resetMappings() .toPromise() .then(async () => { cfg.fileService .resetLibs() .toPromise() .then(async () => { await processMappingsCatalog(selectedFile, cfg); }); }) .catch((error: any) => { if (error.status === 0) { cfg.errorService.addError( new ErrorInfo({ message: "Fatal network error: Could not connect to AtlasMap design runtime service.", level: ErrorLevel.ERROR, scope: ErrorScope.APPLICATION, type: ErrorType.INTERNAL, object: error, }), ); } else { cfg.errorService.addError( new ErrorInfo({ message: "Could not reset document definitions before import.", level: ErrorLevel.ERROR, scope: ErrorScope.APPLICATION, type: ErrorType.INTERNAL, object: error, }), ); } }); } else if (userFileSuffix === "JAR") { cfg.documentService.processDocument( selectedFile, InspectionType.JAVA_CLASS, false, false, ); } } /** * The user has imported a file (mapping catalog, Java archive or source/target * level specific instance or schema document). * * @param selectedFile - user selected file * @param isSource - true is source panel, false is target * @param isSchema - user-specified instance/ schema (true === schema) * @param parameters - CSV parameters */ export function importAtlasFile( selectedFile: File, isSource: boolean, isSchema: boolean, parameters?: { [key: string]: string }, ) { const cfg = ConfigModel.getConfig(); const userFileComps = selectedFile.name.split("."); const userFileSuffix: string = userFileComps[ userFileComps.length - 1 ].toUpperCase(); if (userFileSuffix === "ADM" || userFileSuffix === "JAR") { importAtlasGlobalFile(selectedFile, userFileSuffix, cfg); } else { importInstanceSchema(selectedFile, cfg, isSource, isSchema, parameters); } } /** * Remove all documents and imported JARs from the server. */ export function resetAtlasmap() { const cfg = ConfigModel.getConfig(); cfg.errorService.resetAll(); cfg.fileService .resetMappings() .toPromise() .then(async () => { cfg.mappings = null; cfg.fileService .resetLibs() .toPromise() .then(async () => { await cfg.initializationService.initialize(); }); cfg.clearDocs(); return cfg.initializationService.initialize(); }) .catch((error: any) => { if (error.status === 0) { cfg.errorService.addError( new ErrorInfo({ message: "Fatal network error: Could not connect to AtlasMap design runtime service.", level: ErrorLevel.ERROR, scope: ErrorScope.APPLICATION, type: ErrorType.INTERNAL, object: error, }), ); } else { cfg.errorService.addError( new ErrorInfo({ message: "Could not reset mapping definitions.", level: ErrorLevel.ERROR, scope: ErrorScope.APPLICATION, type: ErrorType.INTERNAL, object: error, }), ); } }); } export function toggleMappingPreview(enabled: boolean) { const cfg = ConfigModel.getConfig(); if (enabled) { cfg.mappingService.enableMappingPreview(); } else { cfg.mappingService.disableMappingPreview(); } return enabled; } export function toggleShowMappedFields(enabled: boolean) { const cfg = ConfigModel.getConfig(); cfg.showMappedFields = enabled; cfg.initializationService.systemInitializedSource.next(); return enabled; } export function toggleShowUnmappedFields(enabled: boolean) { const cfg = ConfigModel.getConfig(); cfg.showUnmappedFields = enabled; cfg.initializationService.systemInitializedSource.next(); return enabled; }
christophd/atlasmap
ui/packages/atlasmap/src/Atlasmap/utils/ui.ts
<gh_stars>0 import ky from "ky"; import { Observable } from "rxjs"; import { ConfigModel, DataMapperUtil, DocumentDefinition, DocumentManagementService, ErrorHandlerService, ErrorInfo, ErrorLevel, ErrorScope, ErrorType, ExpressionModel, Field, FieldAction, FieldActionDefinition, FieldActionService, FileManagementService, InitializationService, MappedField, MappingDefinition, MappingManagementService, MappingModel, Multiplicity, NamespaceModel, TransitionMode, TransitionModel, } from "@atlasmap/core"; import { ITransformationArgument, ITransformationSelectOption } from "../../UI"; import { IAtlasmapDocument, IAtlasmapField, IAtlasmapGroup, IAtlasmapMappedField, IAtlasmapMapping, IAtlasmapNamespace, INotification, } from "../../Views"; const api = ky.create({ headers: { "ATLASMAP-XSRF-TOKEN": "<PASSWORD>" } }); export function copyToClipboard(text: string) { const textArea = document.createElement("textarea"); textArea.value = text; document.body.appendChild(textArea); textArea.select(); try { document.execCommand("copy"); } catch (err) { ConfigModel.getConfig().errorService.addError( new ErrorInfo({ message: "Error copying " + text + " to clipboard", level: ErrorLevel.ERROR, scope: ErrorScope.APPLICATION, type: ErrorType.INTERNAL, }), ); } document.body.removeChild(textArea); return; } export const initializationService = new InitializationService( new DocumentManagementService(api), new MappingManagementService(api), new ErrorHandlerService(), new FieldActionService(api), new FileManagementService(api), ); export function fromFieldToIFieldsGroup(field: Field): IAtlasmapGroup | null { const fields = field.children .map(fromFieldToIFields) .filter((f) => f) as IAtlasmapField[]; return fields.length > 0 && field.visibleInCurrentDocumentSearch ? { id: `${field.docDef.uri || field.docDef.type + "-" + field.scope}:${ field.docDef.isSource ? "source" : "target" }:${field.path}`, name: field.name, type: field.type, isCollection: field.isCollection, isInCollection: field.isInCollection(), fields: fields, amField: field, } : null; } export function fromFieldToIFieldsNode(field: Field): IAtlasmapField | null { const cfg = ConfigModel.getConfig(); const partOfMapping: boolean = field.partOfMapping; const shouldBeVisible = partOfMapping ? cfg.showMappedFields : cfg.showUnmappedFields && field.visibleInCurrentDocumentSearch; return shouldBeVisible ? { id: `${field.docDef.uri || field.docDef.type + "-" + field.scope}:${ field.docDef.isSource ? "source" : "target" }:${field.path}`, name: field.getFieldLabel(false, false), type: field.type, path: field.path, scope: field.scope, amField: field, previewValue: field.value, mappings: (cfg.mappings ?.findMappingsForField(field) .map(fromMappingModelToImapping) .filter((d) => d) as IAtlasmapMapping[]) || [], hasTransformations: field.partOfTransformation, isAttribute: field.isAttribute, isCollection: field.isCollection, isInCollection: field.isInCollection(), isConnected: partOfMapping, isDisabled: field.type === "UNSUPPORTED" || (field.type === "COMPLEX" && !field.enumeration), } : null; } export function fromFieldToIFields(field: Field) { return field.children.length > 0 ? fromFieldToIFieldsGroup(field) : fromFieldToIFieldsNode(field); } export function fromNamespaceModelToINamespace(namespace: NamespaceModel) { return { alias: namespace.alias, uri: namespace.uri, locationUri: namespace.locationUri, isTarget: namespace.isTarget, }; } export function fromDocumentDefinitionToFieldGroup( def: DocumentDefinition, ): IAtlasmapDocument | null { if (!def || !def.fields || def.fields.length === 0) { return null; } const fields = def.fields .map(fromFieldToIFields) .filter((f) => f) as IAtlasmapField[]; const namespaces = def.namespaces .map(fromNamespaceModelToINamespace) .filter((n) => n) as IAtlasmapNamespace[]; return def.visibleInCurrentDocumentSearch && fields.length > 0 ? { id: def.id, fields, name: def.name, type: def.type, namespaces, } : null; } export function fromMappedFieldToIMappingField( mappedField: MappedField, ): IAtlasmapMappedField | null { if (!mappedField.field || !mappedField.field.docDef) { return null; } return { id: `${ mappedField.field!.docDef.uri || mappedField.field!.docDef.type + "-" + mappedField.field!.scope }:${mappedField.field!.docDef.isSource ? "source" : "target"}:${ mappedField.field!.path }`, name: mappedField.field!.getFieldLabel(false, false), type: mappedField.field!.type, path: mappedField.field!.path, scope: mappedField.field!.scope, previewValue: mappedField.field!.value, hasTransformations: false, mappings: [], isAttribute: false, isCollection: false, isInCollection: false, isConnected: false, isDisabled: false, amField: mappedField.field, transformations: mappedField.actions.map((a) => ({ name: a.name, options: getMappingActions(mappedField.isSource()).map( (a): ITransformationSelectOption => ({ name: DataMapperUtil.toDisplayable(a.name), value: a.name, }), ), arguments: a.definition.arguments.map( (av, idx): ITransformationArgument => ({ label: av.serviceObject?.title?.length > 0 ? av.serviceObject.title : DataMapperUtil.toDisplayable(av.name), name: av.name, value: a.argumentValues[idx].value, options: av.values ? av.values.map( (avv): ITransformationSelectOption => ({ name: avv, value: avv, }), ) : undefined, }), ), })), }; } export function errorLevelToVariant( level: ErrorLevel, ): INotification["variant"] { switch (level) { case ErrorLevel.INFO: return "info"; case ErrorLevel.WARN: return "warning"; case ErrorLevel.ERROR: return "danger"; default: return "default"; } } export function errorMessageToString(message: any): string { switch (typeof message) { case "string": return message; default: return message?.message || JSON.stringify(message); } } export function errorTypeToString(type: ErrorType): string { switch (type) { case ErrorType.INTERNAL: return "Internal"; case ErrorType.USER: return "User"; case ErrorType.VALIDATION: return "Validation"; case ErrorType.PREVIEW: return "Preview"; case ErrorType.FORM: return "Form"; } } export function errorInfoToNotification(e: ErrorInfo): INotification { return { variant: errorLevelToVariant(e.level), title: e.mapping && e.type !== ErrorType.PREVIEW ? `${errorTypeToString( e.type, )}: "${e.mapping.transition.getPrettyName()}"` : errorTypeToString(e.type), description: errorMessageToString(e.message), id: e.identifier, mappingId: e.mapping?.uuid, }; } export function fromMappingModelToImapping( m: MappingModel | null | undefined, ): IAtlasmapMapping | null { return m ? { id: m.uuid, name: m.transition.getPrettyName(), sourceFields: m .getUserMappedFields(true) .map(fromMappedFieldToIMappingField) .filter((f) => f) as IAtlasmapMappedField[], targetFields: m .getUserMappedFields(false) .map(fromMappedFieldToIMappingField) .filter((f) => f) as IAtlasmapMappedField[], mapping: m, } : null; } export function fromMappingDefinitionToIMappings( def: MappingDefinition | null, ): IAtlasmapMapping[] { return def ? (def.mappings .map(fromMappingModelToImapping) .filter((d) => d) as IAtlasmapMapping[]) : []; } export function executeFieldSearch( searchFilter: string, isSource: boolean, ): string[][] { return initializationService.cfg.mappingService.executeFieldSearch( initializationService.cfg, searchFilter, isSource, ); } export function getField(fieldPath: string, isSource: boolean): Field | null { let field: Field | null = null; for (const doc of initializationService.cfg.getDocs(isSource)) { field = Field.getField(fieldPath, doc.getAllFields()); if (field) { break; } } return field; } export function mappingExpressionAddField( selectedField: string, selectedFieldScope: string, newTextNode: any, atIndex: number, isTrailer: boolean, ) { const mapping = initializationService.cfg.mappings!.activeMapping; if (!mapping || !selectedField) { return; } let mappedField = mapping.getMappedFieldByName(selectedField, true, { fieldScope: selectedFieldScope, }); if (!mappedField) { // If the selected field was not part of the original mapping // and is complex then add it as a reference node. mappedField = mapping.getReferenceField(selectedField); if (mappedField) { mapping.transition!.expression!.addConditionalExpressionNode( mappedField, newTextNode.getUuid(), isTrailer ? newTextNode.str.length : atIndex, ); } else { // Try adding the selected field to the active mapping. let field: Field | null = null; for (const doc of initializationService.cfg.getDocs(true)) { field = Field.getField( selectedField, doc.getAllFields(), selectedFieldScope, ); if (field) { break; } } if (field) { initializationService.cfg.mappingService.fieldSelected( field, true, newTextNode.getUuid(), isTrailer ? newTextNode.toText().length : atIndex, ); } } } else { mapping.transition!.expression!.addConditionalExpressionNode( mappedField, newTextNode.getUuid(), isTrailer ? newTextNode.str.length : atIndex, ); } initializationService.cfg.mappingService.notifyMappingUpdated(); } export function mappingExpressionInit() { if ( !initializationService.cfg.mappings || !initializationService.cfg.mappings.activeMapping ) { return; } const mapping = initializationService.cfg.mappings!.activeMapping!; // Filter out padding fields for expression mapping. mapping .getMappedFields(true) .filter((mf) => mf.isPadField()) .forEach((mf) => mapping.removeMappedField(mf)); if (!mapping.transition.expression) { mapping.transition.expression = new ExpressionModel( mapping, initializationService.cfg, ); mapping.transition.expression.generateInitialExpression(); } else { mapping.transition.expression.setConfigModel(initializationService.cfg); } mapping.transition.expression.updateFieldReference(mapping); } export function mappingExpressionClearText( nodeId?: string, startOffset?: number, endOffset?: number, ) { const uuidNode = initializationService.cfg.mappings!.activeMapping!.transition.expression!.clearText( nodeId!, startOffset, endOffset, ); initializationService.cfg.mappingService.notifyMappingUpdated(); return uuidNode; } export function mappingExpressionInsertText( str: string, nodeId?: string, offset?: number, ) { initializationService.cfg.mappings!.activeMapping!.transition.expression!.insertText( str, nodeId, offset, ); initializationService.cfg.mappingService.notifyMappingUpdated(); } export function mappingExpressionObservable(): Observable<any> | null { if ( !initializationService.cfg.mappings?.activeMapping?.transition?.expression ) { return null; } return initializationService.cfg.mappings.activeMapping.transition.expression .expressionUpdated$; } export function mappingExpressionRemoveField( tokenPosition?: string, offset?: number, ) { initializationService.cfg.mappings!.activeMapping!.transition.expression!.removeToken( tokenPosition, offset, ); initializationService.cfg.mappingService.notifyMappingUpdated(); } export function onFieldPreviewChange(field: IAtlasmapField, value: string) { field.amField.value = value; initializationService.cfg.mappingService.notifyMappingUpdated(); } export function toggleExpressionMode() { initializationService.cfg.mappingService.toggleExpressionMode(); initializationService.cfg.mappingService.notifyMappingUpdated(); } export function getMappingActions(isSource: boolean) { return initializationService.cfg.fieldActionService.getActionsAppliesToField( initializationService.cfg.mappings!.activeMapping!, isSource, Multiplicity.ONE_TO_ONE, ); } export function getMultiplicityActions(mapping: MappingModel) { if (mapping.transition.mode === TransitionMode.ONE_TO_MANY) { return initializationService.cfg.fieldActionService.getActionsAppliesToField( mapping, true, Multiplicity.ONE_TO_MANY, ); } else if (mapping.transition.mode === TransitionMode.MANY_TO_ONE) { return initializationService.cfg.fieldActionService.getActionsAppliesToField( mapping, true, Multiplicity.MANY_TO_ONE, ); } else { return []; } } export function getMultiplicityActionDelimiters() { return TransitionModel.delimiterModels; } export function handleActionChange( action: FieldAction, definition: FieldActionDefinition, ) { action.argumentValues = []; // Invalidate the previously selected field action arguments. definition.populateFieldAction(action); // If the field action configuration predefines argument values then populate the fields with // default values. Needed to support pull-down menus in action argument definitions. if ( action.argumentValues.values && action.argumentValues.length > 0 && definition.arguments[0] && definition.arguments[0].values && definition.arguments[0].values.length > 0 ) { for (let i = 0; i < action.argumentValues.length; i++) { action.argumentValues[i].value = definition.arguments[i].values![i]; } } initializationService.cfg.mappingService.notifyMappingUpdated(); } /** * Process a mapped field index change. The source field is represented by * currentIndex. The target index is represented either by a number or by a * mapped field (depending on whether the index was physically modified or * d&d modified). * * @param isSource * @param currentIndex * @param target */ export function handleIndexChange( isSource: boolean, currentIndex: number, target: number | Field, ) { const cfg = ConfigModel.getConfig(); const activeMapping = cfg.mappings?.activeMapping; if (!activeMapping) { return; } const sourceField = activeMapping.getMappedFieldForIndex( "" + (currentIndex + 1), isSource, ); if (!sourceField) { return; } let newIndex: number | null = 0; // If the target is an actual index value then check for the need to add padding. if (typeof target === "number") { newIndex = target; if (target <= 0 || !activeMapping) { return; } const mappedFields = activeMapping.getMappedFields(isSource); const maxIndex = mappedFields.length; if (target > maxIndex) { // Add place-holders for each index value between the previous max index // and the insertion index. cfg.mappingService.addPlaceholders( target - mappedFields.length, activeMapping, maxIndex, isSource, ); } // If the target is a dropped field then extract the mapped field to determine the index. } else { const field = activeMapping.getMappedFieldForField(target!); if (!field) { return; } newIndex = activeMapping.getIndexForMappedField(field); } cfg.mappingService.moveMappedFieldTo(activeMapping, sourceField, newIndex!); } export function handleNewTransformation(isSource: boolean, index: number) { const cfg = ConfigModel.getConfig(); const activeMapping = cfg.mappings?.activeMapping; if (!activeMapping) { return; } const field = activeMapping.getMappedFieldForIndex( "" + (index + 1), isSource, ); if (!field) { return; } const action: FieldAction = new FieldAction(); const availableActions = getMappingActions(isSource); availableActions[0].populateFieldAction(action); field.actions.push(action); cfg.mappingService.notifyMappingUpdated(); } export function handleTransformationChange( isSource: boolean, index: number, currentTransformationIndex: number, newTransformationName: string, ) { const cfg = ConfigModel.getConfig(); const activeMapping = cfg.mappings?.activeMapping; if (!activeMapping) { return; } const field = activeMapping.getMappedFieldForIndex( "" + (index + 1), isSource, ); if (!field) { return; } const action = field.actions[currentTransformationIndex]; const newAction = getMappingActions(isSource).find( (a) => a.name === newTransformationName, ); if (action && newAction) { action.argumentValues = []; // Invalidate the previously selected field action arguments. newAction.populateFieldAction(action); // If the field action configuration predefines argument values then populate the fields with // default values. Needed to support pull-down menus in action argument definitions. if ( action.argumentValues.values && action.argumentValues.length > 0 && newAction.arguments[0] && newAction.arguments[0].values && newAction.arguments[0].values.length > 0 ) { for (let i = 0; i < action.argumentValues.length; i++) { action.argumentValues[i].value = newAction.arguments[i].values![i]; } } cfg.mappingService.notifyMappingUpdated(); } } export function handleTransformationArgumentChange( isSource: boolean, index: number, transformationIndex: number, argumentName: string, argumentValue: string, ) { const cfg = ConfigModel.getConfig(); const activeMapping = cfg.mappings?.activeMapping; if (!activeMapping) { return; } const field = activeMapping.getMappedFieldForIndex( "" + (index + 1), isSource, ); if (!field) { return; } const action = field.actions[transformationIndex]; if (action) { action.setArgumentValue(argumentName, argumentValue); cfg.mappingService.notifyMappingUpdated(); } } export function handleRemoveTransformation( isSource: boolean, index: number, transformationIndex: number, ) { const cfg = ConfigModel.getConfig(); const activeMapping = cfg.mappings?.activeMapping; if (!activeMapping) { return; } const field = activeMapping.getMappedFieldForIndex( "" + (index + 1), isSource, ); if (!field) { return; } const action = field.actions[transformationIndex]; if (action) { DataMapperUtil.removeItemFromArray(action, field.actions); cfg.mappingService.notifyMappingUpdated(); } } export function handleMultiplicityChange(action: FieldAction, name: string) { const cfg = ConfigModel.getConfig(); const activeMapping = cfg.mappings?.activeMapping; if (!activeMapping) { return; } const newAction = getMultiplicityActions(activeMapping).find( (a) => a.name === name, ); if (action && newAction) { action.argumentValues = []; // Invalidate the previously selected field action arguments. newAction.populateFieldAction(action); // If the field action configuration predefines argument values then populate the fields with // default values. Needed to support pull-down menus in action argument definitions. if ( action.argumentValues.values && action.argumentValues.length > 0 && newAction.arguments[0] && newAction.arguments[0].values && newAction.arguments[0].values.length > 0 ) { for (let i = 0; i < action.argumentValues.length; i++) { action.argumentValues[i].value = newAction.arguments[i].values![i]; } } initializationService.cfg.mappingService.notifyMappingUpdated(); } } export function handleMultiplicityArgumentChange( multiplicityFieldAction: FieldAction, argumentName: string, argumentValue: string, ) { const cfg = ConfigModel.getConfig(); multiplicityFieldAction.setArgumentValue(argumentName, argumentValue); cfg.mappingService.notifyMappingUpdated(); } export function selectMapping(mapping: IAtlasmapMapping) { initializationService.cfg.mappingService.selectMapping(mapping.mapping); } export function deselectMapping() { initializationService.cfg.mappingService.deselectMapping(); }
mahsumurebe/zelzele
src/Servers/WS/index.ts
<reponame>mahsumurebe/zelzele import {IProviderResponse} from '../../Providers/types'; import http from 'http'; import https from 'https'; import {IWSConfig} from './types'; import {IServer} from '../types'; import ws from 'ws'; import {Signale} from 'signale'; const signale = new Signale({ scope: 'WS', }); export default class WS implements IServer { private readonly server: http.Server | https.Server; private readonly wsServer: ws.Server; private config: IWSConfig; constructor() { this.config = { hostname: process.env.WS_SERVER_HOSTNAME, port: +(process.env.WS_SERVER_PORT || '3001'), https: { use: process.env.WS_SERVER_HTTPS_USE === 'true', certFile: process.env.WS_SERVER_HTTPS_CERT_FILE, privateKey: process.env.WS_SERVER_HTTPS_PRIVATE_KEY_FILE, }, }; //region HTTP/HTTPS Server if (this.config.https.use) { if (!this.config.https.certFile) { throw new Error('Certificate file is not defined.'); } else if (!this.config.https.privateKey) { throw new Error('Private Key is not defined.'); } const fs = require('fs'); if (!fs.existsSync(this.config.https.certFile)) { throw new Error('Certificate file not found.'); } else if (!fs.existsSync(this.config.https.privateKey)) { throw new Error('Private Key file not found.'); } const privateKey = fs.readFileSync(this.config.https.privateKey, 'utf8'); const certificate = fs.readFileSync(this.config.https.certFile, 'utf8'); const credentials = {key: privateKey, cert: certificate}; this.server = https.createServer(credentials); } else { this.server = http.createServer(); } //endregion this.wsServer = new ws.Server({ server: this.server, }); this.wsServer.on('error', error => signale.error(`Websocket Error:`, error)); this.wsServer.on('listening', () => { signale.log(`WebSocket server listening on ws${this.config.https.use ? 's' : ''}://${this.config.hostname}:${this.config.port}`); }); this.wsServer.on('close', () => signale.info(`WebSocket server is closed.`)); } async emit(data: IProviderResponse): Promise<this> { this.wsServer.clients.forEach(client => { client.send(JSON.stringify(data)); }); return this; } async listen(): Promise<void> { this.server.listen(this.config.port, this.config.hostname); return; } }
mahsumurebe/zelzele
src/Providers/index.ts
<reponame>mahsumurebe/zelzele export {default as TrEduBounKoeri} from './tr.edu.boun.koeri';
mahsumurebe/zelzele
src/Providers/tr.edu.boun.koeri/index.ts
import {IProvider, IProviderResponse} from '../types'; import Axios, {AxiosInstance} from 'axios'; import {EventEmitter} from 'events'; class TrEduBounKoeri extends EventEmitter implements IProvider { providerName = '<NAME>'; url = 'http://www.koeri.boun.edu.tr/scripts/lst4.asp'; request: AxiosInstance; private interval = 1000; // Interval ms private timeout: NodeJS.Timeout; private lastTime = 0; private stress = 0; constructor() { super(); this.request = Axios.create({ baseURL: this.url, }); } async get(lastTime: number): Promise<Array<IProviderResponse>> { const self = this; return this.request .get<string>('') .then(data => { const out: IProviderResponse[] = []; const content = data.data; const regex = /^([0-9]{4}.[0-9]{2}.[0-9]{2}\s[0-9]{2}:[0-9]{2}:[0-9]{2})\s+([0-9]{1,2}\.[0-9]{0,4})\s+([0-9]{1,2}\.[0-9]{0,4})\s+([0-9]{1,2}\.[0-9]{0,4})\s+([0-9-]{1,2}\.[0-9-]{0,4})\s+([0-9-]{1,2}\.[0-9-]{0,4})\s+([0-9-]{1,2}\.[0-9-]{0,4})\s+([A-Z-()\s]+)\s.*$/gm; for (const i of content.matchAll(regex)) { const [, date, lat, long, depth, magnitude_local, magnitude_moment, magnitude_duration, location] = i; out.push({ provide: { name: self.providerName, url: self.url, }, date: new Date(date), lat, long, depth, magnitude: { local: +magnitude_local, moment: +magnitude_moment, duration: +magnitude_duration, }, location: location.toString().trim(), }); } return out.filter(item => { return item.date.getTime() > lastTime; }); }); } async run(): Promise<void> { const self = this; this.timeout = setTimeout(() => { self.get(self.lastTime) .then((data) => { if (data.length > 0) { for (const item of data) { if (this.lastTime < item.date.getTime()) { this.lastTime = item.date.getTime(); } self.emit('data', item); } } setTimeout(() => self.run(), this.interval); }) .catch(() => { if (this.stress > 5) { return self.stop(); } self.stress++; }); }, this.interval); return; } async stop(): Promise<void> { clearTimeout(this.lastTime); return; } } const provide = new TrEduBounKoeri(); export default provide;
mahsumurebe/zelzele
src/Providers/types.ts
<reponame>mahsumurebe/zelzele<filename>src/Providers/types.ts export interface IProvider { providerName: string; url: string; get(lastTime: number): Promise<Array<IProviderResponse>>; run(): Promise<void>; stop(): Promise<void>; } export interface IProviderResponse { provide: { name: string; url: string; } date: Date; lat: string; long: string; depth: string; magnitude: { local: number; moment: number; duration: number; }; location: string; }
mahsumurebe/zelzele
src/index.ts
import './config'; import {fromEvent, merge, Observable} from 'rxjs'; import {IProvider, IProviderResponse} from './Providers/types'; import {Signale} from 'signale'; import WS from './Servers/WS'; const logger = new Signale({ scope: 'ZELZELE', types: { fatal: { label: '', badge: '->', color: 'red', }, }, }); async function init() { logger.info('Starting WebSocket server.'); const wsServer = new WS(); await wsServer.listen(); const newEarthquake = logger.scope('ZELZELE', 'NEW'); logger.info(`Running providers.`); let observable: Observable<IProviderResponse>; const providers: { [key: string]: IProvider } = require('./Providers'); const chalk = require('chalk'); for (const provider of Object.values(providers)) { logger.debug(`Starting ${provider.providerName} provider.`); provider.run().catch(() => provider.stop()); observable = merge<IProviderResponse>(fromEvent<IProviderResponse>(provider as any, 'data')); } observable.subscribe(value => { newEarthquake.fatal(`${chalk.red('EarthQuake')} ${chalk.blue('Date:')} ${value.date}\t${chalk.blue('Lat:')} ${value.lat}\t${chalk.blue('Long:')} ${value.long}\t${chalk.blue('Depth:')} ${value.depth}\t${chalk.blue('MD:')} ${isNaN(value.magnitude.local) ? '-.-' : value.magnitude.local}\t${chalk.blue('ML:')} ${isNaN(value.magnitude.moment) ? '-.-' : value.magnitude.moment}\t${chalk.blue('MW:')} ${isNaN(value.magnitude.duration) ? '-.-' : value.magnitude.duration}\t${chalk.blue('Location:')} ${value.location}`); wsServer.emit(value); }); } init().catch(e => logger.fatal(e));
mahsumurebe/zelzele
src/Servers/WS/types.ts
export interface IWSConfig { hostname: string; port: number; pathname?: string; https?: { use: boolean; certFile: string; privateKey: string; }, }
mahsumurebe/zelzele
src/Servers/types.ts
import {IProviderResponse} from '../Providers/types'; export interface IServer { emit(data: IProviderResponse): Promise<this> listen(): Promise<void>; }
mahsumurebe/zelzele
src/config.ts
<reponame>mahsumurebe/zelzele import {resolve as pathResolve} from 'path'; import * as dotenv from 'dotenv'; import ProcessEnv = NodeJS.ProcessEnv; const configDir = pathResolve(__dirname, '../', '.env'); const fs = require('fs'); process.env['FS_PATH'] = __dirname; const env: ProcessEnv = <ProcessEnv>{}; if (fs.existsSync(configDir)) { const defaults = {}; const tempEnv: ProcessEnv = { ...defaults, ...dotenv.config({ path: configDir, }).parsed, }; const processEnvKeys: Array<string> = Object.keys(process.env); for (const key in tempEnv) { // noinspection JSUnfilteredForInLoop if (processEnvKeys.indexOf(key) === -1) { // noinspection JSUnfilteredForInLoop process.env[key] = tempEnv[key]; } // noinspection JSUnfilteredForInLoop env[key] = process.env[key]; } }
jelly/patternfly-react
packages/react-core/src/components/ChipGroup/examples/ChipGroupInline.tsx
<reponame>jelly/patternfly-react<filename>packages/react-core/src/components/ChipGroup/examples/ChipGroupInline.tsx import React from 'react'; import { Chip, ChipGroup } from '@patternfly/react-core'; export const ChipGroupInline: React.FunctionComponent = () => { const [chips, setChips] = React.useState([ 'Chip one', 'Really long chip that goes on and on', 'Chip three', 'Chip four', 'Chip five' ]); const deleteItem = (id: string) => { const copyOfChips = [...chips]; const filteredCopy = copyOfChips.filter(chip => chip !== id); setChips(filteredCopy); }; return ( <ChipGroup> {chips.map(currentChip => ( <Chip key={currentChip} onClick={() => deleteItem(currentChip)}> {currentChip} </Chip> ))} </ChipGroup> ); };
jelly/patternfly-react
packages/react-topology/src/utils/style-utils.ts
import { EdgeAnimationSpeed, EdgeStyle, NodeStatus } from '../types'; import styles from '@patternfly/react-styles/css/components/Topology/topology-components'; export const StatusModifier = { [NodeStatus.default]: '', [NodeStatus.info]: styles.modifiers.info, [NodeStatus.success]: styles.modifiers.success, [NodeStatus.warning]: styles.modifiers.warning, [NodeStatus.danger]: styles.modifiers.danger }; export const getEdgeStyleClassModifier = (edgeType: EdgeStyle): string => { switch (edgeType) { case EdgeStyle.solid: return 'pf-m-solid'; case EdgeStyle.dotted: return 'pf-m-dotted'; case EdgeStyle.dashed: return 'pf-m-dashed'; case EdgeStyle.dashedMd: return 'pf-m-dashed-md'; case EdgeStyle.dashedLg: return 'pf-m-dashed-lg'; case EdgeStyle.dashedXl: return 'pf-m-dashed-xl'; default: return ''; } }; export const getEdgeAnimationDuration = (speed: EdgeAnimationSpeed): number => { switch (speed) { case EdgeAnimationSpeed.slow: return 1.25; case EdgeAnimationSpeed.mediumSlow: return 1; case EdgeAnimationSpeed.medium: return 0.75; case EdgeAnimationSpeed.mediumFast: return 0.5; case EdgeAnimationSpeed.fast: return 0.25; default: return 0; } };
jelly/patternfly-react
packages/react-charts/src/components/ChartTheme/styles/legend-tooltip-styles.ts
/* eslint-disable camelcase */ import global_FontWeight_bold from '@patternfly/react-tokens/dist/esm/global_FontWeight_bold'; import chart_voronoi_labels_Fill from '@patternfly/react-tokens/dist/esm/chart_voronoi_labels_Fill'; // Legend tooltip styles export const LegendTooltipStyles = { flyout: { padding: 40 }, label: { fill: chart_voronoi_labels_Fill.value, fontWeight: global_FontWeight_bold.value } as any };
jelly/patternfly-react
packages/react-core/src/components/Checkbox/examples/CheckboxStandaloneInput.tsx
import React from 'react'; import { Checkbox } from '@patternfly/react-core'; export const CheckboxStandaloneInput: React.FunctionComponent = () => ( <Checkbox id="standalone-check" name="standlone-check" aria-label="Standalone input" /> );
jelly/patternfly-react
packages/react-core/src/components/Menu/MenuList.tsx
import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/Menu/menu'; import { css } from '@patternfly/react-styles'; export interface MenuListProps extends React.HTMLProps<HTMLUListElement> { /** Anything that can be rendered inside of menu list */ children: React.ReactNode; /** Additional classes added to the menu list */ className?: string; } export const MenuList: React.FunctionComponent<MenuListProps> = ({ children = null, className, ...props }: MenuListProps) => ( <ul role="menu" className={css(styles.menuList, className)} {...props}> {children} </ul> ); MenuList.displayName = 'MenuList';
jelly/patternfly-react
packages/react-integration/cypress/integration/tablefavorites.spec.ts
<gh_stars>100-1000 describe('Table Favorites Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/table-favorites-demo-nav-link'); }); it('Check number of rows', () => { cy.get('.pf-c-table > tbody') .find('tr') .should('have.length', 3); }); it('Check number of columns', () => { cy.get('thead > tr') .children() .should('have.length', 7); }); it('Test favorites button', () => { cy.get('#favorites-button-1') .parent() .should('not.have.class', 'pf-m-favorited'); cy.get('#favorites-button-1').click(); cy.get('#favorites-button-1') .parent() .should('have.class', 'pf-m-favorited'); cy.get('#favorites-button-1').click(); cy.get('#favorites-button-1') .parent() .should('not.have.class', 'pf-m-favorited'); }); it('Sort favorites', () => { // initially not sorted cy.get('#favorites-button-0') .parent() .should('have.class', 'pf-m-favorited'); cy.get('#favorites-button-1') .parent() .should('not.have.class', 'pf-m-favorited'); cy.get('#favorites-button-2') .parent() .should('have.class', 'pf-m-favorited'); // click fav sort icon cy.get('thead > tr') .children() .eq(1) .click(); // sorted ascending (favorited items first) cy.get('#favorites-button-0') .parent() .should('have.class', 'pf-m-favorited'); cy.get('#favorites-button-1') .parent() .should('have.class', 'pf-m-favorited'); cy.get('#favorites-button-2') .parent() .should('not.have.class', 'pf-m-favorited'); // sort again descending (favorited items last) cy.get('thead > tr') .children() .eq(1) .click(); cy.get('#favorites-button-0') .parent() .should('not.have.class', 'pf-m-favorited'); cy.get('#favorites-button-1') .parent() .should('have.class', 'pf-m-favorited'); cy.get('#favorites-button-2') .parent() .should('have.class', 'pf-m-favorited'); }); });
jelly/patternfly-react
packages/react-console/src/components/DesktopViewer/__tests__/DesktopViewer.test.tsx
<filename>packages/react-console/src/components/DesktopViewer/__tests__/DesktopViewer.test.tsx<gh_stars>0 import React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { DesktopViewer } from '../DesktopViewer'; import { MoreInformationDefaultContent } from '../MoreInformationDefaultContent'; import { generateDescriptorFile } from '../consoleDescriptorGenerator'; import { constants } from '../../common/constants'; const { SPICE_CONSOLE_TYPE, RDP_CONSOLE_TYPE, DEFAULT_RDP_PORT } = constants; const spice = { address: 'my.host.com', port: 5900, tlsPort: '5901' }; const vnc = { address: 'my.host.com', port: 5902, tlsPort: '5903' }; const rdp = { address: 'my.host.com', port: DEFAULT_RDP_PORT }; const rdp2 = { address: 'my.differenthost.com', port: 1234 }; describe('DesktopViewer', () => { test('empty', () => { const { asFragment } = render(<DesktopViewer />); expect(asFragment()).toMatchSnapshot(); }); test('with Spice and VNC', () => { const { asFragment } = render(<DesktopViewer spice={spice} vnc={vnc} />); expect(asFragment()).toMatchSnapshot(); }); test('with Spice, VNC and RDP', () => { const { asFragment } = render(<DesktopViewer spice={spice} vnc={vnc} rdp={rdp} />); expect(asFragment()).toMatchSnapshot(); }); test('with Spice, VNC and RDP (different hostname)', () => { const { asFragment } = render(<DesktopViewer spice={spice} vnc={vnc} rdp={rdp2} />); expect(asFragment()).toMatchSnapshot(); }); test('launch button', () => { const onDownload = jest.fn(); const onGenerate = jest.fn().mockReturnValue({ content: 'Foo' }); render(<DesktopViewer spice={spice} vnc={vnc} onDownload={onDownload} onGenerate={onGenerate} />); userEvent.click(screen.getByRole('button', { name: 'Launch Remote Viewer' })); expect(onGenerate).toHaveBeenCalledTimes(1); expect(onDownload).toHaveBeenCalledTimes(1); }); test('RDP launch button', () => { const onDownload = jest.fn(); const onGenerate = jest.fn().mockReturnValue({ content: 'Foo' }); render(<DesktopViewer rdp={rdp} onDownload={onDownload} onGenerate={onGenerate} />); userEvent.click(screen.getByRole('button', { name: 'Launch Remote Desktop' })); expect(onGenerate).toHaveBeenCalledTimes(1); expect(onDownload).toHaveBeenCalledTimes(1); }); test('with custom more-info content', () => { render( <DesktopViewer spice={spice} vnc={vnc}> <p id="custom-more-info">My more-info content</p> </DesktopViewer> ); expect(screen.queryByText('My more-info content')).toBeNull(); userEvent.click(screen.getByRole('button', { name: 'Remote Viewer Details' })); // If one of the items is shown in the description list, the rest will be in the document as well. expect(screen.getByText('RHEL, CentOS')).toBeInTheDocument(); }); test('default MoreInformationContent', () => { const { asFragment } = render(<MoreInformationDefaultContent />); expect(asFragment()).toMatchSnapshot(); }); test('default implementation of generateVVFile()', () => { const output = generateDescriptorFile(spice, SPICE_CONSOLE_TYPE); expect(output.mimeType).toMatch('application/x-virt-viewer'); expect(output.content).toMatch( '[virt-viewer]\ntype=spice\nhost=my.host.com\nport=5900\ndelete-this-file=1\nfullscreen=0\n' ); }); test('default implementation of generateRDPFile()', () => { const output = generateDescriptorFile(rdp, RDP_CONSOLE_TYPE); expect(output.mimeType).toMatch('application/rdp'); expect(output.content).toEqual(expect.stringContaining('full address:s:my.host.com:3389\n')); // the rest is a constant so far }); });
jelly/patternfly-react
packages/react-core/src/layouts/Flex/__tests__/Flex.test.tsx
<filename>packages/react-core/src/layouts/Flex/__tests__/Flex.test.tsx import * as React from 'react'; import { render, screen } from '@testing-library/react'; import { Flex } from '../Flex'; import { FlexItem } from '../FlexItem'; describe('Flex', () => { test('Simple flex with single item', () => { const { asFragment } = render( <Flex> <FlexItem>Test</FlexItem> </Flex> ); expect(asFragment()).toMatchSnapshot(); }); test('Nested flex', () => { const { asFragment } = render( <Flex> <Flex> <FlexItem>Test</FlexItem> </Flex> </Flex> ); expect(asFragment()).toMatchSnapshot(); }); test('className is added to the root element', () => { render(<Flex className="extra-class" data-testid="test-id" />); expect(screen.getByTestId('test-id')).toHaveClass('extra-class'); }); const flexModifiers = { spacer: [ 'spacerNone', 'spacerXs', 'spacerSm', 'spacerMd', 'spacerLg', 'spacerXl', 'spacer2xl', 'spacer3xl', 'spacer4xl' ], spaceItems: [ 'spaceItemsNone', 'spaceItemsXs', 'spaceItemsSm', 'spaceItemsMd', 'spaceItemsLg', 'spaceItemsXl', 'spaceItems2xl', 'spaceItems3xl', 'spaceItems4xl' ], grow: ['grow'], shrink: ['shrink'], flex: ['flexDefault', 'flexNone', 'flex_1', 'flex_2', 'flex_3', 'flex_4'], direction: ['column', 'columnReverse', 'row', 'rowReverse'], alignItems: [ 'alignItemsFlexStart', 'alignItemsFlexEnd', 'alignItemsCenter', 'alignItemsStretch', 'alignItemsBaseline' ], alignContent: [ 'alignContentFlexStart', 'alignContentFlexEnd', 'alignContentCenter', 'alignContentStretch', 'alignContentSpaceBetween', 'alignContentSpaceAround' ], alignSelf: ['alignSelfFlexStart', 'alignSelfFlexEnd', 'alignSelfCenter', 'alignSelfStretch', 'alignSelfBaseline'], align: ['alignLeft', 'alignRight'], justifyContent: [ 'justifyContentFlexStart', 'justifyContentFlexEnd', 'justifyContentCenter', 'justifyContentSpaceBetween', 'justifyContentSpaceAround', 'justifyContentSpaceEvenly' ], display: ['inlineFlex'], fullWidth: ['fullWidth'], flexWrap: ['wrap', 'wrapReverse', 'nowrap'] }; describe('flex modifiers', () => { Object.entries(flexModifiers) .map(([mod, values]) => values.map(value => ({ [mod]: { default: value, sm: value, lg: value, xl: value, '2xl': value } })) ) .reduce((acc, val) => acc.concat(val), []) .forEach(props => test(`${JSON.stringify(props)} add valid classes to Flex`, () => { render( <Flex {...props} data-testid="test-id"> {JSON.stringify(props)} </Flex> ); const className = screen .getByTestId('test-id') .className.replace('pf-l-flex', '') .trim(); expect(className).not.toBe("''"); expect(className).not.toBe(''); }) ); }); const flexItemModifiers = { spacer: flexModifiers.spacer, grow: flexModifiers.grow, shrink: flexModifiers.shrink, flex: flexModifiers.flex, alignSelf: flexModifiers.alignSelf, align: flexModifiers.align, fullWidth: flexModifiers.fullWidth }; describe('flexItem modifiers', () => { Object.entries(flexItemModifiers) .map(([mod, values]) => values.map(value => ({ [mod]: { default: value, sm: value, lg: value, xl: value, '2xl': value } })) ) .reduce((acc, val) => acc.concat(val), []) .forEach(props => test(`${JSON.stringify(props)} add valid classes to FlexItem`, () => { render( <FlexItem {...props} data-testid="test-id"> {JSON.stringify(props)} </FlexItem> ); const className = screen.getByTestId('test-id').className.trim(); expect(className).not.toBe("''"); expect(className).not.toBe(''); }) ); }); test('alternative component', () => { const { asFragment } = render( <Flex component="ul"> <FlexItem component="li">Test</FlexItem> </Flex> ); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-core/src/components/ApplicationLauncher/examples/ApplicationLauncherFavoritesAndSearch.tsx
<filename>packages/react-core/src/components/ApplicationLauncher/examples/ApplicationLauncherFavoritesAndSearch.tsx import React from 'react'; import { ApplicationLauncher, ApplicationLauncherItem, ApplicationLauncherGroup, ApplicationLauncherSeparator } from '@patternfly/react-core'; import pfLogoSm from './pf-logo-small.svg'; const icon: JSX.Element = <img src={pfLogoSm} />; const appLauncherItems: React.ReactElement[] = [ <ApplicationLauncherGroup key="group 1c"> <ApplicationLauncherItem key="group 1a" id="item-1" icon={icon}> Item without group title </ApplicationLauncherItem> <ApplicationLauncherSeparator key="separator" /> </ApplicationLauncherGroup>, <ApplicationLauncherGroup label="Group 2" key="group 2c"> <ApplicationLauncherItem key="group 2a" id="item-2" isExternal icon={icon} component="button"> Group 2 button </ApplicationLauncherItem> <ApplicationLauncherItem key="group 2b" id="item-3" isExternal href="#" icon={icon}> Group 2 anchor link </ApplicationLauncherItem> <ApplicationLauncherSeparator key="separator" /> </ApplicationLauncherGroup>, <ApplicationLauncherGroup label="Group 3" key="group 3c"> <ApplicationLauncherItem key="group 3a" id="item-4" isExternal icon={icon} component="button"> Group 3 button </ApplicationLauncherItem> <ApplicationLauncherItem key="group 3b" id="item-5" isExternal href="#" icon={icon}> Group 3 anchor link </ApplicationLauncherItem> </ApplicationLauncherGroup> ]; export const ApplicationLauncherFavoritesAndSearch: React.FunctionComponent = () => { const [isOpen, setIsOpen] = React.useState(false); const [favorites, setFavorites] = React.useState<string[]>([]); const [filteredItems, setFilteredItems] = React.useState<React.ReactNode[]>(null); const onToggle = (isOpen: boolean) => setIsOpen(isOpen); const onFavorite = (itemId: string, isFavorite: boolean) => { let updatedFavorites: string[] = [...favorites, itemId]; if (isFavorite) { updatedFavorites = favorites.filter(id => id !== itemId); } setFavorites(updatedFavorites); }; const onSearch = (textInput: string) => { if (textInput === '') { setFilteredItems(null); } else { const filteredGroups = appLauncherItems .map((group: React.ReactElement) => { const filteredGroup = React.cloneElement(group, { children: group.props.children.filter((item: React.ReactElement) => { if (item.type === ApplicationLauncherSeparator) { return item; } return item.props.children.toLowerCase().includes(textInput.toLowerCase()); }) }); if ( filteredGroup.props.children.length > 0 && filteredGroup.props.children[0].type !== ApplicationLauncherSeparator ) { return filteredGroup; } }) .filter(newGroup => newGroup); if (filteredGroups.length > 0) { let lastGroup = filteredGroups.pop(); lastGroup = React.cloneElement(lastGroup, { children: lastGroup.props.children.filter(item => item.type !== ApplicationLauncherSeparator) }); filteredGroups.push(lastGroup); } setFilteredItems(filteredGroups); } }; return ( <ApplicationLauncher onToggle={onToggle} onFavorite={onFavorite} onSearch={onSearch} isOpen={isOpen} items={filteredItems || appLauncherItems} favorites={favorites} isGrouped /> ); };
jelly/patternfly-react
packages/react-core/src/components/DatePicker/examples/DatePickerAmerican.tsx
<filename>packages/react-core/src/components/DatePicker/examples/DatePickerAmerican.tsx import React from 'react'; import { DatePicker } from '@patternfly/react-core'; export const DatePickerAmerican: React.FunctionComponent = () => { const dateFormat = (date: Date) => date.toLocaleDateString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '-'); const dateParse = (date: string) => { const split = date.split('-'); if (split.length !== 3) { return new Date(); } const month = split[0]; const day = split[1]; const year = split[2]; return new Date(`${year.padStart(4, '0')}-${month.padStart(2, '0')}-${day.padStart(2, '0')}T00:00:00`); }; return <DatePicker value="03-05-2020" placeholder="MM-DD-YYYY" dateFormat={dateFormat} dateParse={dateParse} />; };
jelly/patternfly-react
packages/react-topology/src/components/edges/terminals/index.ts
<reponame>jelly/patternfly-react export { default as ConnectorArrow } from './ConnectorArrow'; export { default as ConnectorArrowAlt } from './ConnectorArrowAlt'; export { default as ConnectorCircle } from './ConnectorCircle'; export { default as ConnectorCross } from './ConnectorCross'; export { default as ConnectorSquare } from './ConnectorSquare'; export { default as DefaultConnectorTerminal } from './DefaultConnectorTerminal'; export { default as EdgeConnectorArrow } from './DefaultConnectorTerminal'; // Backwards compatibility
jelly/patternfly-react
packages/react-core/src/components/MultipleFileUpload/__tests__/MultipleFileUploadTitleText.test.tsx
import React from 'react'; import { render, screen } from '@testing-library/react'; import { MultipleFileUploadTitleText } from '../MultipleFileUploadTitleText'; describe('MultipleFileUploadTitleText', () => { test('renders with expected class names', () => { const { asFragment } = render(<MultipleFileUploadTitleText>Foo</MultipleFileUploadTitleText>); expect(asFragment()).toMatchSnapshot(); }); test('renders custom class names', () => { const { asFragment } = render(<MultipleFileUploadTitleText className="test">Foo</MultipleFileUploadTitleText>); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/TopologyDemo/components/shapes/Path.tsx
<filename>packages/react-integration/demo-app-ts/src/components/demos/TopologyDemo/components/shapes/Path.tsx import { ShapeProps, useCombineRefs, useSvgAnchor } from '@patternfly/react-topology'; import * as React from 'react'; const Path: React.FunctionComponent<ShapeProps> = ({ className, width, height, filter, dndDropRef }) => { const anchorRef = useSvgAnchor(); const refs = useCombineRefs<SVGPathElement>(dndDropRef, anchorRef); return ( <path className={className} ref={refs} d={`M0 0 L${width / 2} ${height / 4} L${width} 0 L${width} ${height} L${width / 2} ${height - height / 4} L0 ${height} Z`} filter={filter} /> ); }; export default Path;
jelly/patternfly-react
packages/react-core/src/helpers/Popper/thirdparty/popper-core/modifiers/eventListeners.ts
// @ts-nocheck import { ModifierArguments, Modifier } from '../types'; import getWindow from '../dom-utils/getWindow'; // eslint-disable-next-line import/no-unused-modules export interface Options { scroll: boolean; resize: boolean; } const passive = { passive: true }; /** * */ function effect({ state, instance, options }: ModifierArguments<Options>) { const { scroll = true, resize = true } = options; const window = getWindow(state.elements.popper); const scrollParents = [...state.scrollParents.reference, ...state.scrollParents.popper]; if (scroll) { scrollParents.forEach(scrollParent => { scrollParent.addEventListener('scroll', instance.update, passive); }); } if (resize) { window.addEventListener('resize', instance.update, passive); } return () => { if (scroll) { scrollParents.forEach(scrollParent => { scrollParent.removeEventListener('scroll', instance.update, passive); }); } if (resize) { window.removeEventListener('resize', instance.update, passive); } }; } // eslint-disable-next-line import/no-unused-modules export type EventListenersModifier = Modifier<'eventListeners', Options>; export default { name: 'eventListeners', enabled: true, phase: 'write', fn: () => {}, effect, data: {} } as EventListenersModifier;
jelly/patternfly-react
packages/react-core/src/components/TextInputGroup/__tests__/TextInputGroup.test.tsx
import React from 'react'; import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom'; import { TextInputGroup, TextInputGroupContext } from '../TextInputGroup'; describe('TextInputGroup', () => { it('renders without children', () => { render(<TextInputGroup data-testid="TextInputGroup" />); expect(screen.getByTestId('TextInputGroup')).toBeVisible(); }); it('renders children', () => { render(<TextInputGroup>Test</TextInputGroup>); expect(screen.getByText('Test')).toBeVisible(); }); it('renders with class pf-c-text-input-group', () => { render(<TextInputGroup>Test</TextInputGroup>); const inputGroup = screen.getByText('Test'); expect(inputGroup).toHaveClass('pf-c-text-input-group'); }); it('renders with custom class names provided via prop', () => { render(<TextInputGroup className="custom-class">Test</TextInputGroup>); const inputGroup = screen.getByText('Test'); expect(inputGroup).toHaveClass('custom-class'); }); it('does not render with the pf-m-disabled class when not disabled', () => { render(<TextInputGroup>Test</TextInputGroup>); const inputGroup = screen.getByText('Test'); expect(inputGroup).not.toHaveClass('pf-m-disabled'); }); it('renders with the pf-m-disabled class when disabled', () => { render(<TextInputGroup isDisabled>Test</TextInputGroup>); const inputGroup = screen.getByText('Test'); expect(inputGroup).toHaveClass('pf-m-disabled'); }); it('passes isDisabled=false to children via a context when isDisabled prop is not passed', () => { const TestComponent: React.FunctionComponent = () => { const context = React.useContext(TextInputGroupContext); return <button disabled={context.isDisabled} />; }; render( <TextInputGroup> <TestComponent /> </TextInputGroup> ); const testComponent = screen.getByRole('button'); expect(testComponent).not.toBeDisabled(); }); it('passes isDisabled=true to children via a context when isDisabled prop is passed', () => { const TestComponent: React.FunctionComponent = () => { const context = React.useContext(TextInputGroupContext); return <button disabled={context.isDisabled} />; }; render( <TextInputGroup isDisabled> <TestComponent /> </TextInputGroup> ); const testComponent = screen.getByRole('button'); expect(testComponent).toBeDisabled(); }); it('matches the snapshot', () => { const { asFragment } = render(<TextInputGroup>Test</TextInputGroup>); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-charts/src/components/ChartTheme/themes/dark/green-color-theme.ts
<filename>packages/react-charts/src/components/ChartTheme/themes/dark/green-color-theme.ts<gh_stars>100-1000 /* eslint-disable camelcase */ import chart_color_green_100 from '@patternfly/react-tokens/dist/esm/chart_color_green_100'; import chart_color_green_200 from '@patternfly/react-tokens/dist/esm/chart_color_green_200'; import chart_color_green_300 from '@patternfly/react-tokens/dist/esm/chart_color_green_300'; import chart_color_green_400 from '@patternfly/react-tokens/dist/esm/chart_color_green_400'; import chart_color_green_500 from '@patternfly/react-tokens/dist/esm/chart_color_green_500'; import { ColorTheme } from '../color-theme'; // Color scale // See https://docs.google.com/document/d/1cw10pJFXWruB1SA8TQwituxn5Ss6KpxYPCOYGrH8qAY/edit const COLOR_SCALE = [ chart_color_green_300.value, chart_color_green_100.value, chart_color_green_500.value, chart_color_green_200.value, chart_color_green_400.value ]; export const DarkGreenColorTheme = ColorTheme({ COLOR_SCALE });
jelly/patternfly-react
packages/react-core/src/components/ClipboardCopy/__tests__/ClipboardCopyExpanded.test.tsx
import React from 'react'; import { render } from '@testing-library/react'; import { ClipboardCopyExpanded } from '../ClipboardCopyExpanded'; const props = { className: 'class-1', id: 'id-1' }; test('expanded content render', () => { const { asFragment } = render(<ClipboardCopyExpanded {...props}>This is my text</ClipboardCopyExpanded>); expect(asFragment()).toMatchSnapshot(); }); test('expanded code content render', () => { const { asFragment } = render( <ClipboardCopyExpanded isCode {...props}>{`{ "name": "@patternfly/react-core", "version": "1.33.2" }`}</ClipboardCopyExpanded> ); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-charts/src/components/ChartTheme/themes/axis-theme.ts
/* eslint-disable camelcase */ import chart_axis_grid_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_axis_grid_stroke_Color'; import chart_axis_tick_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_axis_tick_stroke_Color'; // Axis theme export const AxisTheme = { axis: { style: { grid: { stroke: chart_axis_grid_stroke_Color.value }, ticks: { stroke: chart_axis_tick_stroke_Color.value } } } };
jelly/patternfly-react
packages/react-core/src/components/Backdrop/examples/BackdropSpinner.tsx
<reponame>jelly/patternfly-react import React from 'react'; import { Backdrop, Spinner, Bullseye } from '@patternfly/react-core'; export const BackdropSpinner: React.FunctionComponent = () => ( <Backdrop> <Bullseye> <Spinner aria-label="Backdrop content" aria-valueText="Loading..." /> </Bullseye> </Backdrop> );
jelly/patternfly-react
packages/react-core/src/components/Divider/Divider.tsx
import * as React from 'react'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/Divider/divider'; import { formatBreakpointMods } from '../../helpers/util'; export enum DividerVariant { hr = 'hr', li = 'li', div = 'div' } export interface DividerProps extends React.HTMLProps<HTMLElement> { /** Additional classes added to the divider */ className?: string; /** The component type to use */ component?: 'hr' | 'li' | 'div'; /** @deprecated Use `orientation` instead. Flag to indicate the divider is vertical (must be in a flex layout) */ isVertical?: boolean; /** Insets at various breakpoints. */ inset?: { default?: 'insetNone' | 'insetXs' | 'insetSm' | 'insetMd' | 'insetLg' | 'insetXl' | 'inset2xl' | 'inset3xl'; sm?: 'insetNone' | 'insetXs' | 'insetSm' | 'insetMd' | 'insetLg' | 'insetXl' | 'inset2xl' | 'inset3xl'; md?: 'insetNone' | 'insetXs' | 'insetSm' | 'insetMd' | 'insetLg' | 'insetXl' | 'inset2xl' | 'inset3xl'; lg?: 'insetNone' | 'insetXs' | 'insetSm' | 'insetMd' | 'insetLg' | 'insetXl' | 'inset2xl' | 'inset3xl'; xl?: 'insetNone' | 'insetXs' | 'insetSm' | 'insetMd' | 'insetLg' | 'insetXl' | 'inset2xl' | 'inset3xl'; '2xl'?: 'insetNone' | 'insetXs' | 'insetSm' | 'insetMd' | 'insetLg' | 'insetXl' | 'inset2xl' | 'inset3xl'; }; /** Indicates how the divider will display at various breakpoints. Vertical divider must be in a flex layout. */ orientation?: { default?: 'vertical' | 'horizontal'; sm?: 'vertical' | 'horizontal'; md?: 'vertical' | 'horizontal'; lg?: 'vertical' | 'horizontal'; xl?: 'vertical' | 'horizontal'; '2xl'?: 'vertical' | 'horizontal'; }; } export const Divider: React.FunctionComponent<DividerProps> = ({ className, component = DividerVariant.hr, isVertical = false, inset, orientation, ...props }: DividerProps) => { const Component: any = component; return ( <Component className={css( styles.divider, isVertical && styles.modifiers.vertical, formatBreakpointMods(inset, styles), formatBreakpointMods(orientation, styles), className )} {...(component !== 'hr' && { role: 'separator' })} {...props} /> ); }; Divider.displayName = 'Divider';