repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
JRafael91/codeimage
apps/codeimage/src/core/floating-ui/floating-ui.tsx
<reponame>JRafael91/codeimage<gh_stars>0 import type { ComputePositionConfig, ComputePositionReturn, VirtualElement, } from '@floating-ui/core'; import {autoUpdate, computePosition, ReferenceElement} from '@floating-ui/dom'; import {createStore} from 'solid-js/store'; import {Accessor, createEffect, createSignal, mergeProps, on} from 'solid-js'; type Data = Omit<ComputePositionReturn, 'x' | 'y'> & { x: number | null; y: number | null; }; type UseFloatingReturn = Data & { update: () => void; setReference: (node: ReferenceElement | null) => void; setFloating: (node: ReferenceElement | null) => void; refs: { reference: Accessor<ReferenceElement | null>; floating: Accessor<ReferenceElement | null>; }; }; export type UseFloatingOptions = Omit< Partial<ComputePositionConfig>, 'platform' > & { runAutoUpdate?: boolean; }; export function useFloating({ middleware, placement, strategy, runAutoUpdate, }: UseFloatingOptions = {}): UseFloatingReturn { const [reference, setReference] = createSignal< Element | VirtualElement | null >(null); const [floating, setFloating] = createSignal<HTMLElement | null>(null); const [data, setData] = createStore<Data>({ x: null, y: null, strategy: strategy ?? 'absolute', placement: 'bottom', middlewareData: {}, }); const update = () => { const referenceEl = reference() as HTMLElement | null; const floatingEl = floating() as HTMLElement | null; if (!referenceEl || !floatingEl) { return; } function updater() { if (!referenceEl || !floatingEl) { return; } computePosition(referenceEl, floatingEl, { middleware: middleware, placement, strategy, }).then(data => setData(data)); } if (runAutoUpdate) { autoUpdate(referenceEl, floatingEl, updater, { animationFrame: true, ancestorResize: true, ancestorScroll: true, elementResize: true, }); } else { updater(); } }; createEffect(on([reference, floating], () => update())); const result = mergeProps(data, { update, setReference, setFloating, refs: { reference, floating, }, }); return result as UseFloatingReturn; }
JRafael91/codeimage
apps/codeimage/src/components/ui/Combobox/InlineCombobox.tsx
<reponame>JRafael91/codeimage import {LionCombobox} from '@lion/combobox'; import {css, html, PropertyValues} from '@lion/core'; import {LionOption} from '@lion/listbox'; import '@lion/combobox/define'; import '@lion/listbox/define'; import {map, Subject, takeUntil} from 'rxjs'; import {resizeObserverFactory$} from '../../../core/operators/create-resize-observer'; import {mutationObserverFactory$} from '../../../core/operators/create-mutation-observer'; interface InlineComboboxEventMap extends HTMLElementEventMap { selectedItem: CustomEvent<{value: string}>; } export class InlineCombobox extends LionCombobox { valueMapper?: (value: string) => string; placeholder: string | null | undefined; value: string | null | undefined; readonly destroy$ = new Subject<void>(); static get properties() { return { ...super.properties, placeholder: {type: String}, value: {type: String}, }; } get hiddenValueNode(): HTMLSpanElement | null { return this.shadowRoot?.querySelector('div.inline__item') ?? null; } get hiddenTextValue(): string { return this.value || this.placeholder || ''; } static styles = [ ...super.styles, css` :host { font-family: 'Inter', system-ui, -apple-system; display: inline-block; position: relative; appearance: none; } .input-group__container { border: none; } .inline__item { visibility: hidden; display: inline-block; height: 0; position: absolute; } ::slotted(.form-control) { background-color: transparent; color: inherit; appearance: none; outline: none; } ::slotted(.form-control) { padding: 0; margin: 0; outline: none !important; } `, ]; connectedCallback() { super.connectedCallback(); this.config = { placementMode: 'global', isTooltip: false, isBlocking: false, }; setTimeout(() => { this._inputNode.style.setProperty('appearance', 'none'); this._inputNode.style.setProperty('-webkit-appearance', 'none'); if (this.hiddenValueNode) { resizeObserverFactory$(this.hiddenValueNode, {box: 'content-box'}) .pipe( takeUntil(this.destroy$), map(entries => entries[0].contentRect.width), ) .subscribe(width => this.recalculateWidth(width)); mutationObserverFactory$(this._listboxNode.firstChild as HTMLElement, { childList: true, }) .pipe( map(() => this.formElements), map(() => (this.activeIndex === -1 ? 0 : this.activeIndex)), takeUntil(this.destroy$), ) .subscribe(activeIndex => (this.activeIndex = activeIndex)); } }); } addEventListener<K extends keyof InlineComboboxEventMap>( type: K, listener: (this: HTMLElement, ev: InlineComboboxEventMap[K]) => void, options?: boolean | AddEventListenerOptions, ): void; addEventListener( type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions, ): void { return super.addEventListener(type, listener, options); } removeEventListener<K extends keyof InlineComboboxEventMap>( type: K, listener: (this: HTMLElement, ev: InlineComboboxEventMap[K]) => void, options?: boolean | EventListenerOptions, ): void; removeEventListener( type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions, ): void { return super.removeEventListener(type, listener, options); } disconnectedCallback() { super.disconnectedCallback(); this.destroy$.next(); this.destroy$.complete(); } _getTextboxValueFromOption(option: ComboboxOption) { if (this.valueMapper) { return this.valueMapper(option.choiceValue); } return option.choiceValue; } protected _setTextboxValue(value: string) { super._setTextboxValue(value); this.dispatchEvent(new CustomEvent('inputTextChange', {detail: {value}})); } /** * ATTENTION: override overlay to append content into scaffold and inherit styles * @param config * @protected */ protected _defineOverlay( config: Parameters<LionCombobox['_defineOverlay']>[0], ): ReturnType<LionCombobox['_defineOverlay']> { const controller = super._defineOverlay(config); const portalHost = document.querySelector('#portal-host'); if (portalHost) { portalHost.appendChild(controller.content); } return controller; } protected update(changedProperties: PropertyValues) { if (changedProperties.has('placeholder')) { if (this.placeholder) { this._inputNode.setAttribute('placeholder', this.placeholder); } else { this._inputNode.removeAttribute('placeholder'); } } if (changedProperties.has('value')) { this._setTextboxValue(this.value ?? ''); } super.update(changedProperties); } private recalculateWidth(width: number): void { if (this.hiddenValueNode) { this.style.setProperty('width', `${width + 10}px`); } } protected render(): unknown { return html` ${super.render()} <div class="inline__item">${this.hiddenTextValue}</div> `; } protected _listboxOnKeyDown(ev: KeyboardEvent) { const {key} = ev; if ( this.opened && (key === 'Enter' || key === 'Tab') && this.activeIndex !== -1 ) { const value = this._getTextboxValueFromOption( this.formElements[this.activeIndex], ); this.dispatchEvent( new CustomEvent('selectedItemChange', {detail: {value}}), ); } super._listboxOnKeyDown(ev); } } class ComboboxOption extends LionOption { protected createRenderRoot(): Element | ShadowRoot { return this; } } customElements.define('cmg-inline-combobox', InlineCombobox); customElements.define('cmg-combobox-option', ComboboxOption); declare module 'solid-js' { // eslint-disable-next-line @typescript-eslint/no-namespace namespace JSX { interface IntrinsicElements { 'cmg-inline-combobox': Partial< InlineCombobox & JSX.DOMAttributes<InlineCombobox> & { // eslint-disable-next-line @typescript-eslint/no-explicit-any children: any; class: string; 'prop:valueMapper': InlineCombobox['valueMapper']; 'prop:autocomplete': InlineCombobox['autocomplete']; 'on:selectedItemChange': ( event: CustomEvent<{value: string}>, ) => void; 'on:inputTextChange': (event: CustomEvent<{value: string}>) => void; } >; 'cmg-combobox-option': Partial< ComboboxOption & JSX.DOMAttributes<ComboboxOption> & { // eslint-disable-next-line @typescript-eslint/no-explicit-any children: any; class: string; 'prop:choiceValue': ComboboxOption['choiceValue']; } >; } } } declare global { interface HTMLElementTagNameMap { 'cmg-inline-combobox': InlineCombobox; 'cmg-combobox-option': ComboboxOption; } }
JRafael91/codeimage
apps/codeimage/src/core/operators/create-resize-observer.ts
import {Observable} from 'rxjs'; const createResizeObserverFactory = () => { return (element: HTMLElement, options?: ResizeObserverOptions) => new ReactiveResizeObserver(element, options); }; class ReactiveResizeObserver extends Observable< ReadonlyArray<ResizeObserverEntry> > { constructor(element: HTMLElement, options?: ResizeObserverOptions) { let observer: ResizeObserver; super(subscriber => { observer = new ResizeObserver(entries => subscriber.next(entries)); observer.observe(element, options); return () => observer.disconnect(); }); } } export const resizeObserverFactory$ = createResizeObserverFactory();
JRafael91/codeimage
apps/codeimage/src/components/Terminal/TabName.tsx
<filename>apps/codeimage/src/components/Terminal/TabName.tsx import {createMemo, createSignal, For, JSXElement, onMount} from 'solid-js'; import {Box} from '../ui/Box/Box'; import * as styles from './terminal.css'; import {appEnvironment} from '../../core/configuration'; import {TabIcon} from './TabIcon'; import {highlight as _highlight} from '../../core/directives/highlight'; import '../ui/Combobox/InlineCombobox'; import {InlineCombobox} from '../ui/Combobox/InlineCombobox'; import createResizeObserver from '@solid-primitives/resize-observer'; import {useFloating} from '../../core/floating-ui/floating-ui'; interface TabNameProps { readonly: boolean; value?: string; onValueChange?: (value: string) => void; } const highlight = _highlight; export function TabName(props: TabNameProps): JSXElement { let ref: InlineCombobox; const hasDot = /^[a-zA-Z0-9$_-]{2,}\./; const [width, setWidth] = createSignal(0); const showHint = createMemo(() => hasDot.test(props.value ?? '')); function onChange(value: string): void { if (props.onValueChange) { props.onValueChange(value); } } const icons = appEnvironment.languages.flatMap(language => language.icons); const extension = createMemo(() => { if (!props.value) return ''; const extension = /\.[0-9a-z.]+$/i.exec(props.value); return (extension ? extension[0] : '').replace('.', ''); }); const matchedIcons = createMemo(() => { // TODO: remove this when icons will not be duplicated in configuration. const uniqueIcons = icons.filter( (icon, index, self) => index === self.findIndex(i => i.extension === icon.extension), ); if (!props.value) { return uniqueIcons; } const currentExtension = extension(); if (!currentExtension && props.value.endsWith('.')) { return uniqueIcons; } if (!currentExtension) return []; return uniqueIcons.filter(icon => icon.extension.includes(currentExtension), ); }); const getFormattedValue = (value: string) => { const sanitizedValue = props.value || ''; return sanitizedValue.replace(/\.([0-9a-z.]?)+$/i, `.${value}`); }; const floating = useFloating({ strategy: 'absolute', placement: 'bottom-start', runAutoUpdate: true, }); onMount(() => { const observe = createResizeObserver({ onResize: resize => setWidth(resize.width), }); observe(ref); }); return ( <cmg-inline-combobox ref={el => { ref = el; floating.setReference(el); }} name="tabName" value={props.value} placeholder={'Untitled'} onInput={event => onChange((event.target as HTMLInputElement).value)} on:selectedItemChange={event => setTimeout(() => onChange(event.detail.value)) } on:inputTextChange={event => onChange(event.detail.value)} prop:valueMapper={getFormattedValue} prop:autocomplete={'none'} > <Box ref={floating.setFloating} class={styles.tabHint} display={showHint() ? 'block' : 'none'} style={{ position: floating.strategy, top: `${floating.y ?? 0}px`, left: `${(floating.x ?? 0) + width() - 20}px`, }} > <For each={matchedIcons()}> {icon => { const value = icon.extension.replace('.', ''); return ( <cmg-combobox-option onClick={() => onChange(getFormattedValue(value))} class={styles.tabHintDropdownOption} prop:choiceValue={value} > <Box class={styles.tabHintDropdownItemContent}> <TabIcon delay={0} content={icon.content} /> <div use:highlight={extension()}>{icon.extension}</div> </Box> </cmg-combobox-option> ); }} </For> </Box> </cmg-inline-combobox> ); }
JRafael91/codeimage
apps/codeimage/src/core/operators/create-mutation-observer.ts
<reponame>JRafael91/codeimage import {Observable} from 'rxjs'; const createMutationObserverFactory = () => { return (element: HTMLElement, options?: MutationObserverInit) => new ReactiveMutationObserver(element, options); }; class ReactiveMutationObserver extends Observable< ReadonlyArray<MutationRecord> > { constructor(element: HTMLElement, options?: MutationObserverInit) { let observer: MutationObserver; super(subscriber => { observer = new MutationObserver(entries => subscriber.next(entries)); observer.observe(element, options); return () => observer.disconnect(); }); } } export const mutationObserverFactory$ = createMutationObserverFactory();
JRafael91/codeimage
apps/codeimage/src/core/directives/highlight.ts
import {createEffect, onMount} from 'solid-js'; export const svgNodeFilter: NodeFilter = (node: Node) => 'ownerSVGElement' in node ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT; export function highlight(el: HTMLElement, text: () => string): void { const highlightVar = '--highlight-color'; const treeWalker = document.createTreeWalker( el, NodeFilter.SHOW_TEXT, svgNodeFilter, // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore @bad typescript lib types false, ); el.style.position = 'relative'; el.style.zIndex = '0'; const highlightEl = prepareHighlightEl(); onMount(() => computeHighlight()); createEffect(() => computeHighlight()); function computeHighlight() { highlightEl.style.display = 'none'; const matched = getHighlightIndexOf(el.textContent) !== -1; if (!matched) { return; } treeWalker.currentNode = el; do { const index = getHighlightIndexOf(treeWalker.currentNode.nodeValue); if (index === -1) { continue; } const range = document.createRange(); range.setStart(treeWalker.currentNode, index); range.setEnd(treeWalker.currentNode, index + text().length); const hostRect = el.getBoundingClientRect(); const {left, top, width, height} = range.getBoundingClientRect(); const style = highlightEl.style; style.backgroundColor = `var(${highlightVar})`; style.left = toPx(left - hostRect.left); style.top = toPx(top - hostRect.top); style.width = toPx(width); style.height = toPx(height); style.display = 'block'; return; } while (treeWalker.nextNode()); } function getHighlightIndexOf(source: string | null): number { const highlight = text(); return !source || !highlight ? -1 : source.toLowerCase().indexOf(highlight.toLowerCase()); } function prepareHighlightEl(): HTMLElement { const highlight = document.createElement('div'); const {style} = highlight; style.backgroundColor = `var(${highlightVar})`; style.zIndex = '-1'; style.position = 'absolute'; onMount(() => el.appendChild(highlight)); return highlight; } function toPx(value: number): string { return `${value}px`; } } declare module 'solid-js' { // eslint-disable-next-line @typescript-eslint/no-namespace namespace JSX { interface Directives { highlight?: string; } } }
JRafael91/codeimage
apps/codeimage/src/components/Terminal/terminal.css.ts
import {createTheme, fallbackVar, style} from '@vanilla-extract/css'; import {themeVars} from '../../theme/global.css'; import {backgroundColorVar} from '../../theme/variables.css'; import {recipe} from '@vanilla-extract/recipes'; export const [terminalTheme, terminalVars] = createTheme({ headerHeight: '50px', headerBackgroundColor: themeVars.backgroundColor.white, backgroundColor: themeVars.backgroundColor.white, textColor: themeVars.backgroundColor.gray['800'], boxShadow: themeVars.boxShadow.lg, tabDelta: '10px', }); export const wrapper = style([ terminalTheme, { position: 'relative', backgroundColor: terminalVars.backgroundColor, color: terminalVars.textColor, overflow: 'hidden', borderRadius: '12px', boxShadow: terminalVars.boxShadow, transition: 'box-shadow .2s', }, ]); export const content = style({ position: 'relative', overflow: 'auto', fontSize: themeVars.fontSize.base, paddingBottom: themeVars.spacing['4'], paddingTop: themeVars.spacing['5'], paddingInlineStart: themeVars.spacing['4'], paddingInlineEnd: themeVars.spacing['4'], }); export const header = style({ display: 'flex', alignItems: 'center', position: 'relative', height: terminalVars.headerHeight, transition: 'background-color .2s ease-in-out', selectors: { '[data-theme-mode=light] &[data-accent-visible=true]': { backgroundColor: `rgba(0, 0, 0, .06)`, }, '[data-theme-mode=dark] &[data-accent-visible=true]': { backgroundColor: `rgba(255, 255, 255, .06)`, }, }, }); export const headerIconRow = style({ selectors: { [`${header} &`]: { display: 'flex', paddingInlineStart: themeVars.spacing['4'], paddingInlineEnd: themeVars.spacing['4'], columnGap: themeVars.spacing['2'], }, }, }); export const headerIconRowCircle = style({ selectors: { [`${headerIconRow} &`]: { width: '15px', height: '15px', borderRadius: themeVars.borderRadius.full, backgroundColor: fallbackVar( backgroundColorVar, themeVars.backgroundColor.gray['500'], ), }, }, }); export const tab = recipe({ base: { background: 'transparent', padding: `0 ${themeVars.spacing['3']}`, paddingLeft: 0, fontSize: themeVars.fontSize.sm, borderRadius: `${themeVars.borderRadius.md} ${themeVars.borderRadius.md} 0 0`, position: 'relative', lineHeight: 1, }, variants: { accent: { true: { /** * ATTENTION: this is a workaround related to https://github.com/riccardoperra/codeimage/issues/41 * Flex properties in safari are broken on export with HtmlToImage */ height: `calc(${terminalVars.headerHeight} - ${terminalVars.tabDelta})`, marginTop: 'auto', paddingTop: terminalVars.tabDelta, paddingLeft: themeVars.spacing['3'], backgroundColor: terminalVars.backgroundColor, selectors: { '&:before, &:after': { content: '', display: 'block', position: 'absolute', bottom: 0, backgroundColor: 'transparent', width: '8px', height: '8px', boxShadow: `1px 0px 0px 0px ${terminalVars.backgroundColor}, 3px 4px 0px 0px ${terminalVars.backgroundColor}`, overflow: 'hidden', }, }, ':before': { left: '-8px', borderBottomRightRadius: '8px', }, ':after': { right: '-8px', borderBottomRightRadius: '12px', transform: 'scaleX(-1)', }, }, }, }, }); export const tabIcon = style({ display: 'inline-block', marginRight: themeVars.spacing['2'], verticalAlign: 'middle', }); export const watermark = style({ position: 'absolute', right: '6px', bottom: '-6px', opacity: 0.35, backgroundColor: 'inherit', }); export const tabHint = style({ position: 'absolute', backgroundColor: themeVars.dynamicColors.dialogPanelBackgroundColor, boxShadow: themeVars.dynamicColors.dialogPanelShadow, borderRadius: themeVars.borderRadius.lg, zIndex: themeVars.zIndex['50'], maxHeight: '250px', overflowY: 'auto', left: 0, transition: 'all 100ms ease-in-out', }); export const tabHintDropdownOption = style({ outline: 'none', ':focus': { outline: 'none', }, ':focus-visible': { outline: 'none', }, }); export const tabHintDropdownItemContent = style({ height: '32px', fontWeight: themeVars.fontWeight.normal, fontSize: themeVars.fontSize.sm, display: 'flex', alignItems: 'center', padding: `0 ${themeVars.spacing['3']}`, borderBottom: `1px solid ${themeVars.dynamicColors.divider}`, color: themeVars.dynamicColors.listBoxTextColor, whiteSpace: 'nowrap', cursor: 'pointer', vars: { ['--highlight-color']: 'rgb(112, 182, 246, 0.25)', }, ':hover': { backgroundColor: themeVars.dynamicColors.listBoxHoverBackgroundColor, color: themeVars.dynamicColors.listBoxActiveTextColor, }, selectors: { ['[active] &']: { backgroundColor: themeVars.dynamicColors.listBoxActiveBackgroundColor, color: themeVars.dynamicColors.listBoxActiveTextColor, }, ['[aria-selected=true] &']: { backgroundColor: themeVars.dynamicColors.listBoxActiveBackgroundColor, color: themeVars.dynamicColors.listBoxActiveTextColor, }, }, });
freight-hub/quiz-producer
src/app.service.ts
<filename>src/app.service.ts import { Injectable, OnApplicationBootstrap, OnApplicationShutdown, } from '@nestjs/common'; import { readFileSync } from 'fs'; import { join } from 'path'; import { Client, ClientKafka } from '@nestjs/microservices'; import { microserviceConfig } from './microserviceConfig'; @Injectable() export class AppService implements OnApplicationBootstrap { @Client(microserviceConfig) client: ClientKafka; async onApplicationBootstrap(): Promise<any> { const producer = await this.client.connect(); const rawdata = readFileSync(join(process.cwd(), './data/basic.json')); const data = JSON.parse(rawdata.toLocaleString()); for (const event of data) { event.timestamp = new Date(event.timestamp); await producer.send({ topic: 'playing_with_projections_events', messages: [ { value: JSON.stringify(event), }, ], }); } } }
freight-hub/quiz-producer
src/microserviceConfig.ts
import { KafkaOptions, Transport } from '@nestjs/microservices'; export const microserviceConfig: KafkaOptions = { transport: Transport.KAFKA, options: { client: { clientId: 'quiz-producer', brokers: ['pkc-4r297.europe-west1.gcp.confluent.cloud:9092'], ssl: true, sasl: { mechanism: 'plain', username: '2XQ5Z2BKJ6QBNF57', password: '<PASSWORD>', }, }, }, };
simplaex/ngx-datatable
demo/app.component.ts
import { Component, ViewEncapsulation } from '@angular/core'; import { Location, LocationStrategy, HashLocationStrategy } from '@angular/common'; @Component({ selector: 'app', styleUrls: [ '../src/themes/material.scss', '../src/themes/dark.scss', '../src/themes/bootstrap.scss' ], encapsulation: ViewEncapsulation.None, providers: [ Location, { provide: LocationStrategy, useClass: HashLocationStrategy } ], template: ` <div [class.dark]="state === 'dark'"> <nav> <h3>ngx-datatable <small>({{version}})</small></h3> <ul class="main-ul"> <li> <h4>Documentation</h4> <ul> <li> <a href="https://swimlane.gitbooks.io/ngx-datatable/content/" target="_black">Online</a> </li> <li> <a href="https://www.gitbook.com/download/pdf/book/swimlane/ngx-datatable" target="_black">PDF</a> </li> </ul> </li> <li> <h4>Basic</h4> <ul> <li><a href="#virtual-scroll" (click)="state='virtual-scroll'">10k Rows</a></li> <li><a href="#full-screen" (click)="state='full-screen'">Full Screen</a></li> <li><a href="#inline-edit" (click)="state='inline-edit'">Inline Editing</a></li> <li><a href="#horz-vert-scrolling" (click)="state='horz-vert-scrolling'">Horz/Vert Scrolling</a></li> <li><a href="#horz-buttons-scroll" (click)="state='horz-buttons-scroll'">Horz Buttons Scroll</a></li> <li><a href="#multiple-tables" (click)="state='multiple-tables'">Multiple Tables</a></li> <li><a href="#filter" (click)="state='filter'">Filtering</a></li> <li><a href="#hidden" (click)="state='hidden'">Hidden On Load</a></li> <li><a href="#live" (click)="state='live'">Live Data</a></li> <li><a href="#rx" (click)="state='rx'">RxJS</a></li> <li><a href="#contextmenu" (click)="state='contextmenu'">Context Menu</a></li> <li><a href="#css" (click)="state='css'">CSS Classes</a></li> <li><a href="#footer" (click)="state='footer'">Footer Template</a></li> </ul> </li> <li> <h4>Themes</h4> <ul> <li><a href="#dark" (click)="state='dark'">Dark theme</a></li> <li><a href="#bootstrap" (click)="state='bootstrap'">Bootstrap theme</a></li> </ul> </li> <li> <h4>Rows</h4> <ul> <li><a href="#row-grouping" (click)="state='row-grouping'">Row Grouping</a></li> <li><a href="#" (click)="state=''">Fluid Row Height</a></li> <li><a href="#basic-fixed" (click)="state='basic-fixed'">Fixed Row Height</a></li> <li><a href="#dynamic" (click)="state='dynamic'">Dynamic Row Height</a></li> <li><a href="#row-details" (click)="state='row-details'">Row Detail</a></li> <li><a href="#responsive" (click)="state='responsive'">Responsive</a></li> </ul> </li> <li> <h4>Paging</h4> <ul> <li><a href="#client-paging" (click)="state='client-paging'">Client-side</a></li> <li><a href="#server-paging" (click)="state='server-paging'">Server-side</a></li> <li><a href="#server-scrolling" (click)="state='server-scrolling'">Scrolling server-side</a></li> <li><a href="#virtual-paging" (click)="state='virtual-paging'">Virtual server-side</a></li> </ul> </li> <li> <h4>Sorting</h4> <ul> <li><a href="#client-sorting" (click)="state='client-sorting'">Client-side</a></li> <li><a href="#default-sorting" (click)="state='default-sorting'">Default sort</a></li> <li><a href="#server-sorting" (click)="state='server-sorting'">Server-side</a></li> <li><a href="#comparator-sorting" (click)="state='comparator-sorting'">Comparator</a></li> </ul> </li> <li> <h4>Selection</h4> <ul> <li><a href="#cell-selection" (click)="state='cell-selection'">Cell</a></li> <li><a href="#single-selection" (click)="state='single-selection'">Single Row</a></li> <li><a href="#multi-selection" (click)="state='multi-selection'">Multi Row</a></li> <li><a href="#multi-click-selection" (click)="state='multi-click-selection'">Multi Click Row</a></li> <li><a href="#multidisable-selection" (click)="state='multidisable-selection'">Disable Callback</a></li> <li><a href="#chkbox-selection" (click)="state='chkbox-selection'">Checkbox</a></li> <li><a href="#chkbox-selection-template" (click)="state='chkbox-selection-template'">Custom Checkbox</a></li> </ul> </li> <li> <h4>Templates</h4> <ul> <li><a href="#inline" (click)="state='inline'">Inline</a></li> <li><a href="#templateref" (click)="state='templateref'">TemplateRef</a></li> </ul> </li> <li> <h4>Column</h4> <ul> <li><a href="#flex" (click)="state='flex'">Flex</a></li> <li><a href="#toggle" (click)="state='toggle'">Toggling</a></li> <li><a href="#fixed" (click)="state='fixed'">Fixed</a></li> <li><a href="#force" (click)="state='force'">Force</a></li> <li><a href="#pinning" (click)="state='pinning'">Pinning</a></li> <li><a href="#reorder" (click)="state='reorder'">Reorder</a></li> </ul> </li> <li> <h4>Summary Row</h4> <ul> <li><a href="#simple-summary" (click)="state='simple-summary'">Simple</a></li> <li><a href="#custom-template-summary" (click)="state='custom-template-summary'">Custom Template</a></li> <li><a href="#paging-summary" (click)="state='paging-summary'">Server-side paging</a></li> <li><a href="#inline-html-summary" (click)="state='inline-html-summary'">Inline HTML</a></li> </ul> </li> </ul> </nav> <content> <!-- Basic --> <basic-auto-demo *ngIf="!state"></basic-auto-demo> <basic-fixed-demo *ngIf="state === 'basic-fixed'"></basic-fixed-demo> <full-screen-demo *ngIf="state === 'full-screen'"></full-screen-demo> <inline-edit-demo *ngIf="state === 'inline-edit'"></inline-edit-demo> <virtual-scroll-demo *ngIf="state === 'virtual-scroll'"></virtual-scroll-demo> <horz-vert-scrolling-demo *ngIf="state === 'horz-vert-scrolling'"></horz-vert-scrolling-demo> <horz-buttons-scroll-demo *ngIf="state === 'horz-buttons-scroll'"></horz-buttons-scroll-demo> <multiple-tables-demo *ngIf="state === 'multiple-tables'"></multiple-tables-demo> <row-details-demo *ngIf="state === 'row-details'"></row-details-demo> <responsive-demo *ngIf="state === 'responsive'"></responsive-demo> <filter-demo *ngIf="state === 'filter'"></filter-demo> <tabs-demo *ngIf="state === 'hidden'"></tabs-demo> <live-data-demo *ngIf="state === 'live'"></live-data-demo> <rx-demo *ngIf="state === 'rx'"></rx-demo> <contextmenu-demo *ngIf="state === 'contextmenu'"></contextmenu-demo> <row-css-demo *ngIf="state === 'css'"></row-css-demo> <dynamic-height-demo *ngIf="state === 'dynamic'"></dynamic-height-demo> <footer-demo *ngIf="state === 'footer'"></footer-demo> <!-- Themes --> <basic-dark-theme-demo *ngIf="state === 'dark'"></basic-dark-theme-demo> <basic-bootstrap-theme-demo *ngIf="state === 'bootstrap'"></basic-bootstrap-theme-demo> <!-- Paging --> <row-grouping-demo *ngIf="state === 'row-grouping'"></row-grouping-demo> <client-paging-demo *ngIf="state === 'client-paging'"></client-paging-demo> <server-paging-demo *ngIf="state === 'server-paging'"></server-paging-demo> <server-scrolling-demo *ngIf="state === 'server-scrolling'"></server-scrolling-demo> <virtual-paging-demo *ngIf="state === 'virtual-paging'"></virtual-paging-demo> <!-- Sorting --> <client-sorting-demo *ngIf="state === 'client-sorting'"></client-sorting-demo> <default-sorting-demo *ngIf="state === 'default-sorting'"></default-sorting-demo> <server-sorting-demo *ngIf="state === 'server-sorting'"></server-sorting-demo> <comparator-sorting-demo *ngIf="state === 'comparator-sorting'"></comparator-sorting-demo> <!-- Selection --> <cell-selection-demo *ngIf="state === 'cell-selection'"></cell-selection-demo> <single-selection-demo *ngIf="state === 'single-selection'"></single-selection-demo> <multi-selection-demo *ngIf="state === 'multi-selection'"></multi-selection-demo> <multidisable-selection-demo *ngIf="state === 'multidisable-selection'"></multidisable-selection-demo> <chkbox-selection-demo *ngIf="state === 'chkbox-selection'"></chkbox-selection-demo> <chkbox-selection-template-demo *ngIf="state === 'chkbox-selection-template'"></chkbox-selection-template-demo> <multi-click-selection-demo *ngIf="state === 'multi-click-selection'"></multi-click-selection-demo> <!-- Templates --> <template-ref-demo *ngIf="state === 'templateref'"></template-ref-demo> <inline-templates-demo *ngIf="state === 'inline'"></inline-templates-demo> <!-- Columns --> <column-flex-demo *ngIf="state === 'flex'"></column-flex-demo> <column-toggle-demo *ngIf="state === 'toggle'"></column-toggle-demo> <column-standard-demo *ngIf="state === 'fixed'"></column-standard-demo> <column-force-demo *ngIf="state === 'force'"></column-force-demo> <column-pinning-demo *ngIf="state === 'pinning'"></column-pinning-demo> <column-reorder-demo *ngIf="state === 'reorder'"></column-reorder-demo> <!-- Summary row --> <summary-row-simple-demo *ngIf="state === 'simple-summary'"></summary-row-simple-demo> <summary-row-custom-template-demo *ngIf="state === 'custom-template-summary'"> </summary-row-custom-template-demo> <summary-row-server-paging-demo *ngIf="state === 'paging-summary'"> </summary-row-server-paging-demo> <summary-row-inline-html *ngIf="state === 'inline-html-summary'"></summary-row-inline-html> </content> </div> ` }) export class AppComponent { get state() { return window.state; } set state(state) { window.state = state; } version: string = APP_VERSION; constructor(location: Location) { this.state = location.path(true); } }
simplaex/ngx-datatable
demo/basic/horz-buttons-scroll.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'horz-buttons-scroll-demo', template: ` <div> <h3> Horizontal Buttons Scroll <small> <a href="https://github.com/swimlane/ngx-datatable/blob/master/demo/basic/scrolling.component.ts" target="_blank" > Source </a> </small> </h3> <div style='float:left;width:75%'> <ngx-datatable class="material" [rows]="rows" columnMode="force" [headerHeight]="50" [footerHeight]="0" [rowHeight]="50" [scrollbarV]="true" [scrollbarH]="true"> <ngx-datatable-column *ngFor="let col of columns" [name]="col.name" [prop]="col.prop"> </ngx-datatable-column> </ngx-datatable> </div> <div class='selected-column'> <h4>Available Columns</h4> <ul> <li *ngFor='let col of allColumns'> <input type='checkbox' [id]="col.name" (click)='toggle(col)' [checked]='isChecked(col)' /> <label [attr.for]="col.name">{{col.name}}</label> </li> </ul> </div> </div> ` }) export class HorzButtonsScroll { rows = []; allColumns = [ { name: 'Name', prop: 'name' }, { name: 'Gender', prop: 'gender' }, { name: 'Age', prop: 'age' }, { name: 'City', prop: 'address.city' }, { name: 'State', prop: 'address.state' }, ]; columns = [ { name: 'Name', prop: 'name' }, { name: 'Gender', prop: 'gender' }, { name: 'Age', prop: 'age' }, { name: 'City', prop: 'address.city' }, { name: 'State', prop: 'address.state' }, ]; constructor() { this.fetch((data) => { this.rows = data; }); } toggle(col) { const isChecked = this.isChecked(col); if(isChecked) { this.columns = this.columns.filter(c => { return c.name !== col.name; }); } else { this.columns = [...this.columns, col]; } } fetch(cb) { const req = new XMLHttpRequest(); req.open('GET', `assets/data/100k.json`); req.onload = () => { cb(JSON.parse(req.response)); }; req.send(); } private isChecked(col) { return this.columns.find(c => { return c.name === col.name; }); } }
vincenteof/valtio
tests/getter.test.tsx
<gh_stars>1-10 import React, { StrictMode } from 'react' import { fireEvent, render, waitFor } from '@testing-library/react' import { proxy, useSnapshot } from '../src/index' const consoleError = console.error beforeEach(() => { console.error = jest.fn((message) => { if ( process.env.NODE_ENV === 'production' && message.startsWith('act(...) is not supported in production') ) { return } consoleError(message) }) }) afterEach(() => { console.error = consoleError }) it('simple object getters', async () => { const computeDouble = jest.fn((x) => x * 2) const state = proxy({ count: 0, get doubled() { return computeDouble(this.count) }, }) const Counter: React.FC<{ name: string }> = ({ name }) => { const snap = useSnapshot(state) return ( <> <div> {name} count: {snap.doubled} </div> <button onClick={() => ++state.count}>{name} button</button> </> ) } const { getByText } = render( <StrictMode> <Counter name="A" /> <Counter name="B" /> </StrictMode> ) await waitFor(() => { getByText('A count: 0') getByText('B count: 0') }) computeDouble.mockClear() fireEvent.click(getByText('A button')) await waitFor(() => { getByText('A count: 2') getByText('B count: 2') }) expect(computeDouble).toBeCalledTimes(1) }) it('object getters returning object', async () => { const computeDouble = jest.fn((x) => x * 2) const state = proxy({ count: 0, get doubled() { return { value: computeDouble(this.count) } }, }) const Counter: React.FC<{ name: string }> = ({ name }) => { const snap = useSnapshot(state) return ( <> <div> {name} count: {snap.doubled.value} </div> <button onClick={() => ++state.count}>{name} button</button> </> ) } const { getByText } = render( <StrictMode> <Counter name="A" /> <Counter name="B" /> </StrictMode> ) await waitFor(() => { getByText('A count: 0') getByText('B count: 0') }) computeDouble.mockClear() fireEvent.click(getByText('A button')) await waitFor(() => { getByText('A count: 2') getByText('B count: 2') }) expect(computeDouble).toBeCalledTimes(1) })
vincenteof/valtio
tests/ref.test.tsx
import React, { StrictMode, useRef, useEffect } from 'react' import { fireEvent, render } from '@testing-library/react' import { proxy, ref, useSnapshot } from '../src/index' const consoleError = console.error beforeEach(() => { console.error = jest.fn((message) => { if ( process.env.NODE_ENV === 'production' && message.startsWith('act(...) is not supported in production') ) { return } consoleError(message) }) }) afterEach(() => { console.error = consoleError }) it('should trigger re-render setting objects with ref wrapper', async () => { const obj = proxy({ nested: ref({ count: 0 }) }) const Counter: React.FC = () => { const snap = useSnapshot(obj) const commitsRef = useRef(1) useEffect(() => { commitsRef.current += 1 }) return ( <> <div> count: {snap.nested.count} ({commitsRef.current}) </div> <button onClick={() => (obj.nested = ref({ count: 0 }))}>button</button> </> ) } const { getByText, findByText } = render( <StrictMode> <Counter /> </StrictMode> ) await findByText('count: 0 (1)') fireEvent.click(getByText('button')) await findByText('count: 0 (2)') }) it('should not track object wrapped in ref assigned to proxy state', async () => { const obj = proxy<{ ui: JSX.Element | null }>({ ui: null }) const Component: React.FC = () => { const snap = useSnapshot(obj) return ( <> {snap.ui || <span>original</span>} <button onClick={() => (obj.ui = ref(<span>replace</span>))}> button </button> </> ) } const { getByText, findByText } = render( <StrictMode> <Component /> </StrictMode> ) await findByText('original') fireEvent.click(getByText('button')) await findByText('replace') }) it('should not trigger re-render when mutating object wrapped in ref', async () => { const obj = proxy({ nested: ref({ count: 0 }) }) const Counter: React.FC = () => { const snap = useSnapshot(obj) return ( <> <div>count: {snap.nested.count}</div> <button onClick={() => ++obj.nested.count}>button</button> </> ) } const { getByText, findByText } = render( <StrictMode> <Counter /> </StrictMode> ) await findByText('count: 0') fireEvent.click(getByText('button')) await findByText('count: 0') })
vincenteof/valtio
src/utils/watch.ts
<filename>src/utils/watch.ts import { subscribe } from '../vanilla' type WatchGet = <T extends object>(value: T) => T type WatchCallback = (get: WatchGet) => (() => void) | void | undefined let currentCleanups: Set<() => void> | undefined /** * watch * * Creates a reactive effect that automatically tracks proxy objects and * reevaluates everytime one of the tracked proxy objects updates. It returns * a cleanup function to stop the reactive effect from reevaluating. * * Callback is invoked immediately to detect the tracked objects. * * Callback passed to `watch` receives a `get` function that "tracks" the * passed proxy object. * * Watch callbacks may return an optional cleanup function, which is evaluated * whenever the callback reevaluates or when the cleanup function returned by * `watch` is evaluated. * * `watch` calls inside `watch` are also automatically tracked and cleaned up * whenever the parent `watch` reevaluates. * * @param callback * @returns A cleanup function that stops the callback from reevaluating and * also performs cleanups registered into `watch`. */ export const watch = (callback: WatchCallback): (() => void) => { const cleanups = new Set<() => void>() const subscriptions = new Set<object>() let alive = true const cleanup = () => { // Cleanup subscriptions and other pushed callbacks cleanups.forEach((clean) => { clean() }) // Clear cleanup set cleanups.clear() // Clear tracked proxies subscriptions.clear() } const revalidate = () => { if (!alive) { return } cleanup() // Setup watch context, this allows us to automatically capture // watch cleanups if the watch callback itself has watch calls. const parent = currentCleanups currentCleanups = cleanups // Ensures that the parent is reset if the callback throws an error. try { const cleanupReturn = callback((proxy) => { subscriptions.add(proxy) return proxy }) // If there's a cleanup, we add this to the cleanups set if (cleanupReturn) { cleanups.add(cleanupReturn) } } finally { currentCleanups = parent } // Subscribe to all collected proxies subscriptions.forEach((proxy) => { const clean = subscribe(proxy, revalidate) cleanups.add(clean) }) } const wrappedCleanup = () => { if (alive) { cleanup() alive = false } } // If there's a parent watch call, we attach this watch's // cleanup to the parent. if (currentCleanups) { currentCleanups.add(wrappedCleanup) } // Invoke effect to create subscription list revalidate() return wrappedCleanup }
vincenteof/valtio
tests/mapset.test.tsx
import React, { StrictMode } from 'react' import { fireEvent, render } from '@testing-library/react' import { proxy, useSnapshot } from '../src/index' const consoleError = console.error beforeEach(() => { console.error = jest.fn((message) => { if ( process.env.NODE_ENV === 'production' && message.startsWith('act(...) is not supported in production') ) { return } consoleError(message) }) }) afterEach(() => { console.error = consoleError }) it('unsupported map', async () => { const obj = proxy({ map: new Map([['count', 0]]) }) const Counter: React.FC = () => { const snap = useSnapshot(obj) as any return ( <> <div>count: {snap.map.get('count')}</div> <button onClick={() => obj.map.set('count', 1)}>button</button> </> ) } const { getByText, findByText } = render( <StrictMode> <Counter /> </StrictMode> ) await findByText('count: 0') fireEvent.click(getByText('button')) await new Promise((resolve) => setTimeout(resolve, 10)) // FIXME better way? expect(() => getByText('count: 1')).toThrow() }) it('unsupported set', async () => { const obj = proxy({ set: new Set([1, 2, 3]) }) const Counter: React.FC = () => { const snap = useSnapshot(obj) as any return ( <> <div>count: {[...snap.set].join(',')}</div> <button onClick={() => obj.set.add(4)}>button</button> </> ) } const { getByText, findByText } = render( <StrictMode> <Counter /> </StrictMode> ) await findByText('count: 1,2,3') fireEvent.click(getByText('button')) await new Promise((resolve) => setTimeout(resolve, 10)) // FIXME better way? expect(() => getByText('count: 1,2,3,4')).toThrow() })
vincenteof/valtio
src/utils/subscribeKey.ts
import { subscribe } from '../vanilla' /** * subscribeKey * * The subscribeKey utility enables subscription to a primitive subproperty of a given state proxy. * Subscriptions created with subscribeKey will only fire when the specified property changes. * notifyInSync: same as the parameter to subscribe(); true disables batching of subscriptions. * * @example * import { subscribeKey } from 'valtio/utils' * subscribeKey(state, 'count', (v) => console.log('state.count has changed to', v)) */ export const subscribeKey = <T extends object>( proxyObject: T, key: keyof T, callback: (value: T[typeof key]) => void, notifyInSync?: boolean ) => subscribe( proxyObject, (ops) => { if (ops.some((op) => op[1][0] === key)) { callback(proxyObject[key]) } }, notifyInSync )
vincenteof/valtio
src/react.ts
<filename>src/react.ts import { useCallback, useDebugValue, useEffect, useLayoutEffect, useMemo, useReducer, useRef, } from 'react' import { createProxy as createProxyToCompare, isChanged, affectedToPathList, } from 'proxy-compare' import { getVersion, subscribe, snapshot } from './vanilla' import { createMutableSource, useMutableSource } from './useMutableSource' import type { DeepResolveType } from './vanilla' const isSSR = typeof window === 'undefined' || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent) const useIsomorphicLayoutEffect = isSSR ? useEffect : useLayoutEffect const useAffectedDebugValue = <State>( state: State, affected: WeakMap<object, unknown> ) => { const pathList = useRef<(string | number | symbol)[][]>() useEffect(() => { pathList.current = affectedToPathList(state, affected) }) useDebugValue(pathList.current) } type MutableSource = any const mutableSourceCache = new WeakMap<object, MutableSource>() const getMutableSource = (proxyObject: any): MutableSource => { if (!mutableSourceCache.has(proxyObject)) { mutableSourceCache.set( proxyObject, createMutableSource(proxyObject, getVersion) ) } return mutableSourceCache.get(proxyObject) as MutableSource } type Options = { sync?: boolean } /** * useSnapshot * * Create a local snapshot that catches changes. This hook actually returns a wrapped snapshot in a proxy for * render optimization instead of a plain object compared to `snapshot()` method. * Rule of thumb: read from snapshots, mutate the source. * The component will only re-render when the parts of the state you access have changed, it is render-optimized. * * @example A * function Counter() { * const snap = useSnapshot(state) * return ( * <div> * {snap.count} * <button onClick={() => ++state.count}>+1</button> * </div> * ) * } * * [Notes] * Every object inside your proxy also becomes a proxy (if you don't use "ref"), so you can also use them to create * the local snapshot as seen on example B. * * @example B * function ProfileName() { * const snap = useSnapshot(state.profile) * return ( * <div> * {snap.name} * </div> * ) * } * * Beware that you still can replace the child proxy with something else so it will break your snapshot. You can see * above what happens with the original proxy when you replace the child proxy. * * > console.log(state) * { profile: { name: "valtio" } } * > childState = state.profile * > console.log(childState) * { name: "valtio" } * > state.profile.name = "react" * > console.log(childState) * { name: "react" } * > state.profile = { name: "<NAME>" } * > console.log(childState) * { name: "react" } * > console.log(state) * { profile: { name: "<NAME>" } } * * `useSnapshot()` depends on the original reference of the child proxy so if you replace it with a new one, the component * that is subscribed to the old proxy won't receive new updates because it is still subscribed to the old one. * * In this case we recommend the example C or D. On both examples you don't need to worry with re-render, * because it is render-optimized. * * @example C * const snap = useSnapshot(state) * return ( * <div> * {snap.profile.name} * </div> * ) * * @example D * const { profile } = useSnapshot(state) * return ( * <div> * {profile.name} * </div> * ) */ export const useSnapshot = <T extends object>( proxyObject: T, options?: Options ): DeepResolveType<T> => { const forceUpdate = useReducer((c) => c + 1, 0)[1] const affected = new WeakMap() const lastAffected = useRef<typeof affected>() const prevSnapshot = useRef<DeepResolveType<T>>() const lastSnapshot = useRef<DeepResolveType<T>>() useIsomorphicLayoutEffect(() => { lastSnapshot.current = prevSnapshot.current = snapshot(proxyObject) }, [proxyObject]) useIsomorphicLayoutEffect(() => { lastAffected.current = affected if ( prevSnapshot.current !== lastSnapshot.current && isChanged( prevSnapshot.current, lastSnapshot.current, affected, new WeakMap() ) ) { prevSnapshot.current = lastSnapshot.current forceUpdate() } }) const notifyInSync = options?.sync const sub = useCallback( (proxyObject: T, cb: () => void) => subscribe( proxyObject, () => { const nextSnapshot = snapshot(proxyObject) lastSnapshot.current = nextSnapshot try { if ( lastAffected.current && !isChanged( prevSnapshot.current, nextSnapshot, lastAffected.current, new WeakMap() ) ) { // not changed return } } catch (e) { // ignore if a promise or something is thrown } prevSnapshot.current = nextSnapshot cb() }, notifyInSync ), [notifyInSync] ) const currSnapshot = useMutableSource( getMutableSource(proxyObject), snapshot, sub ) if (typeof process === 'object' && process.env.NODE_ENV !== 'production') { // eslint-disable-next-line react-hooks/rules-of-hooks useAffectedDebugValue(currSnapshot, affected) } const proxyCache = useMemo(() => new WeakMap(), []) // per-hook proxyCache return createProxyToCompare(currSnapshot, affected, proxyCache) }
uranussolutions/minhdu-logger
src/api/system/entities/system.entity.ts
<reponame>uranussolutions/minhdu-logger<gh_stars>0 import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; import { APP_NAME } from 'src/core/enum/app-name.enum'; export type SystemDocument = System & Document; @Schema() export class System { @Prop() appName: APP_NAME;0 @Prop() age: number; @Prop() breed: string; } export const SystemSchema = SchemaFactory.createForClass(System);
uranussolutions/minhdu-logger
src/api/system/dto/update-system.dto.ts
<filename>src/api/system/dto/update-system.dto.ts import { PartialType } from '@nestjs/mapped-types'; import { CreateSystemDto } from './create-system.dto'; export class UpdateSystemDto extends PartialType(CreateSystemDto) {}
uranussolutions/minhdu-logger
src/api/system/system.service.ts
import { Injectable } from '@nestjs/common'; import { CreateSystemDto } from './dto/create-system.dto'; import { UpdateSystemDto } from './dto/update-system.dto'; @Injectable() export class SystemService { create(createSystemDto: CreateSystemDto) { return 'This action adds a new system'; } findAll() { return `This action returns all system`; } findOne(id: number) { return `This action returns a #${id} system`; } update(id: number, updateSystemDto: UpdateSystemDto) { return `This action updates a #${id} system`; } remove(id: number) { return `This action removes a #${id} system`; } }
uranussolutions/minhdu-logger
src/core/enum/app-name.enum.ts
<filename>src/core/enum/app-name.enum.ts export enum APP_NAME { HR = 'HR', SELL = 'SELL', }
uranussolutions/minhdu-logger
src/api/system/system.controller.ts
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common'; import { SystemService } from './system.service'; import { CreateSystemDto } from './dto/create-system.dto'; import { UpdateSystemDto } from './dto/update-system.dto'; @Controller('system') export class SystemController { constructor(private readonly systemService: SystemService) {} @Post() create(@Body() createSystemDto: CreateSystemDto) { return this.systemService.create(createSystemDto); } @Get() findAll() { return this.systemService.findAll(); } @Get(':id') findOne(@Param('id') id: string) { return this.systemService.findOne(+id); } @Patch(':id') update(@Param('id') id: string, @Body() updateSystemDto: UpdateSystemDto) { return this.systemService.update(+id, updateSystemDto); } @Delete(':id') remove(@Param('id') id: string) { return this.systemService.remove(+id); } }
uranussolutions/minhdu-logger
src/api/system/dto/create-system.dto.ts
<gh_stars>0 export class CreateSystemDto {}
Nfinished/react-tiny-modal
test/Modal.test.tsx
import React from 'react' import { render, fireEvent, screen, cleanup, waitForElementToBeRemoved } from '@testing-library/react' import '@testing-library/jest-dom' import { Modal, ModalProps } from '../src' type WrapperProps = Partial<ModalProps> const Wrapper: React.FC<WrapperProps> = overrides => { const [showModal, setShowModal] = React.useState(true) const props = { isOpen: showModal, onClose: () => setShowModal(false), ...overrides, } return ( <div data-testid="container"> <Modal data-testid="modal" {...props}> <button onClick={() => setShowModal(false)} data-testid="closeButton"> click me to close! </button> </Modal> </div> ) } afterEach(cleanup) describe('Modal', () => { describe('Mounting', () => { it('should be in the dom', () => { render(<Wrapper />) expect(screen.getByTestId('modal')).toBeInTheDocument() }) }) describe('Unmounting', () => { it('Unmounts on close', () => { render(<Wrapper />) waitForElementToBeRemoved(screen.queryByTestId('modal')) fireEvent.click(screen.getByTestId('closeButton')) }) }) })
Nfinished/react-tiny-modal
src/types/index.ts
export interface ModalProps extends React.ComponentPropsWithoutRef<'div'> { isOpen: boolean onClose?: React.MouseEventHandler portalElement?: Element }
Nfinished/react-tiny-modal
src/components/Modal/index.tsx
<filename>src/components/Modal/index.tsx<gh_stars>0 import React from 'react' import ReactDOM from 'react-dom' import { useOnClickOutside } from '../../hooks' import { ModalProps } from '../../types' import { combineClassNames } from '../../utils' import './styles.css' export const Modal: React.FC<ModalProps> = ({ className, isOpen, onClose = () => {}, portalElement = document.body, onAnimationEnd, children, ...rest }) => { const [shouldRender, setShouldRender] = React.useState(isOpen) const ref = React.useRef<HTMLDivElement>(null) React.useEffect(() => { if (isOpen) setShouldRender(true) }, [isOpen]) useOnClickOutside(ref, onClose) const handleAnimationEnd: React.AnimationEventHandler<HTMLDivElement> = e => { onAnimationEnd && onAnimationEnd(e) if (!isOpen) setShouldRender(false) } if (!shouldRender) return null return ReactDOM.createPortal( <div className={combineClassNames('_rtm-container', isOpen && '_rtm-container--open', className)} onAnimationEnd={handleAnimationEnd} {...rest} > <div ref={ref}>{children}</div> </div>, portalElement, ) }
Nfinished/react-tiny-modal
example/index.tsx
import * as React from 'react' import * as ReactDOM from 'react-dom' import { Modal } from '../' import 'bulma/css/bulma.css' import './styles.css' const App = () => { const [showModal, setShowModal] = React.useState(true) return ( <> <div>I'm behind the modal</div> <button className="button" onClick={() => setShowModal(true)}> click me </button> <Modal onClose={() => setShowModal(false)} isOpen={showModal}> <p> hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello!hello! </p> <button className="button" onClick={() => setShowModal(false)}> click me to close! </button> </Modal> </> ) } ReactDOM.render(<App />, document.getElementById('root'))
raulrozza/Gametask_Mobile
src/modules/selectedGame/infra/routes/home.routes.tsx
<filename>src/modules/selectedGame/infra/routes/home.routes.tsx import React from 'react'; // Navigation import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs'; // Pages import Feed from 'modules/selectedGame/view/pages/Feed'; import Ranking from 'modules/selectedGame/view/pages/Ranking'; import { useThemeContext } from 'shared/view/contexts'; const Tab = createMaterialTopTabNavigator(); const SelectedGameHome: React.FC = () => { const { theme } = useThemeContext(); return ( <Tab.Navigator tabBarOptions={{ activeTintColor: theme.palette.secondary.main, inactiveTintColor: theme.palette.primary.contrast, pressColor: theme.palette.primary.dark, indicatorContainerStyle: { backgroundColor: theme.palette.primary.main, }, indicatorStyle: { backgroundColor: theme.palette.secondary.main, }, }} > <Tab.Screen name="Atividades Recentes" component={Feed} /> <Tab.Screen name="Ranking" component={Ranking} /> </Tab.Navigator> ); }; export default SelectedGameHome;
raulrozza/Gametask_Mobile
src/modules/chooseGame/view/pages/Lobby/components/EmptyList/styles.ts
import { Typography } from 'shared/view/components'; import styled from 'styled-components/native'; export const Container = styled.View` padding: ${({ theme }) => theme.layout.spacing(4, 0)}; `; export const Text = styled(Typography)` color: ${({ theme }) => theme.palette.primary.contrast}; font-size: 18px; text-align: center; `;
raulrozza/Gametask_Mobile
src/modules/selectedGame/services/factories/makeGetCurrentLeaderboard.ts
import makeLeaderboardsRepository from 'modules/selectedGame/infra/repositories/factories/makeLeaderboardsRepository'; import GetCurrentLeaderboard from 'modules/selectedGame/services/GetCurrentLeaderboard'; export default function makeGetCurrentLeaderboard(): GetCurrentLeaderboard { const repository = makeLeaderboardsRepository(); return new GetCurrentLeaderboard(repository); }
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/components/UserImage/index.tsx
<gh_stars>0 import React from 'react'; import { Image, ImageStyle, StyleProp } from 'react-native'; interface UserImageProps { image?: string; style?: StyleProp<ImageStyle>; } const UserImage: React.FC<UserImageProps> = ({ image, style }) => ( <Image style={style} source={ image ? { uri: image, } : require('assets/img/users/placeholder.png') } /> ); export default UserImage;
raulrozza/Gametask_Mobile
src/modules/selectedGame/infra/routes/game.tsx
import React from 'react'; import { IGameRouteScreen } from 'shared/infra/routes/game'; // Icons import { FontAwesome, Feather, MaterialCommunityIcons, } from '@expo/vector-icons'; // Pages import ProfileRoutes from './profile.routes'; import ActivitiesRoutes from './activities.routes'; import SelectedGameHome from './home.routes'; const SelectedGameGameRoutes = ( Screen: IGameRouteScreen, ): React.ReactNode[] => [ <Screen key="selected-game-home" options={{ title: 'Principal', tabBarIcon: props => <Feather name="list" {...props} />, }} name="Home" component={SelectedGameHome} />, <Screen key="selected-game-activities" options={{ title: 'Atividades', tabBarIcon: props => ( <MaterialCommunityIcons name="trophy-award" {...props} /> ), }} name="Activities" component={ActivitiesRoutes} />, <Screen key="selected-game-profile" options={{ title: 'Perfil', tabBarIcon: props => <FontAwesome name="user-circle-o" {...props} />, }} name="Profile" component={ProfileRoutes} />, ]; export default SelectedGameGameRoutes;
raulrozza/Gametask_Mobile
src/modules/chooseGame/infra/repositories/factories/makeGamesRepository.ts
<filename>src/modules/chooseGame/infra/repositories/factories/makeGamesRepository.ts<gh_stars>0 import IGamesRepository from 'modules/chooseGame/domain/repositories/IGamesRepository'; import GamesRepository from 'modules/chooseGame/infra/repositories/GamesRepository'; export default function makeGamesRepository(): IGamesRepository { return new GamesRepository(); }
raulrozza/Gametask_Mobile
src/modules/chooseGame/infra/controllers/useFetchPlayersController.ts
import makeFetchPlayersService from 'modules/chooseGame/services/factories/makeFetchPlayersService'; import { useCallback, useEffect, useMemo, useState } from 'react'; import { useSessionContext } from 'shared/view/contexts'; import { useToastContext } from 'shared/view/contexts'; import IPlayer from 'shared/domain/entities/IPlayer'; interface UseFetchPlayersController { loading: boolean; players: IPlayer[]; fetchPlayers(): Promise<void>; } export default function useFetchPlayersController( deps?: string, ): UseFetchPlayersController { const [loading, setLoading] = useState(true); const [players, setPlayers] = useState<IPlayer[]>([]); const fetchPlayersService = useMemo(() => makeFetchPlayersService(), []); const session = useSessionContext(); const toast = useToastContext(); const fetchPlayers = useCallback(async () => { setLoading(true); const response = await fetchPlayersService.execute(); setLoading(false); if (response.shouldLogout) return session.logout(); if (response.error) return toast.showError(response.error); if (response.players) setPlayers(response.players); }, [fetchPlayersService, session, toast]); useEffect(() => { fetchPlayers(); }, [deps, fetchPlayers]); return { loading, players, fetchPlayers, }; }
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/pages/Feed/styles.ts
<filename>src/modules/selectedGame/view/pages/Feed/styles.ts import { darken } from 'polished'; import styled from 'styled-components/native'; export const Container = styled.SafeAreaView` flex: 1; background-color: ${({ theme }) => darken(0.05, theme.palette.primary.main)}; `; export const FeedText = { Text: styled.Text` color: ${({ theme }) => theme.palette.primary.contrast}; line-height: 24px; flex-wrap: wrap; `, Name: styled.Text` color: ${({ theme }) => theme.palette.secondary.dark}; font-weight: bold; `, Activity: styled.Text` color: ${({ theme }) => theme.palette.secondary.main}; font-weight: bold; text-transform: uppercase; flex-wrap: wrap; `, Bold: styled.Text` font-weight: bold; `, };
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/pages/PlayerProfile/components/Options/styles.ts
<filename>src/modules/selectedGame/view/pages/PlayerProfile/components/Options/styles.ts import styled, { css } from 'styled-components/native'; // Icons import { Feather } from '@expo/vector-icons'; export const Container = styled.View` width: 100%; `; export const Button = styled.TouchableOpacity` width: 100%; height: 48px; flex-direction: row; justify-content: center; align-items: center; ${({ theme }) => css` background-color: ${theme.palette.primary.dark}; border-top-width: 1px; border-color: ${theme.palette.primary.dark}; `} `; export const Icon = styled(Feather)` color: ${({ theme }) => theme.palette.secondary.light}; font-size: 24px; font-weight: bold; `; export const Text = styled.Text` ${({ theme }) => css` color: ${theme.palette.secondary.light}; font-size: 24px; font-weight: bold; `} `; export const ThinText = styled.Text` ${({ theme }) => css` color: ${theme.palette.secondary.light}; font-size: 18px; `} `;
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/pages/PlayerProfile/components/ProgressBar/index.tsx
<reponame>raulrozza/Gametask_Mobile<filename>src/modules/selectedGame/view/pages/PlayerProfile/components/ProgressBar/index.tsx import React from 'react'; import { BarContainer, Progress } from './styles'; interface ProgressBarProps { progress: number; } const ProgressBar: React.FC<ProgressBarProps> = ({ progress }) => ( <BarContainer> <Progress width={progress * 100} /> </BarContainer> ); export default ProgressBar;
raulrozza/Gametask_Mobile
src/modules/selectedGame/infra/routes/profile.routes.tsx
import React from 'react'; // Navigation import { createStackNavigator } from '@react-navigation/stack'; import AchievementDetails from 'modules/selectedGame/view/pages/AchievementDetails'; import PlayerProfile from 'modules/selectedGame/view/pages/PlayerProfile'; import RequestAchievementUnlock from 'modules/selectedGame/view/pages/RequestAchievementUnlock'; const Stack = createStackNavigator(); const ProfileRoutes: React.FC = () => { return ( <Stack.Navigator screenOptions={{ headerShown: false }}> <Stack.Screen name="playerProfile" component={PlayerProfile} /> <Stack.Screen name="achievementDetails" component={AchievementDetails} /> <Stack.Screen name="requestAchievementUnlock" component={RequestAchievementUnlock} /> </Stack.Navigator> ); }; export default ProfileRoutes;
raulrozza/Gametask_Mobile
src/modules/selectedGame/services/factories/makeRequestActivityService.ts
<reponame>raulrozza/Gametask_Mobile import makeRequestsRepository from 'modules/selectedGame/infra/repositories/factories/makeRequestsRepository'; import RequestActivityService from 'modules/selectedGame/services/RequestActivityService'; export default function makeRequestActivityService(): RequestActivityService { const repository = makeRequestsRepository(); return new RequestActivityService(repository); }
raulrozza/Gametask_Mobile
src/shared/view/contexts/ToastContext/index.ts
<reponame>raulrozza/Gametask_Mobile import useToastContext from 'shared/view/contexts/ToastContext/hooks/useToastContext'; import ToastContext from 'shared/view/contexts/ToastContext/implementations/FlashMessageToastContext'; export { ToastContext, useToastContext };
raulrozza/Gametask_Mobile
src/modules/authentication/view/pages/Login/components/SignupForm/styles.ts
<filename>src/modules/authentication/view/pages/Login/components/SignupForm/styles.ts<gh_stars>0 import { css } from 'styled-components'; export const signInTextStyle = css` color: ${({ theme }) => theme.palette.secondary.contrast}; line-height: 24px; font-size: 16px; `;
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/pages/PlayerProfile/components/TitleSelect/styles.ts
import { Picker } from '@react-native-picker/picker'; import styled, { css } from 'styled-components/native'; export const Container = styled.View` ${({ theme }) => css` background-color: ${theme.palette.secondary.contrast}; margin: 0 auto; width: 80%; height: 52px; padding: ${theme.layout.spacing(3)}; `} `; export const Select = styled(Picker)` ${({ theme }) => css` color: ${theme.palette.secondary.main}; height: 100%; width: 100%; `} `;
raulrozza/Gametask_Mobile
src/modules/chooseGame/services/UpdateUserService.ts
<reponame>raulrozza/Gametask_Mobile import IUpdateUserDTO from 'modules/chooseGame/domain/dtos/IUpdateUserDTO'; import IUsersRepository from 'modules/chooseGame/domain/repositories/IUsersRepository'; interface IExecute { shouldLogout?: boolean; error?: string; } export default class UpdateUserService { constructor(private usersRepository: IUsersRepository) {} public async execute(data: IUpdateUserDTO): Promise<IExecute> { try { await this.usersRepository.update(data); return {}; } catch (error) { return { error: error.message, shouldLogout: error.shouldLogout, }; } } }
raulrozza/Gametask_Mobile
src/modules/selectedGame/services/factories/makeFindPlayerService.ts
import makePlayersRepository from 'modules/selectedGame/infra/repositories/factories/makePlayersRepository'; import FindPlayerService from 'modules/selectedGame/services/FindPlayerService'; export default function makeFindPlayerService(): FindPlayerService { const repository = makePlayersRepository(); return new FindPlayerService(repository); }
raulrozza/Gametask_Mobile
src/modules/chooseGame/view/validation/UserSchema.ts
import * as Yup from 'yup'; const UserSchema = Yup.object().shape({ firstname: Yup.string().required('Você precisa de um nome.'), lastname: Yup.string(), image: Yup.mixed(), }); export default UserSchema;
raulrozza/Gametask_Mobile
src/shared/view/contexts/ToastContext/implementations/FlashMessageToastContext/index.tsx
import React, { useCallback } from 'react'; import FlashMessage, { showMessage } from 'react-native-flash-message'; import IToastContext from 'shared/domain/providers/IToastContext'; import { ToastContextProvider } from 'shared/view/contexts/ToastContext/hooks/useToastContext'; const FlashMessageToastContext: React.FC = ({ children }) => { const showError = useCallback<IToastContext['showError']>( message => showMessage({ message, type: 'danger', }), [], ); const showInfo = useCallback<IToastContext['showInfo']>( message => showMessage({ message, type: 'info', }), [], ); const showSuccess = useCallback<IToastContext['showSuccess']>( message => showMessage({ message, type: 'success', }), [], ); return ( <ToastContextProvider.Provider value={{ showError, showInfo, showSuccess }}> {children} <FlashMessage position="bottom" /> </ToastContextProvider.Provider> ); }; export default FlashMessageToastContext;
raulrozza/Gametask_Mobile
src/modules/selectedGame/infra/controllers/useFindPlayerController.ts
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import makeFindPlayerService from 'modules/selectedGame/services/factories/makeFindPlayerService'; import IPlayer from 'shared/domain/entities/IPlayer'; import { useSessionContext, useToastContext } from 'shared/view/contexts'; interface UseFindPlayerController { loading: boolean; player: IPlayer; getPlayer(id: string): Promise<void>; } export default function useFindPlayerController(): UseFindPlayerController { const [loading, setLoading] = useState(true); const [player, setPlayer] = useState<IPlayer>({} as IPlayer); const mounted = useRef(false); const findPlayersService = useMemo(() => makeFindPlayerService(), []); const session = useSessionContext(); const toast = useToastContext(); const getPlayer = useCallback( async (id: string) => { setLoading(true); const response = await findPlayersService.execute(id); if (!mounted.current) return; setLoading(false); if (response.shouldLogout) return session.logout(); if (response.error) return toast.showError(response.error); if (response.player) setPlayer(response.player); }, [findPlayersService, session, toast], ); useEffect(() => { mounted.current = true; getPlayer(session.playerId); return () => { mounted.current = false; }; }, [getPlayer, session.playerId]); return { loading, player, getPlayer, }; }
raulrozza/Gametask_Mobile
src/modules/selectedGame/domain/dtos/IUpdateTitleDTO.ts
export default interface IUpdateTitleDTO { playerId: string; titleId?: string; }
raulrozza/Gametask_Mobile
src/@types/crypto.d.ts
<reponame>raulrozza/Gametask_Mobile declare module 'react-native-crypto-js' { import { AES, enc } from 'crypto-js'; export default { AES, enc, }; }
raulrozza/Gametask_Mobile
src/modules/authentication/infra/repositories/factories/makeUsersRepository.ts
<filename>src/modules/authentication/infra/repositories/factories/makeUsersRepository.ts<gh_stars>0 import IUsersRepository from 'modules/authentication/domain/repositories/IUsersRepository'; import UsersRepository from 'modules/authentication/infra/repositories/UsersRepository'; export default function makeUsersRepository(): IUsersRepository { const usersRepository = new UsersRepository(); return usersRepository; }
raulrozza/Gametask_Mobile
src/shared/view/components/SubmitButton/index.tsx
<gh_stars>0 import { useFormikContext } from 'formik'; import React, { useCallback } from 'react'; import Button, { ButtonProps } from 'shared/view/components/Button'; const SubmitButton: React.FC<ButtonProps> = ({ onPress, ...props }) => { const formik = useFormikContext(); const handlePress = useCallback(() => { onPress?.(); formik.handleSubmit(); }, []); return <Button {...props} onPress={handlePress} />; }; export default SubmitButton;
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/contexts/PlayerProfileContext/implementations/DefaultPlayerProfileContext/index.tsx
<gh_stars>0 import React from 'react'; import { IPlayerProfileContext, PlayerProfileContextProvider, } from 'modules/selectedGame/view/contexts/PlayerProfileContext/hooks/usePlayerProfileContext'; const DefaultPlayerProfileContext: React.FC<IPlayerProfileContext> = ({ player, children, }) => ( <PlayerProfileContextProvider.Provider value={{ player }}> {children} </PlayerProfileContextProvider.Provider> ); export default DefaultPlayerProfileContext;
raulrozza/Gametask_Mobile
src/modules/selectedGame/domain/dtos/IRequestAchievementDTO.ts
<reponame>raulrozza/Gametask_Mobile export default interface IRequestAchievementDTO { playerId: string; id: string; information: string; }
raulrozza/Gametask_Mobile
src/shared/infra/routes/logged.tsx
<gh_stars>0 import React from 'react'; import ChooseGameLoggedRoutes from 'modules/chooseGame/infra/routes/logged'; import GameRoutes from 'shared/infra/routes/game'; import { useSessionContext } from 'shared/view/contexts'; // Routes const LoggedRoutes: React.FC = () => { const { selectedGame } = useSessionContext(); if (selectedGame) return <GameRoutes />; return <ChooseGameLoggedRoutes />; }; export default LoggedRoutes;
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/pages/Feed/components/index.ts
<reponame>raulrozza/Gametask_Mobile export { default as AchievementFeed } from './AchievementFeed'; export { default as ActivityFeed } from './ActivityFeed'; export { default as EmptyList } from './EmptyList'; export { default as FeedPost } from './FeedPost'; export { default as FeedText } from './FeedText'; export { default as LevelUpFeed } from './LevelUpFeed'; export { default as RankFeed } from './RankFeed'; export { default as RankTag } from './RankTag';
raulrozza/Gametask_Mobile
src/shared/view/helpers/getTextColor.ts
<filename>src/shared/view/helpers/getTextColor.ts import tinyColor from 'tinycolor2'; export default function getTextColor(color?: string): string | undefined { if (!color) return; const colorObj = tinyColor(color); if (colorObj.isLight()) return '#1F1F1F'; return '#FFF'; }
raulrozza/Gametask_Mobile
src/modules/chooseGame/view/pages/Lobby/styles.ts
<filename>src/modules/chooseGame/view/pages/Lobby/styles.ts import styled from 'styled-components/native'; export const Container = styled.View` flex: 1; justify-content: flex-start; background-color: ${({ theme }) => theme.palette.primary.dark}; `; export const Title = styled.Text` color: ${({ theme }) => theme.palette.secondary.main}; text-align: center; margin-bottom: ${({ theme }) => theme.layout.spacing(4)}; font-family: ${({ theme }) => theme.typography.family.title.bold}; font-size: 24px; `;
raulrozza/Gametask_Mobile
src/modules/selectedGame/services/factories/makeRequestAchievementUnlockService.ts
import makeRequestsRepository from 'modules/selectedGame/infra/repositories/factories/makeRequestsRepository'; import RequestAchievementUnlockService from 'modules/selectedGame/services/RequestAchievementUnlockService'; export default function makeRequestAchievementUnlockService(): RequestAchievementUnlockService { const repository = makeRequestsRepository(); return new RequestAchievementUnlockService(repository); }
raulrozza/Gametask_Mobile
src/modules/chooseGame/infra/routes/logged.tsx
import React from 'react'; // Navigation import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; // Pages import GameInvite from 'modules/chooseGame/view/pages/GameInvite'; import Lobby from 'modules/chooseGame/view/pages/Lobby'; import Profile from 'modules/chooseGame/view/pages/Profile'; const Stack = createStackNavigator(); const ChooseGameLoggedRoutes: React.FC = () => { return ( <NavigationContainer> <Stack.Navigator headerMode="none"> <Stack.Screen name="Lobby" component={Lobby} /> <Stack.Screen name="GameInvite" component={GameInvite} /> <Stack.Screen name="Profile" component={Profile} options={{}} /> </Stack.Navigator> </NavigationContainer> ); }; export default ChooseGameLoggedRoutes;
raulrozza/Gametask_Mobile
src/modules/authentication/services/SignUserService.ts
import IUserSignupDTO from 'modules/authentication/domain/dtos/IUserSignupDTO'; import IUsersRepository from 'modules/authentication/domain/repositories/IUsersRepository'; import IUser from 'shared/domain/entities/IUser'; interface IExecute { user?: IUser; error?: string; } export default class SignUserService { constructor(private usersRepository: IUsersRepository) {} public async execute(values: IUserSignupDTO): Promise<IExecute> { try { const user = await this.usersRepository.create(values); return { user }; } catch (error) { console.error(error); return { error: error.message }; } } }
raulrozza/Gametask_Mobile
src/modules/selectedGame/infra/repositories/PlayersRepository.ts
<gh_stars>0 import IPlayersRepository from 'modules/selectedGame/domain/repositories/IPlayersRepository'; import IPlayer from 'shared/domain/entities/IPlayer'; import makeHttpProvider from 'shared/infra/providers/factories/makeHttpProvider'; export default class PlayersRepository implements IPlayersRepository { private httpProvider = makeHttpProvider(); public async updateCurrentTitle(id: string, titleId?: string): Promise<void> { return this.httpProvider.patch(`/players/${id}/titles`, { titleId }); } public async findById(id: string): Promise<IPlayer> { return this.httpProvider.get(`players/${id}`); } }
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/pages/RequestActivity/index.tsx
import React, { useCallback } from 'react'; import { useRoute, RouteProp, useNavigation } from '@react-navigation/native'; import { Formik } from 'formik'; import IActivity from 'modules/selectedGame/domain/entities/IActivity'; import useRequestActivityController from 'modules/selectedGame/infra/controllers/useRequestActivityController'; import RequestActivitySchema from 'modules/selectedGame/view/validation/RequestActivitySchema'; import { Input } from 'shared/view/components'; import { useSessionContext, useToastContext } from 'shared/view/contexts'; import { DateInput, Footer } from './components'; import { Container, Title, Paragraph, Info, Form } from './styles'; type ActivityParams = RouteProp< { requestActivity: { activity: IActivity }; }, 'requestActivity' >; interface IValues { date: string; information: string; } const initialValues: IValues = { date: new Date().toDateString(), information: '', }; const ActivityRegister: React.FC = () => { const { params: { activity }, } = useRoute<ActivityParams>(); const session = useSessionContext(); const toast = useToastContext(); const navigation = useNavigation(); const { loading, requestActivity } = useRequestActivityController(); const onSubmit = useCallback( async (values: IValues) => { const success = await requestActivity({ id: activity.id, information: values.information, completionDate: values.date, playerId: session.playerId, }); if (success) { toast.showSuccess('Atividade registrada!'); return navigation.goBack(); } }, [activity.id, requestActivity, toast, navigation, session.playerId], ); return ( <Container> <Title variant="title">Registrar Atividade</Title> <Title>{activity.name}</Title> <Paragraph> Então você completou esta atividade e quer ganhar seus merecidos{' '} {activity.experience} XP? Preencha as informações abaixo, por favor. </Paragraph> <Info>{activity.description}</Info> <Formik initialValues={initialValues} validationSchema={RequestActivitySchema} onSubmit={onSubmit} > <Form> <Input name="information" placeholder="Como foi sua atividade?" multiline fullWidth /> <DateInput /> <Footer loading={loading} /> </Form> </Formik> </Container> ); }; export default ActivityRegister;
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/pages/PlayerProfile/components/AchievementList/styles.ts
import { Typography } from 'shared/view/components'; import styled from 'styled-components/native'; export const Container = styled.View` width: 80%; border-radius: 5px; padding: ${({ theme }) => theme.layout.spacing(2)}; margin-top: ${({ theme }) => theme.layout.spacing(2)}; margin-bottom: ${({ theme }) => theme.layout.spacing(2)}; background-color: ${({ theme }) => theme.palette.primary.main}; flex-direction: row; flex-wrap: wrap; `; export const Title = styled(Typography)` width: 100%; text-align: center; color: ${({ theme }) => theme.palette.primary.contrast}; font-weight: bold; font-size: 36px; margin: ${({ theme }) => theme.layout.spacing(2, 0)}; `;
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/pages/PlayerProfile/components/BasicLevelInfo/helpers/index.ts
export { default as getPlayerNextLevel } from './getPlayerNextLevel';
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/validation/RequestAchievementUnlockSchema.ts
import * as Yup from 'yup'; const RequestAchievementUnlockSchema = Yup.object().shape({ information: Yup.string().required('Conte como desbloqueou a conquista.'), }); export default RequestAchievementUnlockSchema;
raulrozza/Gametask_Mobile
src/modules/selectedGame/domain/dtos/IRequestActivityDTO.ts
<filename>src/modules/selectedGame/domain/dtos/IRequestActivityDTO.ts export default interface IRequestActivityDTO { id: string; playerId: string; completionDate: string; information: string; }
raulrozza/Gametask_Mobile
src/shared/infra/routes/index.tsx
import React from 'react'; import { StatusBar } from 'react-native'; import { AppLoading } from 'expo'; import LoggedRoutes from 'shared/infra/routes/logged'; import PublicRoutes from 'shared/infra/routes/public'; import { useSessionContext, useThemeContext } from 'shared/view/contexts'; // Routes const Routes: React.FC = () => { const { userToken, loading } = useSessionContext(); const { theme } = useThemeContext(); if (loading) return <AppLoading />; return ( <> <StatusBar barStyle={theme.palette.statusBar} backgroundColor={theme.palette.primary.main} /> {userToken ? <LoggedRoutes /> : <PublicRoutes />} </> ); }; export default Routes;
raulrozza/Gametask_Mobile
src/modules/authentication/view/pages/Login/components/Form/index.ts
import styled, { css } from 'styled-components/native'; interface FormProps { active: boolean; } const Form = styled.ScrollView.attrs(() => ({ contentContainerStyle: { justifyContent: 'center', alignItems: 'center', }, }))<FormProps>` margin: ${({ theme }) => theme.layout.spacing(4, 0)}; ${({ active }) => active ? css` display: flex; ` : css` display: none; `} `; export default Form;
raulrozza/Gametask_Mobile
src/shared/infra/providers/factories/makeJwtProvider.ts
import { IJwtProvider } from 'shared/domain/providers/IJwtProvider'; import JwtDecodeJwtProvider from 'shared/infra/providers/JwtDecodeJwtProvider'; export default function makeJwtProvider(): IJwtProvider { const jwtProvider = new JwtDecodeJwtProvider(); return jwtProvider; }
raulrozza/Gametask_Mobile
src/modules/selectedGame/infra/routes/activities.routes.tsx
<reponame>raulrozza/Gametask_Mobile import React from 'react'; import { createStackNavigator } from '@react-navigation/stack'; // Pages import Activities from 'modules/selectedGame/view/pages/Activities'; import RequestActivity from 'modules/selectedGame/view/pages/RequestActivity'; const Stack = createStackNavigator(); const ActivitiesRoutes: React.FC = () => ( <Stack.Navigator screenOptions={{ headerShown: false }}> <Stack.Screen name="activityList" component={Activities} /> <Stack.Screen name="requestActivity" component={RequestActivity} /> </Stack.Navigator> ); export default ActivitiesRoutes;
raulrozza/Gametask_Mobile
src/modules/selectedGame/domain/repositories/IRequestsRepository.ts
import IRequestAchievementDTO from 'modules/selectedGame/domain/dtos/IRequestAchievementDTO'; import IRequestActivityDTO from 'modules/selectedGame/domain/dtos/IRequestActivityDTO'; export default interface IRequestsRepository { achievement(payload: IRequestAchievementDTO): Promise<void>; activity(payload: IRequestActivityDTO): Promise<void>; }
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/helpers/formatDate.ts
<reponame>raulrozza/Gametask_Mobile<gh_stars>0 const formatDate = (dateString: string): string => { const date = new Date(dateString); const day = date.getDate(); const month = date.getMonth() + 1; return `${day < 10 ? `0${day}` : day}/${ month < 10 ? `0${month}` : month }/${date.getFullYear()}`; }; export default formatDate;
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/pages/RequestActivity/components/index.ts
export { default as DateInput } from './DateInput'; export { default as Footer } from './Footer';
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/pages/Ranking/components/RankingPosition/styles.ts
import { FontAwesome } from '@expo/vector-icons'; import styled, { css } from 'styled-components/native'; import { UserImage } from 'modules/selectedGame/view/components'; interface IconProps { index: number; } const trophyColor = [ '#d4af37', // gold '#C0C0C0', // silver '#b08d57', // bronze ]; export const Container = styled.View` width: 100%; padding: ${({ theme }) => theme.layout.spacing(2)}; border-width: 1px; border-color: ${({ theme }) => theme.palette.primary.dark}; border-radius: 12px; flex-direction: row; margin-bottom: ${({ theme }) => theme.layout.spacing(1)}; align-items: center; `; export const Image = styled(UserImage)` height: 40px; width: 40px; border-radius: 20px; margin-right: ${({ theme }) => theme.layout.spacing(2)}; `; export const PositionBlock = styled.View` ${({ theme }) => css` margin-right: ${theme.layout.spacing(1)}; background-color: ${theme.palette.secondary.light}; padding: ${theme.layout.spacing(0, 2)}; border-radius: ${theme.layout.borderRadius.small}; `} `; export const Text = { Position: styled.Text` ${({ theme }) => css` font-weight: bold; font-size: 16px; color: ${theme.palette.secondary.contrast}; `} `, Name: styled.Text` color: ${({ theme }) => theme.palette.secondary.light}; font-weight: bold; flex-wrap: wrap; font-size: 12px; `, Bold: styled.Text` color: ${({ theme }) => theme.palette.primary.contrast}; font-weight: bold; font-size: 14px; margin-right: ${({ theme }) => theme.layout.spacing(1)}; `, }; export const Icon = styled(FontAwesome)<IconProps>` margin-right: ${({ theme }) => theme.layout.spacing(1)}; font-size: 24px; color: ${({ index }) => trophyColor[index]}; text-shadow: 0px 0px 1px black; `;
raulrozza/Gametask_Mobile
src/modules/selectedGame/infra/repositories/factories/makeAchievementsRepository.ts
<gh_stars>0 import IAchievementsRepository from 'modules/selectedGame/domain/repositories/IAchievementsRepository'; import AchievementsRepository from 'modules/selectedGame/infra/repositories/AchievementsRepository'; export default function makeAchievementsRepository(): IAchievementsRepository { return new AchievementsRepository(); }
raulrozza/Gametask_Mobile
src/modules/chooseGame/infra/repositories/PlayersRepository.ts
<reponame>raulrozza/Gametask_Mobile import IPlayersRepository from 'modules/chooseGame/domain/repositories/IPlayersRepository'; import IPlayer from 'shared/domain/entities/IPlayer'; import makeHttpProvider from 'shared/infra/providers/factories/makeHttpProvider'; export default class PlayersRepository implements IPlayersRepository { private httpProvider = makeHttpProvider(); public async create(gameId: string): Promise<void> { return this.httpProvider.post('players', null, { headers: { 'x-game-id': gameId, }, }); } public async findAll(): Promise<IPlayer[]> { return this.httpProvider.get('players'); } }
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/pages/RequestActivity/components/DateInput/index.tsx
import React, { useCallback, useState } from 'react'; import DatePicker from '@react-native-community/datetimepicker'; import { Container, ErrorField, ErrorFieldText, Picker, Text } from './styles'; import { formatDate } from 'modules/selectedGame/view/helpers'; import { useField } from 'formik'; const DateInput: React.FC = () => { const [showDatePicker, setShowDatePicker] = useState(false); const [{ value }, { error, touched }, { setValue }] = useField('date'); const handleChange = useCallback( (_: unknown, date?: Date) => { setShowDatePicker(false); setValue(date?.toDateString()); }, [setValue], ); return ( <Container> <Picker onTouchEnd={() => { setShowDatePicker(true); }} > <Text date={Boolean(value)}> {value ? formatDate(value) : 'Data da conclusão'} </Text> </Picker> {error && touched && ( <ErrorField> <ErrorFieldText>{error}</ErrorFieldText> </ErrorField> )} {showDatePicker && ( <DatePicker value={value ? ((Date.parse(value) as unknown) as Date) : new Date()} onChange={handleChange} maximumDate={new Date()} /> )} </Container> ); }; export default DateInput;
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/pages/PlayerProfile/components/AchievementList/helpers/index.ts
<reponame>raulrozza/Gametask_Mobile<gh_stars>0 export { default as addObtainedFieldToAchievements } from './addObtainedFieldToAchievements';
raulrozza/Gametask_Mobile
src/modules/chooseGame/domain/dtos/IUpdateUserDTO.ts
<reponame>raulrozza/Gametask_Mobile export default interface IUpdateUserDTO { firstname: string; lastname?: string; image?: string; }
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/pages/Ranking/components/index.ts
export { default as EmptyList } from './EmptyList'; export { default as RankingPosition } from './RankingPosition';
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/pages/PlayerProfile/components/Header/index.tsx
import React from 'react'; import { usePlayerProfileContext } from 'modules/selectedGame/view/contexts'; import { useSessionContext } from 'shared/view/contexts'; import { Container, Name, Title } from './styles'; const Header: React.FC = () => { const { userData } = useSessionContext(); const { player } = usePlayerProfileContext(); return ( <Container> <Name> {player.rank?.name ? `${player.rank.name} ` : ''} {userData.name} {player.currentTitle && ( <Title>{`, ${player.currentTitle.name}`}</Title> )} </Name> </Container> ); }; export default Header;
raulrozza/Gametask_Mobile
src/modules/chooseGame/view/components/index.ts
<gh_stars>0 export { default as GameImage } from './GameImage';
raulrozza/Gametask_Mobile
src/shared/infra/errors/RequestError.ts
<gh_stars>0 import { AxiosError } from 'axios'; import apiCodes from 'config/errors/apiCodes'; interface IErrorResponseDetails { errorCode: number; message: string; } interface GetAxiosMessage { message: string; shouldLogout: boolean; } const isAxiosError = (error: Error | AxiosError): error is AxiosError => (error as AxiosError).isAxiosError; const isAuthenticationError = ( response: AxiosError<IErrorResponseDetails>['response'], ): boolean => response ? response.status === 403 || response.status === 401 || response.data.errorCode === 403 : false; const getAxiosErrorMessage = ( error: AxiosError<IErrorResponseDetails>, ): GetAxiosMessage => { const details = error.response?.data; const shouldLogout = isAuthenticationError(error.response); if (!details) return { message: error.message, shouldLogout }; const errorMessage = apiCodes[details.errorCode]; if (!errorMessage) return { message: error.message, shouldLogout }; return { message: errorMessage, shouldLogout }; }; export default class RequestError extends Error { public shouldLogout: boolean; constructor(error: Error | AxiosError) { if (isAxiosError(error)) { const { message, shouldLogout } = getAxiosErrorMessage(error); super(message); this.shouldLogout = shouldLogout; return; } super(error.message); this.shouldLogout = false; } }
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/pages/PlayerProfile/components/AchievementCard/index.tsx
<gh_stars>0 import React from 'react'; import { useNavigation } from '@react-navigation/native'; import IAchievement from 'modules/selectedGame/domain/entities/IAchievement'; import { Container, Image, Text } from './styles'; interface AchievementCardProps { achievement: IAchievement & { obtained: boolean }; } const AchievementCard: React.FC<AchievementCardProps> = ({ achievement }) => { const { navigate } = useNavigation(); return ( <Container obtained={achievement.obtained || false} onTouchEnd={() => navigate('achievementDetails', { achievement, }) } > <Image image={achievement.image_url} /> <Text>{achievement.name}</Text> </Container> ); }; export default AchievementCard;
raulrozza/Gametask_Mobile
src/modules/chooseGame/view/pages/GameInvite/styles.ts
import styled, { css } from 'styled-components/native'; import GameImage from 'modules/chooseGame/view/components/GameImage'; export const Container = styled.View` flex: 1; justify-content: center; align-items: center; padding: ${({ theme }) => theme.layout.spacing(4)}; background-color: ${({ theme }) => theme.palette.primary.main}; `; export const InviteTitle = { Text: styled.Text` color: ${({ theme }) => theme.palette.primary.contrast}; text-align: center; font-size: 16px; line-height: 22px; margin-bottom: ${({ theme }) => theme.layout.spacing(4)}; `, Inviter: styled.Text` color: ${({ theme }) => theme.palette.secondary.main}; text-transform: uppercase; `, Game: styled.Text` font-weight: bold; color: ${({ theme }) => theme.palette.primary.contrast}; font-size: 18px; `, }; export const GameContainer = { Wrapper: styled.View` background-color: ${({ theme }) => theme.palette.primary.main}; border: 1px solid ${({ theme }) => theme.palette.secondary.main}; border-radius: ${({ theme }) => theme.layout.borderRadius.small}; padding: ${({ theme }) => theme.layout.spacing(8, 4)}; ${'elevation'}: 2; align-items: center; `, Image: styled(GameImage)` height: 96px; width: 96px; border-radius: 48px; margin-bottom: ${({ theme }) => theme.layout.spacing(4)}; `, Description: styled.Text` margin-bottom: ${({ theme }) => theme.layout.spacing(8)}; color: ${({ theme }) => theme.palette.secondary.main}; font-size: 16px; text-align: center; `, buttonTextStyle: css` margin: ${({ theme }) => theme.layout.spacing(0, 2)}; `, };
raulrozza/Gametask_Mobile
src/config/http.ts
<filename>src/config/http.ts import Axios from 'axios'; const instance = Axios.create({ baseURL: process.env.REACT_NATIVE_API_URL, }); instance.defaults.headers = { 'Cache-Control': 'no-cache', Pragma: 'no-cache', Expires: '0', }; export default { instance, };
raulrozza/Gametask_Mobile
src/modules/chooseGame/services/CreatePlayerService.ts
<filename>src/modules/chooseGame/services/CreatePlayerService.ts import IPlayersRepository from 'modules/chooseGame/domain/repositories/IPlayersRepository'; interface IExecute { shouldLogout?: boolean; error?: string; } export default class CreatePlayerService { constructor(private playersRepository: IPlayersRepository) {} public async execute(gameId: string): Promise<IExecute> { try { await this.playersRepository.create(gameId); return {}; } catch (error) { return { error: error.message, shouldLogout: error.shouldLogout, }; } } }
raulrozza/Gametask_Mobile
src/shared/domain/entities/IPlayer.ts
import IGame from 'shared/domain/entities/IGame'; import IRank from 'shared/domain/entities/IRank'; import ITitle from 'shared/domain/entities/ITitle'; import IUser from 'shared/domain/entities/IUser'; export default interface IPlayer { id: string; experience: number; level: number; titles?: ITitle[]; currentTitle?: ITitle; achievements: string[]; rank?: IRank; user: Omit<IUser, 'email'>; game: IGame; }
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/contexts/index.ts
<reponame>raulrozza/Gametask_Mobile<filename>src/modules/selectedGame/view/contexts/index.ts<gh_stars>0 export * from './PlayerProfileContext';
raulrozza/Gametask_Mobile
src/modules/selectedGame/services/FindPlayerService.ts
import IPlayersRepository from 'modules/selectedGame/domain/repositories/IPlayersRepository'; import IPlayer from 'shared/domain/entities/IPlayer'; interface IExecute { player?: IPlayer; shouldLogout?: boolean; error?: string; } export default class FindPlayerService { constructor(private playersRepository: IPlayersRepository) {} public async execute(id: string): Promise<IExecute> { try { const player = await this.playersRepository.findById(id); return { player }; } catch (error) { return { error: error.message, shouldLogout: error.shouldLogout, }; } } }
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/pages/RequestActivity/components/Footer/index.tsx
<reponame>raulrozza/Gametask_Mobile import React from 'react'; import { useNavigation } from '@react-navigation/core'; import { Button, SubmitButton } from 'shared/view/components'; import { Container } from './styles'; interface FooterProps { loading: boolean; } const Footer: React.FC<FooterProps> = ({ loading }) => { const navigation = useNavigation(); return ( <Container> <Button outline onPress={navigation.goBack}> Voltar </Button> <SubmitButton loading={loading}>Confirmar</SubmitButton> </Container> ); }; export default Footer;
raulrozza/Gametask_Mobile
src/config/theme/palette.ts
<filename>src/config/theme/palette.ts interface PaletteOptions { light: string; main: string; dark: string; contrast: string; } type PaletteKeys = 'primary' | 'secondary' | 'error'; const gray = { 0: '#FFFFFF', 100: '#E6E6E6', 200: '#CCCCCC', 300: '#B3B3B3', 400: '#999999', 500: '#808080', 600: '#666666', 700: '#4C4C4C', 800: '#333333', 900: '#1A1A1A', 1000: '#000000', }; type ScalePallete = typeof gray; type ScalePalleteKeys = 'gray'; type StatusBarColors = 'light-content' | 'dark-content' | 'default'; type StatusBarPallete = { statusBar: StatusBarColors; }; const palette: Record<PaletteKeys, PaletteOptions> & Record<ScalePalleteKeys, ScalePallete> & StatusBarPallete = { primary: { light: '#FFFFFF', main: '#FFFFFF', dark: '#E6E6E6', contrast: '#1F1F1F', }, secondary: { light: '#ab39a5', main: '#852c80', dark: '#5f1f5b', contrast: '#F5F5F5', }, error: { light: '#DF2935', main: '#BF252D', dark: '#8E1E20', contrast: '#F5F5F5', }, gray, statusBar: 'dark-content', }; export default palette;
raulrozza/Gametask_Mobile
src/shared/view/contexts/ThemeContext/index.ts
<filename>src/shared/view/contexts/ThemeContext/index.ts import useThemeContext from 'shared/view/contexts/ThemeContext/hooks/useThemeContext'; import ThemeContext from 'shared/view/contexts/ThemeContext/implementations/StyledComponentsThemeContext'; export { ThemeContext, useThemeContext };
raulrozza/Gametask_Mobile
src/modules/authentication/services/factories/makeLogUserService.ts
<filename>src/modules/authentication/services/factories/makeLogUserService.ts import makeUsersRepository from 'modules/authentication/infra/repositories/factories/makeUsersRepository'; import LogUserService from '../LogUserService'; export default function makeLogUserService(): LogUserService { const usersRepository = makeUsersRepository(); const logUserService = new LogUserService(usersRepository); return logUserService; }
raulrozza/Gametask_Mobile
src/modules/selectedGame/infra/repositories/factories/makeRequestsRepository.ts
<filename>src/modules/selectedGame/infra/repositories/factories/makeRequestsRepository.ts import IRequestsRepository from 'modules/selectedGame/domain/repositories/IRequestsRepository'; import RequestsRepository from 'modules/selectedGame/infra/repositories/RequestsRepository'; export default function makeRequestsRepository(): IRequestsRepository { return new RequestsRepository(); }
raulrozza/Gametask_Mobile
src/modules/chooseGame/infra/providers/factories/makeCryptoProvider.ts
<filename>src/modules/chooseGame/infra/providers/factories/makeCryptoProvider.ts<gh_stars>0 import ICryptoProvider from 'modules/chooseGame/domain/providers/ICryptoProvider'; import CryptoJDCryptoProvider from 'modules/chooseGame/infra/providers/CryptoJSCryptoProvider'; export default function makeCryptoProvider(): ICryptoProvider { return new CryptoJDCryptoProvider(); }
raulrozza/Gametask_Mobile
src/modules/chooseGame/services/factories/makeFetchPlayersService.ts
import makePlayersRepository from 'modules/chooseGame/infra/repositories/factories/makePlayersRepository'; import FetchPlayersService from 'modules/chooseGame/services/FetchPlayersService'; export default function makeFetchPlayersService(): FetchPlayersService { const repository = makePlayersRepository(); return new FetchPlayersService(repository); }
raulrozza/Gametask_Mobile
src/shared/view/global/FontLoader.tsx
<reponame>raulrozza/Gametask_Mobile<filename>src/shared/view/global/FontLoader.tsx import React from 'react'; import { AppLoading } from 'expo'; // Fonts import { Roboto_400Regular, Roboto_500Medium, Roboto_700Bold, } from '@expo-google-fonts/roboto'; import { OpenSans_400Regular, OpenSans_700Bold, useFonts, } from '@expo-google-fonts/open-sans'; interface FontLoaderProps { children: React.ReactElement; } const FontLoader: React.FC<FontLoaderProps> = ({ children }) => { const [fontsLoaded] = useFonts({ Roboto_400Regular, Roboto_500Medium, Roboto_700Bold, OpenSans_400Regular, OpenSans_700Bold, }); if (!fontsLoaded) { return <AppLoading />; } return children; }; export default FontLoader;
raulrozza/Gametask_Mobile
src/modules/selectedGame/view/pages/PlayerProfile/components/Options/index.tsx
import React from 'react'; import { MaterialCommunityIcons } from '@expo/vector-icons'; import { useSessionContext } from 'shared/view/contexts'; // Icons import { Button, Container, Icon, ThinText } from './styles'; const Options: React.FC = () => { const { logout, switchGame } = useSessionContext(); return ( <Container> <Button onPress={() => switchGame()}> <Icon as={MaterialCommunityIcons} name="swap-horizontal-bold" /> <ThinText> Trocar Jogo</ThinText> </Button> <Button onPress={logout}> <Icon name="log-out" /> <ThinText> Sair</ThinText> </Button> </Container> ); }; export default Options;
raulrozza/Gametask_Mobile
src/shared/view/contexts/SessionContext/hooks/useSessionContext.ts
import { createContext, useContext } from 'react'; import { isEmpty } from 'lodash'; import ISessionContext from 'shared/domain/providers/ISessionContext'; export const SessionContextProvider = createContext<ISessionContext>( {} as ISessionContext, ); const useSessionContext = (): ISessionContext => { const sessionProvider = useContext(SessionContextProvider); if (isEmpty(sessionProvider)) throw new Error( 'useSessionContext should be called inside a SessionContextProvider', ); return sessionProvider; }; export default useSessionContext;